PackageManagerService.java revision f291e6380028a47317ae2c2f506f80584dd8e86e
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.DELETE_PACKAGES;
20import static android.Manifest.permission.INSTALL_PACKAGES;
21import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS;
22import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
23import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
24import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
25import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
31import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
39import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
40import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
41import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
49import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
54import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
55import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
56import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
57import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
58import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
59import static android.content.pm.PackageManager.INSTALL_INTERNAL;
60import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
65import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
66import static android.content.pm.PackageManager.MATCH_ALL;
67import static android.content.pm.PackageManager.MATCH_ANY_USER;
68import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
70import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
71import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
72import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
73import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
74import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
75import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
76import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
77import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
78import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
79import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
80import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
81import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
82import static android.content.pm.PackageManager.PERMISSION_DENIED;
83import static android.content.pm.PackageManager.PERMISSION_GRANTED;
84import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
85import static android.content.pm.PackageParser.isApkFile;
86import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
87import static android.system.OsConstants.O_CREAT;
88import static android.system.OsConstants.O_RDWR;
89import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
90import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
91import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
92import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
93import static com.android.internal.util.ArrayUtils.appendInt;
94import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
95import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
96import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
97import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
98import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
99import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
100import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
101import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
102import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
103import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
104import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
105
106import android.Manifest;
107import android.annotation.IntDef;
108import android.annotation.NonNull;
109import android.annotation.Nullable;
110import android.app.ActivityManager;
111import android.app.AppOpsManager;
112import android.app.IActivityManager;
113import android.app.ResourcesManager;
114import android.app.admin.IDevicePolicyManager;
115import android.app.admin.SecurityLog;
116import android.app.backup.IBackupManager;
117import android.content.BroadcastReceiver;
118import android.content.ComponentName;
119import android.content.ContentResolver;
120import android.content.Context;
121import android.content.IIntentReceiver;
122import android.content.Intent;
123import android.content.IntentFilter;
124import android.content.IntentSender;
125import android.content.IntentSender.SendIntentException;
126import android.content.ServiceConnection;
127import android.content.pm.ActivityInfo;
128import android.content.pm.ApplicationInfo;
129import android.content.pm.AppsQueryHelper;
130import android.content.pm.AuxiliaryResolveInfo;
131import android.content.pm.ChangedPackages;
132import android.content.pm.FallbackCategoryProvider;
133import android.content.pm.FeatureInfo;
134import android.content.pm.IDexModuleRegisterCallback;
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    @GuardedBy("mProtectedBroadcasts")
925    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
926
927    /** List of packages waiting for verification. */
928    final SparseArray<PackageVerificationState> mPendingVerification
929            = new SparseArray<PackageVerificationState>();
930
931    /** Set of packages associated with each app op permission. */
932    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
933
934    final PackageInstallerService mInstallerService;
935
936    private final PackageDexOptimizer mPackageDexOptimizer;
937    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
938    // is used by other apps).
939    private final DexManager mDexManager;
940
941    private AtomicInteger mNextMoveId = new AtomicInteger();
942    private final MoveCallbacks mMoveCallbacks;
943
944    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
945
946    // Cache of users who need badging.
947    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
948
949    /** Token for keys in mPendingVerification. */
950    private int mPendingVerificationToken = 0;
951
952    volatile boolean mSystemReady;
953    volatile boolean mSafeMode;
954    volatile boolean mHasSystemUidErrors;
955    private volatile boolean mEphemeralAppsDisabled;
956
957    ApplicationInfo mAndroidApplication;
958    final ActivityInfo mResolveActivity = new ActivityInfo();
959    final ResolveInfo mResolveInfo = new ResolveInfo();
960    ComponentName mResolveComponentName;
961    PackageParser.Package mPlatformPackage;
962    ComponentName mCustomResolverComponentName;
963
964    boolean mResolverReplaced = false;
965
966    private final @Nullable ComponentName mIntentFilterVerifierComponent;
967    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
968
969    private int mIntentFilterVerificationToken = 0;
970
971    /** The service connection to the ephemeral resolver */
972    final EphemeralResolverConnection mInstantAppResolverConnection;
973    /** Component used to show resolver settings for Instant Apps */
974    final ComponentName mInstantAppResolverSettingsComponent;
975
976    /** Activity used to install instant applications */
977    ActivityInfo mInstantAppInstallerActivity;
978    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
979
980    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
981            = new SparseArray<IntentFilterVerificationState>();
982
983    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
984
985    // List of packages names to keep cached, even if they are uninstalled for all users
986    private List<String> mKeepUninstalledPackages;
987
988    private UserManagerInternal mUserManagerInternal;
989
990    private DeviceIdleController.LocalService mDeviceIdleController;
991
992    private File mCacheDir;
993
994    private ArraySet<String> mPrivappPermissionsViolations;
995
996    private Future<?> mPrepareAppDataFuture;
997
998    private static class IFVerificationParams {
999        PackageParser.Package pkg;
1000        boolean replacing;
1001        int userId;
1002        int verifierUid;
1003
1004        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1005                int _userId, int _verifierUid) {
1006            pkg = _pkg;
1007            replacing = _replacing;
1008            userId = _userId;
1009            replacing = _replacing;
1010            verifierUid = _verifierUid;
1011        }
1012    }
1013
1014    private interface IntentFilterVerifier<T extends IntentFilter> {
1015        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1016                                               T filter, String packageName);
1017        void startVerifications(int userId);
1018        void receiveVerificationResponse(int verificationId);
1019    }
1020
1021    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1022        private Context mContext;
1023        private ComponentName mIntentFilterVerifierComponent;
1024        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1025
1026        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1027            mContext = context;
1028            mIntentFilterVerifierComponent = verifierComponent;
1029        }
1030
1031        private String getDefaultScheme() {
1032            return IntentFilter.SCHEME_HTTPS;
1033        }
1034
1035        @Override
1036        public void startVerifications(int userId) {
1037            // Launch verifications requests
1038            int count = mCurrentIntentFilterVerifications.size();
1039            for (int n=0; n<count; n++) {
1040                int verificationId = mCurrentIntentFilterVerifications.get(n);
1041                final IntentFilterVerificationState ivs =
1042                        mIntentFilterVerificationStates.get(verificationId);
1043
1044                String packageName = ivs.getPackageName();
1045
1046                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1047                final int filterCount = filters.size();
1048                ArraySet<String> domainsSet = new ArraySet<>();
1049                for (int m=0; m<filterCount; m++) {
1050                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1051                    domainsSet.addAll(filter.getHostsList());
1052                }
1053                synchronized (mPackages) {
1054                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1055                            packageName, domainsSet) != null) {
1056                        scheduleWriteSettingsLocked();
1057                    }
1058                }
1059                sendVerificationRequest(verificationId, ivs);
1060            }
1061            mCurrentIntentFilterVerifications.clear();
1062        }
1063
1064        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1065            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1066            verificationIntent.putExtra(
1067                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1068                    verificationId);
1069            verificationIntent.putExtra(
1070                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1071                    getDefaultScheme());
1072            verificationIntent.putExtra(
1073                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1074                    ivs.getHostsString());
1075            verificationIntent.putExtra(
1076                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1077                    ivs.getPackageName());
1078            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1079            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1080
1081            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1082            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1083                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1084                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1085
1086            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1087            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1088                    "Sending IntentFilter verification broadcast");
1089        }
1090
1091        public void receiveVerificationResponse(int verificationId) {
1092            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1093
1094            final boolean verified = ivs.isVerified();
1095
1096            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1097            final int count = filters.size();
1098            if (DEBUG_DOMAIN_VERIFICATION) {
1099                Slog.i(TAG, "Received verification response " + verificationId
1100                        + " for " + count + " filters, verified=" + verified);
1101            }
1102            for (int n=0; n<count; n++) {
1103                PackageParser.ActivityIntentInfo filter = filters.get(n);
1104                filter.setVerified(verified);
1105
1106                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1107                        + " verified with result:" + verified + " and hosts:"
1108                        + ivs.getHostsString());
1109            }
1110
1111            mIntentFilterVerificationStates.remove(verificationId);
1112
1113            final String packageName = ivs.getPackageName();
1114            IntentFilterVerificationInfo ivi = null;
1115
1116            synchronized (mPackages) {
1117                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1118            }
1119            if (ivi == null) {
1120                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1121                        + verificationId + " packageName:" + packageName);
1122                return;
1123            }
1124            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1125                    "Updating IntentFilterVerificationInfo for package " + packageName
1126                            +" verificationId:" + verificationId);
1127
1128            synchronized (mPackages) {
1129                if (verified) {
1130                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1131                } else {
1132                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1133                }
1134                scheduleWriteSettingsLocked();
1135
1136                final int userId = ivs.getUserId();
1137                if (userId != UserHandle.USER_ALL) {
1138                    final int userStatus =
1139                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1140
1141                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1142                    boolean needUpdate = false;
1143
1144                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1145                    // already been set by the User thru the Disambiguation dialog
1146                    switch (userStatus) {
1147                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1148                            if (verified) {
1149                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1150                            } else {
1151                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1152                            }
1153                            needUpdate = true;
1154                            break;
1155
1156                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1157                            if (verified) {
1158                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1159                                needUpdate = true;
1160                            }
1161                            break;
1162
1163                        default:
1164                            // Nothing to do
1165                    }
1166
1167                    if (needUpdate) {
1168                        mSettings.updateIntentFilterVerificationStatusLPw(
1169                                packageName, updatedStatus, userId);
1170                        scheduleWritePackageRestrictionsLocked(userId);
1171                    }
1172                }
1173            }
1174        }
1175
1176        @Override
1177        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1178                    ActivityIntentInfo filter, String packageName) {
1179            if (!hasValidDomains(filter)) {
1180                return false;
1181            }
1182            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1183            if (ivs == null) {
1184                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1185                        packageName);
1186            }
1187            if (DEBUG_DOMAIN_VERIFICATION) {
1188                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1189            }
1190            ivs.addFilter(filter);
1191            return true;
1192        }
1193
1194        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1195                int userId, int verificationId, String packageName) {
1196            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1197                    verifierUid, userId, packageName);
1198            ivs.setPendingState();
1199            synchronized (mPackages) {
1200                mIntentFilterVerificationStates.append(verificationId, ivs);
1201                mCurrentIntentFilterVerifications.add(verificationId);
1202            }
1203            return ivs;
1204        }
1205    }
1206
1207    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1208        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1209                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1210                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1211    }
1212
1213    // Set of pending broadcasts for aggregating enable/disable of components.
1214    static class PendingPackageBroadcasts {
1215        // for each user id, a map of <package name -> components within that package>
1216        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1217
1218        public PendingPackageBroadcasts() {
1219            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1220        }
1221
1222        public ArrayList<String> get(int userId, String packageName) {
1223            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1224            return packages.get(packageName);
1225        }
1226
1227        public void put(int userId, String packageName, ArrayList<String> components) {
1228            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1229            packages.put(packageName, components);
1230        }
1231
1232        public void remove(int userId, String packageName) {
1233            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1234            if (packages != null) {
1235                packages.remove(packageName);
1236            }
1237        }
1238
1239        public void remove(int userId) {
1240            mUidMap.remove(userId);
1241        }
1242
1243        public int userIdCount() {
1244            return mUidMap.size();
1245        }
1246
1247        public int userIdAt(int n) {
1248            return mUidMap.keyAt(n);
1249        }
1250
1251        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1252            return mUidMap.get(userId);
1253        }
1254
1255        public int size() {
1256            // total number of pending broadcast entries across all userIds
1257            int num = 0;
1258            for (int i = 0; i< mUidMap.size(); i++) {
1259                num += mUidMap.valueAt(i).size();
1260            }
1261            return num;
1262        }
1263
1264        public void clear() {
1265            mUidMap.clear();
1266        }
1267
1268        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1269            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1270            if (map == null) {
1271                map = new ArrayMap<String, ArrayList<String>>();
1272                mUidMap.put(userId, map);
1273            }
1274            return map;
1275        }
1276    }
1277    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1278
1279    // Service Connection to remote media container service to copy
1280    // package uri's from external media onto secure containers
1281    // or internal storage.
1282    private IMediaContainerService mContainerService = null;
1283
1284    static final int SEND_PENDING_BROADCAST = 1;
1285    static final int MCS_BOUND = 3;
1286    static final int END_COPY = 4;
1287    static final int INIT_COPY = 5;
1288    static final int MCS_UNBIND = 6;
1289    static final int START_CLEANING_PACKAGE = 7;
1290    static final int FIND_INSTALL_LOC = 8;
1291    static final int POST_INSTALL = 9;
1292    static final int MCS_RECONNECT = 10;
1293    static final int MCS_GIVE_UP = 11;
1294    static final int UPDATED_MEDIA_STATUS = 12;
1295    static final int WRITE_SETTINGS = 13;
1296    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1297    static final int PACKAGE_VERIFIED = 15;
1298    static final int CHECK_PENDING_VERIFICATION = 16;
1299    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1300    static final int INTENT_FILTER_VERIFIED = 18;
1301    static final int WRITE_PACKAGE_LIST = 19;
1302    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1303
1304    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1305
1306    // Delay time in millisecs
1307    static final int BROADCAST_DELAY = 10 * 1000;
1308
1309    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1310            2 * 60 * 60 * 1000L; /* two hours */
1311
1312    static UserManagerService sUserManager;
1313
1314    // Stores a list of users whose package restrictions file needs to be updated
1315    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1316
1317    final private DefaultContainerConnection mDefContainerConn =
1318            new DefaultContainerConnection();
1319    class DefaultContainerConnection implements ServiceConnection {
1320        public void onServiceConnected(ComponentName name, IBinder service) {
1321            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1322            final IMediaContainerService imcs = IMediaContainerService.Stub
1323                    .asInterface(Binder.allowBlocking(service));
1324            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1325        }
1326
1327        public void onServiceDisconnected(ComponentName name) {
1328            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1329        }
1330    }
1331
1332    // Recordkeeping of restore-after-install operations that are currently in flight
1333    // between the Package Manager and the Backup Manager
1334    static class PostInstallData {
1335        public InstallArgs args;
1336        public PackageInstalledInfo res;
1337
1338        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1339            args = _a;
1340            res = _r;
1341        }
1342    }
1343
1344    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1345    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1346
1347    // XML tags for backup/restore of various bits of state
1348    private static final String TAG_PREFERRED_BACKUP = "pa";
1349    private static final String TAG_DEFAULT_APPS = "da";
1350    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1351
1352    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1353    private static final String TAG_ALL_GRANTS = "rt-grants";
1354    private static final String TAG_GRANT = "grant";
1355    private static final String ATTR_PACKAGE_NAME = "pkg";
1356
1357    private static final String TAG_PERMISSION = "perm";
1358    private static final String ATTR_PERMISSION_NAME = "name";
1359    private static final String ATTR_IS_GRANTED = "g";
1360    private static final String ATTR_USER_SET = "set";
1361    private static final String ATTR_USER_FIXED = "fixed";
1362    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1363
1364    // System/policy permission grants are not backed up
1365    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1366            FLAG_PERMISSION_POLICY_FIXED
1367            | FLAG_PERMISSION_SYSTEM_FIXED
1368            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1369
1370    // And we back up these user-adjusted states
1371    private static final int USER_RUNTIME_GRANT_MASK =
1372            FLAG_PERMISSION_USER_SET
1373            | FLAG_PERMISSION_USER_FIXED
1374            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1375
1376    final @Nullable String mRequiredVerifierPackage;
1377    final @NonNull String mRequiredInstallerPackage;
1378    final @NonNull String mRequiredUninstallerPackage;
1379    final @Nullable String mSetupWizardPackage;
1380    final @Nullable String mStorageManagerPackage;
1381    final @NonNull String mServicesSystemSharedLibraryPackageName;
1382    final @NonNull String mSharedSystemSharedLibraryPackageName;
1383
1384    final boolean mPermissionReviewRequired;
1385
1386    private final PackageUsage mPackageUsage = new PackageUsage();
1387    private final CompilerStats mCompilerStats = new CompilerStats();
1388
1389    class PackageHandler extends Handler {
1390        private boolean mBound = false;
1391        final ArrayList<HandlerParams> mPendingInstalls =
1392            new ArrayList<HandlerParams>();
1393
1394        private boolean connectToService() {
1395            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1396                    " DefaultContainerService");
1397            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1398            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1399            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1400                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1401                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1402                mBound = true;
1403                return true;
1404            }
1405            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1406            return false;
1407        }
1408
1409        private void disconnectService() {
1410            mContainerService = null;
1411            mBound = false;
1412            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1413            mContext.unbindService(mDefContainerConn);
1414            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1415        }
1416
1417        PackageHandler(Looper looper) {
1418            super(looper);
1419        }
1420
1421        public void handleMessage(Message msg) {
1422            try {
1423                doHandleMessage(msg);
1424            } finally {
1425                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1426            }
1427        }
1428
1429        void doHandleMessage(Message msg) {
1430            switch (msg.what) {
1431                case INIT_COPY: {
1432                    HandlerParams params = (HandlerParams) msg.obj;
1433                    int idx = mPendingInstalls.size();
1434                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1435                    // If a bind was already initiated we dont really
1436                    // need to do anything. The pending install
1437                    // will be processed later on.
1438                    if (!mBound) {
1439                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1440                                System.identityHashCode(mHandler));
1441                        // If this is the only one pending we might
1442                        // have to bind to the service again.
1443                        if (!connectToService()) {
1444                            Slog.e(TAG, "Failed to bind to media container service");
1445                            params.serviceError();
1446                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1447                                    System.identityHashCode(mHandler));
1448                            if (params.traceMethod != null) {
1449                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1450                                        params.traceCookie);
1451                            }
1452                            return;
1453                        } else {
1454                            // Once we bind to the service, the first
1455                            // pending request will be processed.
1456                            mPendingInstalls.add(idx, params);
1457                        }
1458                    } else {
1459                        mPendingInstalls.add(idx, params);
1460                        // Already bound to the service. Just make
1461                        // sure we trigger off processing the first request.
1462                        if (idx == 0) {
1463                            mHandler.sendEmptyMessage(MCS_BOUND);
1464                        }
1465                    }
1466                    break;
1467                }
1468                case MCS_BOUND: {
1469                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1470                    if (msg.obj != null) {
1471                        mContainerService = (IMediaContainerService) msg.obj;
1472                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1473                                System.identityHashCode(mHandler));
1474                    }
1475                    if (mContainerService == null) {
1476                        if (!mBound) {
1477                            // Something seriously wrong since we are not bound and we are not
1478                            // waiting for connection. Bail out.
1479                            Slog.e(TAG, "Cannot bind to media container service");
1480                            for (HandlerParams params : mPendingInstalls) {
1481                                // Indicate service bind error
1482                                params.serviceError();
1483                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1484                                        System.identityHashCode(params));
1485                                if (params.traceMethod != null) {
1486                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1487                                            params.traceMethod, params.traceCookie);
1488                                }
1489                                return;
1490                            }
1491                            mPendingInstalls.clear();
1492                        } else {
1493                            Slog.w(TAG, "Waiting to connect to media container service");
1494                        }
1495                    } else if (mPendingInstalls.size() > 0) {
1496                        HandlerParams params = mPendingInstalls.get(0);
1497                        if (params != null) {
1498                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1499                                    System.identityHashCode(params));
1500                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1501                            if (params.startCopy()) {
1502                                // We are done...  look for more work or to
1503                                // go idle.
1504                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1505                                        "Checking for more work or unbind...");
1506                                // Delete pending install
1507                                if (mPendingInstalls.size() > 0) {
1508                                    mPendingInstalls.remove(0);
1509                                }
1510                                if (mPendingInstalls.size() == 0) {
1511                                    if (mBound) {
1512                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1513                                                "Posting delayed MCS_UNBIND");
1514                                        removeMessages(MCS_UNBIND);
1515                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1516                                        // Unbind after a little delay, to avoid
1517                                        // continual thrashing.
1518                                        sendMessageDelayed(ubmsg, 10000);
1519                                    }
1520                                } else {
1521                                    // There are more pending requests in queue.
1522                                    // Just post MCS_BOUND message to trigger processing
1523                                    // of next pending install.
1524                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1525                                            "Posting MCS_BOUND for next work");
1526                                    mHandler.sendEmptyMessage(MCS_BOUND);
1527                                }
1528                            }
1529                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1530                        }
1531                    } else {
1532                        // Should never happen ideally.
1533                        Slog.w(TAG, "Empty queue");
1534                    }
1535                    break;
1536                }
1537                case MCS_RECONNECT: {
1538                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1539                    if (mPendingInstalls.size() > 0) {
1540                        if (mBound) {
1541                            disconnectService();
1542                        }
1543                        if (!connectToService()) {
1544                            Slog.e(TAG, "Failed to bind to media container service");
1545                            for (HandlerParams params : mPendingInstalls) {
1546                                // Indicate service bind error
1547                                params.serviceError();
1548                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1549                                        System.identityHashCode(params));
1550                            }
1551                            mPendingInstalls.clear();
1552                        }
1553                    }
1554                    break;
1555                }
1556                case MCS_UNBIND: {
1557                    // If there is no actual work left, then time to unbind.
1558                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1559
1560                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1561                        if (mBound) {
1562                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1563
1564                            disconnectService();
1565                        }
1566                    } else if (mPendingInstalls.size() > 0) {
1567                        // There are more pending requests in queue.
1568                        // Just post MCS_BOUND message to trigger processing
1569                        // of next pending install.
1570                        mHandler.sendEmptyMessage(MCS_BOUND);
1571                    }
1572
1573                    break;
1574                }
1575                case MCS_GIVE_UP: {
1576                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1577                    HandlerParams params = mPendingInstalls.remove(0);
1578                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1579                            System.identityHashCode(params));
1580                    break;
1581                }
1582                case SEND_PENDING_BROADCAST: {
1583                    String packages[];
1584                    ArrayList<String> components[];
1585                    int size = 0;
1586                    int uids[];
1587                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1588                    synchronized (mPackages) {
1589                        if (mPendingBroadcasts == null) {
1590                            return;
1591                        }
1592                        size = mPendingBroadcasts.size();
1593                        if (size <= 0) {
1594                            // Nothing to be done. Just return
1595                            return;
1596                        }
1597                        packages = new String[size];
1598                        components = new ArrayList[size];
1599                        uids = new int[size];
1600                        int i = 0;  // filling out the above arrays
1601
1602                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1603                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1604                            Iterator<Map.Entry<String, ArrayList<String>>> it
1605                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1606                                            .entrySet().iterator();
1607                            while (it.hasNext() && i < size) {
1608                                Map.Entry<String, ArrayList<String>> ent = it.next();
1609                                packages[i] = ent.getKey();
1610                                components[i] = ent.getValue();
1611                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1612                                uids[i] = (ps != null)
1613                                        ? UserHandle.getUid(packageUserId, ps.appId)
1614                                        : -1;
1615                                i++;
1616                            }
1617                        }
1618                        size = i;
1619                        mPendingBroadcasts.clear();
1620                    }
1621                    // Send broadcasts
1622                    for (int i = 0; i < size; i++) {
1623                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1624                    }
1625                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1626                    break;
1627                }
1628                case START_CLEANING_PACKAGE: {
1629                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1630                    final String packageName = (String)msg.obj;
1631                    final int userId = msg.arg1;
1632                    final boolean andCode = msg.arg2 != 0;
1633                    synchronized (mPackages) {
1634                        if (userId == UserHandle.USER_ALL) {
1635                            int[] users = sUserManager.getUserIds();
1636                            for (int user : users) {
1637                                mSettings.addPackageToCleanLPw(
1638                                        new PackageCleanItem(user, packageName, andCode));
1639                            }
1640                        } else {
1641                            mSettings.addPackageToCleanLPw(
1642                                    new PackageCleanItem(userId, packageName, andCode));
1643                        }
1644                    }
1645                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1646                    startCleaningPackages();
1647                } break;
1648                case POST_INSTALL: {
1649                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1650
1651                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1652                    final boolean didRestore = (msg.arg2 != 0);
1653                    mRunningInstalls.delete(msg.arg1);
1654
1655                    if (data != null) {
1656                        InstallArgs args = data.args;
1657                        PackageInstalledInfo parentRes = data.res;
1658
1659                        final boolean grantPermissions = (args.installFlags
1660                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1661                        final boolean killApp = (args.installFlags
1662                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1663                        final String[] grantedPermissions = args.installGrantPermissions;
1664
1665                        // Handle the parent package
1666                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1667                                grantedPermissions, didRestore, args.installerPackageName,
1668                                args.observer);
1669
1670                        // Handle the child packages
1671                        final int childCount = (parentRes.addedChildPackages != null)
1672                                ? parentRes.addedChildPackages.size() : 0;
1673                        for (int i = 0; i < childCount; i++) {
1674                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1675                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1676                                    grantedPermissions, false, args.installerPackageName,
1677                                    args.observer);
1678                        }
1679
1680                        // Log tracing if needed
1681                        if (args.traceMethod != null) {
1682                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1683                                    args.traceCookie);
1684                        }
1685                    } else {
1686                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1687                    }
1688
1689                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1690                } break;
1691                case UPDATED_MEDIA_STATUS: {
1692                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1693                    boolean reportStatus = msg.arg1 == 1;
1694                    boolean doGc = msg.arg2 == 1;
1695                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1696                    if (doGc) {
1697                        // Force a gc to clear up stale containers.
1698                        Runtime.getRuntime().gc();
1699                    }
1700                    if (msg.obj != null) {
1701                        @SuppressWarnings("unchecked")
1702                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1703                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1704                        // Unload containers
1705                        unloadAllContainers(args);
1706                    }
1707                    if (reportStatus) {
1708                        try {
1709                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1710                                    "Invoking StorageManagerService call back");
1711                            PackageHelper.getStorageManager().finishMediaUpdate();
1712                        } catch (RemoteException e) {
1713                            Log.e(TAG, "StorageManagerService not running?");
1714                        }
1715                    }
1716                } break;
1717                case WRITE_SETTINGS: {
1718                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1719                    synchronized (mPackages) {
1720                        removeMessages(WRITE_SETTINGS);
1721                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1722                        mSettings.writeLPr();
1723                        mDirtyUsers.clear();
1724                    }
1725                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1726                } break;
1727                case WRITE_PACKAGE_RESTRICTIONS: {
1728                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1729                    synchronized (mPackages) {
1730                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1731                        for (int userId : mDirtyUsers) {
1732                            mSettings.writePackageRestrictionsLPr(userId);
1733                        }
1734                        mDirtyUsers.clear();
1735                    }
1736                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1737                } break;
1738                case WRITE_PACKAGE_LIST: {
1739                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1740                    synchronized (mPackages) {
1741                        removeMessages(WRITE_PACKAGE_LIST);
1742                        mSettings.writePackageListLPr(msg.arg1);
1743                    }
1744                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1745                } break;
1746                case CHECK_PENDING_VERIFICATION: {
1747                    final int verificationId = msg.arg1;
1748                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1749
1750                    if ((state != null) && !state.timeoutExtended()) {
1751                        final InstallArgs args = state.getInstallArgs();
1752                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1753
1754                        Slog.i(TAG, "Verification timed out for " + originUri);
1755                        mPendingVerification.remove(verificationId);
1756
1757                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1758
1759                        final UserHandle user = args.getUser();
1760                        if (getDefaultVerificationResponse(user)
1761                                == PackageManager.VERIFICATION_ALLOW) {
1762                            Slog.i(TAG, "Continuing with installation of " + originUri);
1763                            state.setVerifierResponse(Binder.getCallingUid(),
1764                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1765                            broadcastPackageVerified(verificationId, originUri,
1766                                    PackageManager.VERIFICATION_ALLOW, user);
1767                            try {
1768                                ret = args.copyApk(mContainerService, true);
1769                            } catch (RemoteException e) {
1770                                Slog.e(TAG, "Could not contact the ContainerService");
1771                            }
1772                        } else {
1773                            broadcastPackageVerified(verificationId, originUri,
1774                                    PackageManager.VERIFICATION_REJECT, user);
1775                        }
1776
1777                        Trace.asyncTraceEnd(
1778                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1779
1780                        processPendingInstall(args, ret);
1781                        mHandler.sendEmptyMessage(MCS_UNBIND);
1782                    }
1783                    break;
1784                }
1785                case PACKAGE_VERIFIED: {
1786                    final int verificationId = msg.arg1;
1787
1788                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1789                    if (state == null) {
1790                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1791                        break;
1792                    }
1793
1794                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1795
1796                    state.setVerifierResponse(response.callerUid, response.code);
1797
1798                    if (state.isVerificationComplete()) {
1799                        mPendingVerification.remove(verificationId);
1800
1801                        final InstallArgs args = state.getInstallArgs();
1802                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1803
1804                        int ret;
1805                        if (state.isInstallAllowed()) {
1806                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1807                            broadcastPackageVerified(verificationId, originUri,
1808                                    response.code, state.getInstallArgs().getUser());
1809                            try {
1810                                ret = args.copyApk(mContainerService, true);
1811                            } catch (RemoteException e) {
1812                                Slog.e(TAG, "Could not contact the ContainerService");
1813                            }
1814                        } else {
1815                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1816                        }
1817
1818                        Trace.asyncTraceEnd(
1819                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1820
1821                        processPendingInstall(args, ret);
1822                        mHandler.sendEmptyMessage(MCS_UNBIND);
1823                    }
1824
1825                    break;
1826                }
1827                case START_INTENT_FILTER_VERIFICATIONS: {
1828                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1829                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1830                            params.replacing, params.pkg);
1831                    break;
1832                }
1833                case INTENT_FILTER_VERIFIED: {
1834                    final int verificationId = msg.arg1;
1835
1836                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1837                            verificationId);
1838                    if (state == null) {
1839                        Slog.w(TAG, "Invalid IntentFilter verification token "
1840                                + verificationId + " received");
1841                        break;
1842                    }
1843
1844                    final int userId = state.getUserId();
1845
1846                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1847                            "Processing IntentFilter verification with token:"
1848                            + verificationId + " and userId:" + userId);
1849
1850                    final IntentFilterVerificationResponse response =
1851                            (IntentFilterVerificationResponse) msg.obj;
1852
1853                    state.setVerifierResponse(response.callerUid, response.code);
1854
1855                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1856                            "IntentFilter verification with token:" + verificationId
1857                            + " and userId:" + userId
1858                            + " is settings verifier response with response code:"
1859                            + response.code);
1860
1861                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1862                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1863                                + response.getFailedDomainsString());
1864                    }
1865
1866                    if (state.isVerificationComplete()) {
1867                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1868                    } else {
1869                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1870                                "IntentFilter verification with token:" + verificationId
1871                                + " was not said to be complete");
1872                    }
1873
1874                    break;
1875                }
1876                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1877                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1878                            mInstantAppResolverConnection,
1879                            (InstantAppRequest) msg.obj,
1880                            mInstantAppInstallerActivity,
1881                            mHandler);
1882                }
1883            }
1884        }
1885    }
1886
1887    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1888            boolean killApp, String[] grantedPermissions,
1889            boolean launchedForRestore, String installerPackage,
1890            IPackageInstallObserver2 installObserver) {
1891        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1892            // Send the removed broadcasts
1893            if (res.removedInfo != null) {
1894                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1895            }
1896
1897            // Now that we successfully installed the package, grant runtime
1898            // permissions if requested before broadcasting the install. Also
1899            // for legacy apps in permission review mode we clear the permission
1900            // review flag which is used to emulate runtime permissions for
1901            // legacy apps.
1902            if (grantPermissions) {
1903                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1904            }
1905
1906            final boolean update = res.removedInfo != null
1907                    && res.removedInfo.removedPackage != null;
1908            final String origInstallerPackageName = res.removedInfo != null
1909                    ? res.removedInfo.installerPackageName : null;
1910
1911            // If this is the first time we have child packages for a disabled privileged
1912            // app that had no children, we grant requested runtime permissions to the new
1913            // children if the parent on the system image had them already granted.
1914            if (res.pkg.parentPackage != null) {
1915                synchronized (mPackages) {
1916                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1917                }
1918            }
1919
1920            synchronized (mPackages) {
1921                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1922            }
1923
1924            final String packageName = res.pkg.applicationInfo.packageName;
1925
1926            // Determine the set of users who are adding this package for
1927            // the first time vs. those who are seeing an update.
1928            int[] firstUsers = EMPTY_INT_ARRAY;
1929            int[] updateUsers = EMPTY_INT_ARRAY;
1930            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1931            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1932            for (int newUser : res.newUsers) {
1933                if (ps.getInstantApp(newUser)) {
1934                    continue;
1935                }
1936                if (allNewUsers) {
1937                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1938                    continue;
1939                }
1940                boolean isNew = true;
1941                for (int origUser : res.origUsers) {
1942                    if (origUser == newUser) {
1943                        isNew = false;
1944                        break;
1945                    }
1946                }
1947                if (isNew) {
1948                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1949                } else {
1950                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1951                }
1952            }
1953
1954            // Send installed broadcasts if the package is not a static shared lib.
1955            if (res.pkg.staticSharedLibName == null) {
1956                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1957
1958                // Send added for users that see the package for the first time
1959                // sendPackageAddedForNewUsers also deals with system apps
1960                int appId = UserHandle.getAppId(res.uid);
1961                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1962                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1963
1964                // Send added for users that don't see the package for the first time
1965                Bundle extras = new Bundle(1);
1966                extras.putInt(Intent.EXTRA_UID, res.uid);
1967                if (update) {
1968                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1969                }
1970                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1971                        extras, 0 /*flags*/,
1972                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
1973                if (origInstallerPackageName != null) {
1974                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1975                            extras, 0 /*flags*/,
1976                            origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1977                }
1978
1979                // Send replaced for users that don't see the package for the first time
1980                if (update) {
1981                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1982                            packageName, extras, 0 /*flags*/,
1983                            null /*targetPackage*/, null /*finishedReceiver*/,
1984                            updateUsers);
1985                    if (origInstallerPackageName != null) {
1986                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
1987                                extras, 0 /*flags*/,
1988                                origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1989                    }
1990                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1991                            null /*package*/, null /*extras*/, 0 /*flags*/,
1992                            packageName /*targetPackage*/,
1993                            null /*finishedReceiver*/, updateUsers);
1994                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1995                    // First-install and we did a restore, so we're responsible for the
1996                    // first-launch broadcast.
1997                    if (DEBUG_BACKUP) {
1998                        Slog.i(TAG, "Post-restore of " + packageName
1999                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2000                    }
2001                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2002                }
2003
2004                // Send broadcast package appeared if forward locked/external for all users
2005                // treat asec-hosted packages like removable media on upgrade
2006                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2007                    if (DEBUG_INSTALL) {
2008                        Slog.i(TAG, "upgrading pkg " + res.pkg
2009                                + " is ASEC-hosted -> AVAILABLE");
2010                    }
2011                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2012                    ArrayList<String> pkgList = new ArrayList<>(1);
2013                    pkgList.add(packageName);
2014                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2015                }
2016            }
2017
2018            // Work that needs to happen on first install within each user
2019            if (firstUsers != null && firstUsers.length > 0) {
2020                synchronized (mPackages) {
2021                    for (int userId : firstUsers) {
2022                        // If this app is a browser and it's newly-installed for some
2023                        // users, clear any default-browser state in those users. The
2024                        // app's nature doesn't depend on the user, so we can just check
2025                        // its browser nature in any user and generalize.
2026                        if (packageIsBrowser(packageName, userId)) {
2027                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2028                        }
2029
2030                        // We may also need to apply pending (restored) runtime
2031                        // permission grants within these users.
2032                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2033                    }
2034                }
2035            }
2036
2037            // Log current value of "unknown sources" setting
2038            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2039                    getUnknownSourcesSettings());
2040
2041            // Remove the replaced package's older resources safely now
2042            // We delete after a gc for applications  on sdcard.
2043            if (res.removedInfo != null && res.removedInfo.args != null) {
2044                Runtime.getRuntime().gc();
2045                synchronized (mInstallLock) {
2046                    res.removedInfo.args.doPostDeleteLI(true);
2047                }
2048            } else {
2049                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2050                // and not block here.
2051                VMRuntime.getRuntime().requestConcurrentGC();
2052            }
2053
2054            // Notify DexManager that the package was installed for new users.
2055            // The updated users should already be indexed and the package code paths
2056            // should not change.
2057            // Don't notify the manager for ephemeral apps as they are not expected to
2058            // survive long enough to benefit of background optimizations.
2059            for (int userId : firstUsers) {
2060                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2061                // There's a race currently where some install events may interleave with an uninstall.
2062                // This can lead to package info being null (b/36642664).
2063                if (info != null) {
2064                    mDexManager.notifyPackageInstalled(info, userId);
2065                }
2066            }
2067        }
2068
2069        // If someone is watching installs - notify them
2070        if (installObserver != null) {
2071            try {
2072                Bundle extras = extrasForInstallResult(res);
2073                installObserver.onPackageInstalled(res.name, res.returnCode,
2074                        res.returnMsg, extras);
2075            } catch (RemoteException e) {
2076                Slog.i(TAG, "Observer no longer exists.");
2077            }
2078        }
2079    }
2080
2081    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2082            PackageParser.Package pkg) {
2083        if (pkg.parentPackage == null) {
2084            return;
2085        }
2086        if (pkg.requestedPermissions == null) {
2087            return;
2088        }
2089        final PackageSetting disabledSysParentPs = mSettings
2090                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2091        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2092                || !disabledSysParentPs.isPrivileged()
2093                || (disabledSysParentPs.childPackageNames != null
2094                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2095            return;
2096        }
2097        final int[] allUserIds = sUserManager.getUserIds();
2098        final int permCount = pkg.requestedPermissions.size();
2099        for (int i = 0; i < permCount; i++) {
2100            String permission = pkg.requestedPermissions.get(i);
2101            BasePermission bp = mSettings.mPermissions.get(permission);
2102            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2103                continue;
2104            }
2105            for (int userId : allUserIds) {
2106                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2107                        permission, userId)) {
2108                    grantRuntimePermission(pkg.packageName, permission, userId);
2109                }
2110            }
2111        }
2112    }
2113
2114    private StorageEventListener mStorageListener = new StorageEventListener() {
2115        @Override
2116        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2117            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2118                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2119                    final String volumeUuid = vol.getFsUuid();
2120
2121                    // Clean up any users or apps that were removed or recreated
2122                    // while this volume was missing
2123                    sUserManager.reconcileUsers(volumeUuid);
2124                    reconcileApps(volumeUuid);
2125
2126                    // Clean up any install sessions that expired or were
2127                    // cancelled while this volume was missing
2128                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2129
2130                    loadPrivatePackages(vol);
2131
2132                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2133                    unloadPrivatePackages(vol);
2134                }
2135            }
2136
2137            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2138                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2139                    updateExternalMediaStatus(true, false);
2140                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2141                    updateExternalMediaStatus(false, false);
2142                }
2143            }
2144        }
2145
2146        @Override
2147        public void onVolumeForgotten(String fsUuid) {
2148            if (TextUtils.isEmpty(fsUuid)) {
2149                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2150                return;
2151            }
2152
2153            // Remove any apps installed on the forgotten volume
2154            synchronized (mPackages) {
2155                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2156                for (PackageSetting ps : packages) {
2157                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2158                    deletePackageVersioned(new VersionedPackage(ps.name,
2159                            PackageManager.VERSION_CODE_HIGHEST),
2160                            new LegacyPackageDeleteObserver(null).getBinder(),
2161                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2162                    // Try very hard to release any references to this package
2163                    // so we don't risk the system server being killed due to
2164                    // open FDs
2165                    AttributeCache.instance().removePackage(ps.name);
2166                }
2167
2168                mSettings.onVolumeForgotten(fsUuid);
2169                mSettings.writeLPr();
2170            }
2171        }
2172    };
2173
2174    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2175            String[] grantedPermissions) {
2176        for (int userId : userIds) {
2177            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2178        }
2179    }
2180
2181    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2182            String[] grantedPermissions) {
2183        PackageSetting ps = (PackageSetting) pkg.mExtras;
2184        if (ps == null) {
2185            return;
2186        }
2187
2188        PermissionsState permissionsState = ps.getPermissionsState();
2189
2190        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2191                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2192
2193        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2194                >= Build.VERSION_CODES.M;
2195
2196        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2197
2198        for (String permission : pkg.requestedPermissions) {
2199            final BasePermission bp;
2200            synchronized (mPackages) {
2201                bp = mSettings.mPermissions.get(permission);
2202            }
2203            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2204                    && (!instantApp || bp.isInstant())
2205                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2206                    && (grantedPermissions == null
2207                           || ArrayUtils.contains(grantedPermissions, permission))) {
2208                final int flags = permissionsState.getPermissionFlags(permission, userId);
2209                if (supportsRuntimePermissions) {
2210                    // Installer cannot change immutable permissions.
2211                    if ((flags & immutableFlags) == 0) {
2212                        grantRuntimePermission(pkg.packageName, permission, userId);
2213                    }
2214                } else if (mPermissionReviewRequired) {
2215                    // In permission review mode we clear the review flag when we
2216                    // are asked to install the app with all permissions granted.
2217                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2218                        updatePermissionFlags(permission, pkg.packageName,
2219                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2220                    }
2221                }
2222            }
2223        }
2224    }
2225
2226    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2227        Bundle extras = null;
2228        switch (res.returnCode) {
2229            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2230                extras = new Bundle();
2231                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2232                        res.origPermission);
2233                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2234                        res.origPackage);
2235                break;
2236            }
2237            case PackageManager.INSTALL_SUCCEEDED: {
2238                extras = new Bundle();
2239                extras.putBoolean(Intent.EXTRA_REPLACING,
2240                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2241                break;
2242            }
2243        }
2244        return extras;
2245    }
2246
2247    void scheduleWriteSettingsLocked() {
2248        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2249            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2250        }
2251    }
2252
2253    void scheduleWritePackageListLocked(int userId) {
2254        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2255            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2256            msg.arg1 = userId;
2257            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2258        }
2259    }
2260
2261    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2262        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2263        scheduleWritePackageRestrictionsLocked(userId);
2264    }
2265
2266    void scheduleWritePackageRestrictionsLocked(int userId) {
2267        final int[] userIds = (userId == UserHandle.USER_ALL)
2268                ? sUserManager.getUserIds() : new int[]{userId};
2269        for (int nextUserId : userIds) {
2270            if (!sUserManager.exists(nextUserId)) return;
2271            mDirtyUsers.add(nextUserId);
2272            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2273                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2274            }
2275        }
2276    }
2277
2278    public static PackageManagerService main(Context context, Installer installer,
2279            boolean factoryTest, boolean onlyCore) {
2280        // Self-check for initial settings.
2281        PackageManagerServiceCompilerMapping.checkProperties();
2282
2283        PackageManagerService m = new PackageManagerService(context, installer,
2284                factoryTest, onlyCore);
2285        m.enableSystemUserPackages();
2286        ServiceManager.addService("package", m);
2287        return m;
2288    }
2289
2290    private void enableSystemUserPackages() {
2291        if (!UserManager.isSplitSystemUser()) {
2292            return;
2293        }
2294        // For system user, enable apps based on the following conditions:
2295        // - app is whitelisted or belong to one of these groups:
2296        //   -- system app which has no launcher icons
2297        //   -- system app which has INTERACT_ACROSS_USERS permission
2298        //   -- system IME app
2299        // - app is not in the blacklist
2300        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2301        Set<String> enableApps = new ArraySet<>();
2302        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2303                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2304                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2305        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2306        enableApps.addAll(wlApps);
2307        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2308                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2309        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2310        enableApps.removeAll(blApps);
2311        Log.i(TAG, "Applications installed for system user: " + enableApps);
2312        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2313                UserHandle.SYSTEM);
2314        final int allAppsSize = allAps.size();
2315        synchronized (mPackages) {
2316            for (int i = 0; i < allAppsSize; i++) {
2317                String pName = allAps.get(i);
2318                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2319                // Should not happen, but we shouldn't be failing if it does
2320                if (pkgSetting == null) {
2321                    continue;
2322                }
2323                boolean install = enableApps.contains(pName);
2324                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2325                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2326                            + " for system user");
2327                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2328                }
2329            }
2330            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2331        }
2332    }
2333
2334    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2335        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2336                Context.DISPLAY_SERVICE);
2337        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2338    }
2339
2340    /**
2341     * Requests that files preopted on a secondary system partition be copied to the data partition
2342     * if possible.  Note that the actual copying of the files is accomplished by init for security
2343     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2344     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2345     */
2346    private static void requestCopyPreoptedFiles() {
2347        final int WAIT_TIME_MS = 100;
2348        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2349        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2350            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2351            // We will wait for up to 100 seconds.
2352            final long timeStart = SystemClock.uptimeMillis();
2353            final long timeEnd = timeStart + 100 * 1000;
2354            long timeNow = timeStart;
2355            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2356                try {
2357                    Thread.sleep(WAIT_TIME_MS);
2358                } catch (InterruptedException e) {
2359                    // Do nothing
2360                }
2361                timeNow = SystemClock.uptimeMillis();
2362                if (timeNow > timeEnd) {
2363                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2364                    Slog.wtf(TAG, "cppreopt did not finish!");
2365                    break;
2366                }
2367            }
2368
2369            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2370        }
2371    }
2372
2373    public PackageManagerService(Context context, Installer installer,
2374            boolean factoryTest, boolean onlyCore) {
2375        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2376        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2377        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2378                SystemClock.uptimeMillis());
2379
2380        if (mSdkVersion <= 0) {
2381            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2382        }
2383
2384        mContext = context;
2385
2386        mPermissionReviewRequired = context.getResources().getBoolean(
2387                R.bool.config_permissionReviewRequired);
2388
2389        mFactoryTest = factoryTest;
2390        mOnlyCore = onlyCore;
2391        mMetrics = new DisplayMetrics();
2392        mSettings = new Settings(mPackages);
2393        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2394                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2395        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2396                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2397        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2398                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2399        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2400                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2401        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2402                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2403        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2404                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2405
2406        String separateProcesses = SystemProperties.get("debug.separate_processes");
2407        if (separateProcesses != null && separateProcesses.length() > 0) {
2408            if ("*".equals(separateProcesses)) {
2409                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2410                mSeparateProcesses = null;
2411                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2412            } else {
2413                mDefParseFlags = 0;
2414                mSeparateProcesses = separateProcesses.split(",");
2415                Slog.w(TAG, "Running with debug.separate_processes: "
2416                        + separateProcesses);
2417            }
2418        } else {
2419            mDefParseFlags = 0;
2420            mSeparateProcesses = null;
2421        }
2422
2423        mInstaller = installer;
2424        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2425                "*dexopt*");
2426        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2427        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2428
2429        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2430                FgThread.get().getLooper());
2431
2432        getDefaultDisplayMetrics(context, mMetrics);
2433
2434        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2435        SystemConfig systemConfig = SystemConfig.getInstance();
2436        mGlobalGids = systemConfig.getGlobalGids();
2437        mSystemPermissions = systemConfig.getSystemPermissions();
2438        mAvailableFeatures = systemConfig.getAvailableFeatures();
2439        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2440
2441        mProtectedPackages = new ProtectedPackages(mContext);
2442
2443        synchronized (mInstallLock) {
2444        // writer
2445        synchronized (mPackages) {
2446            mHandlerThread = new ServiceThread(TAG,
2447                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2448            mHandlerThread.start();
2449            mHandler = new PackageHandler(mHandlerThread.getLooper());
2450            mProcessLoggingHandler = new ProcessLoggingHandler();
2451            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2452
2453            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2454            mInstantAppRegistry = new InstantAppRegistry(this);
2455
2456            File dataDir = Environment.getDataDirectory();
2457            mAppInstallDir = new File(dataDir, "app");
2458            mAppLib32InstallDir = new File(dataDir, "app-lib");
2459            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2460            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2461            sUserManager = new UserManagerService(context, this,
2462                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2463
2464            // Propagate permission configuration in to package manager.
2465            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2466                    = systemConfig.getPermissions();
2467            for (int i=0; i<permConfig.size(); i++) {
2468                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2469                BasePermission bp = mSettings.mPermissions.get(perm.name);
2470                if (bp == null) {
2471                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2472                    mSettings.mPermissions.put(perm.name, bp);
2473                }
2474                if (perm.gids != null) {
2475                    bp.setGids(perm.gids, perm.perUser);
2476                }
2477            }
2478
2479            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2480            final int builtInLibCount = libConfig.size();
2481            for (int i = 0; i < builtInLibCount; i++) {
2482                String name = libConfig.keyAt(i);
2483                String path = libConfig.valueAt(i);
2484                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2485                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2486            }
2487
2488            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2489
2490            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2491            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2492            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2493
2494            // Clean up orphaned packages for which the code path doesn't exist
2495            // and they are an update to a system app - caused by bug/32321269
2496            final int packageSettingCount = mSettings.mPackages.size();
2497            for (int i = packageSettingCount - 1; i >= 0; i--) {
2498                PackageSetting ps = mSettings.mPackages.valueAt(i);
2499                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2500                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2501                    mSettings.mPackages.removeAt(i);
2502                    mSettings.enableSystemPackageLPw(ps.name);
2503                }
2504            }
2505
2506            if (mFirstBoot) {
2507                requestCopyPreoptedFiles();
2508            }
2509
2510            String customResolverActivity = Resources.getSystem().getString(
2511                    R.string.config_customResolverActivity);
2512            if (TextUtils.isEmpty(customResolverActivity)) {
2513                customResolverActivity = null;
2514            } else {
2515                mCustomResolverComponentName = ComponentName.unflattenFromString(
2516                        customResolverActivity);
2517            }
2518
2519            long startTime = SystemClock.uptimeMillis();
2520
2521            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2522                    startTime);
2523
2524            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2525            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2526
2527            if (bootClassPath == null) {
2528                Slog.w(TAG, "No BOOTCLASSPATH found!");
2529            }
2530
2531            if (systemServerClassPath == null) {
2532                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2533            }
2534
2535            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2536
2537            final VersionInfo ver = mSettings.getInternalVersion();
2538            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2539            if (mIsUpgrade) {
2540                logCriticalInfo(Log.INFO,
2541                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2542            }
2543
2544            // when upgrading from pre-M, promote system app permissions from install to runtime
2545            mPromoteSystemApps =
2546                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2547
2548            // When upgrading from pre-N, we need to handle package extraction like first boot,
2549            // as there is no profiling data available.
2550            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2551
2552            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2553
2554            // save off the names of pre-existing system packages prior to scanning; we don't
2555            // want to automatically grant runtime permissions for new system apps
2556            if (mPromoteSystemApps) {
2557                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2558                while (pkgSettingIter.hasNext()) {
2559                    PackageSetting ps = pkgSettingIter.next();
2560                    if (isSystemApp(ps)) {
2561                        mExistingSystemPackages.add(ps.name);
2562                    }
2563                }
2564            }
2565
2566            mCacheDir = preparePackageParserCache(mIsUpgrade);
2567
2568            // Set flag to monitor and not change apk file paths when
2569            // scanning install directories.
2570            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2571
2572            if (mIsUpgrade || mFirstBoot) {
2573                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2574            }
2575
2576            // Collect vendor overlay packages. (Do this before scanning any apps.)
2577            // For security and version matching reason, only consider
2578            // overlay packages if they reside in the right directory.
2579            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2580                    | PackageParser.PARSE_IS_SYSTEM
2581                    | PackageParser.PARSE_IS_SYSTEM_DIR
2582                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2583
2584            mParallelPackageParserCallback.findStaticOverlayPackages();
2585
2586            // Find base frameworks (resource packages without code).
2587            scanDirTracedLI(frameworkDir, mDefParseFlags
2588                    | PackageParser.PARSE_IS_SYSTEM
2589                    | PackageParser.PARSE_IS_SYSTEM_DIR
2590                    | PackageParser.PARSE_IS_PRIVILEGED,
2591                    scanFlags | SCAN_NO_DEX, 0);
2592
2593            // Collected privileged system packages.
2594            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2595            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2596                    | PackageParser.PARSE_IS_SYSTEM
2597                    | PackageParser.PARSE_IS_SYSTEM_DIR
2598                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2599
2600            // Collect ordinary system packages.
2601            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2602            scanDirTracedLI(systemAppDir, mDefParseFlags
2603                    | PackageParser.PARSE_IS_SYSTEM
2604                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2605
2606            // Collect all vendor packages.
2607            File vendorAppDir = new File("/vendor/app");
2608            try {
2609                vendorAppDir = vendorAppDir.getCanonicalFile();
2610            } catch (IOException e) {
2611                // failed to look up canonical path, continue with original one
2612            }
2613            scanDirTracedLI(vendorAppDir, mDefParseFlags
2614                    | PackageParser.PARSE_IS_SYSTEM
2615                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2616
2617            // Collect all OEM packages.
2618            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2619            scanDirTracedLI(oemAppDir, mDefParseFlags
2620                    | PackageParser.PARSE_IS_SYSTEM
2621                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2622
2623            // Prune any system packages that no longer exist.
2624            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2625            if (!mOnlyCore) {
2626                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2627                while (psit.hasNext()) {
2628                    PackageSetting ps = psit.next();
2629
2630                    /*
2631                     * If this is not a system app, it can't be a
2632                     * disable system app.
2633                     */
2634                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2635                        continue;
2636                    }
2637
2638                    /*
2639                     * If the package is scanned, it's not erased.
2640                     */
2641                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2642                    if (scannedPkg != null) {
2643                        /*
2644                         * If the system app is both scanned and in the
2645                         * disabled packages list, then it must have been
2646                         * added via OTA. Remove it from the currently
2647                         * scanned package so the previously user-installed
2648                         * application can be scanned.
2649                         */
2650                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2651                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2652                                    + ps.name + "; removing system app.  Last known codePath="
2653                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2654                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2655                                    + scannedPkg.mVersionCode);
2656                            removePackageLI(scannedPkg, true);
2657                            mExpectingBetter.put(ps.name, ps.codePath);
2658                        }
2659
2660                        continue;
2661                    }
2662
2663                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2664                        psit.remove();
2665                        logCriticalInfo(Log.WARN, "System package " + ps.name
2666                                + " no longer exists; it's data will be wiped");
2667                        // Actual deletion of code and data will be handled by later
2668                        // reconciliation step
2669                    } else {
2670                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2671                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2672                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2673                        }
2674                    }
2675                }
2676            }
2677
2678            //look for any incomplete package installations
2679            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2680            for (int i = 0; i < deletePkgsList.size(); i++) {
2681                // Actual deletion of code and data will be handled by later
2682                // reconciliation step
2683                final String packageName = deletePkgsList.get(i).name;
2684                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2685                synchronized (mPackages) {
2686                    mSettings.removePackageLPw(packageName);
2687                }
2688            }
2689
2690            //delete tmp files
2691            deleteTempPackageFiles();
2692
2693            // Remove any shared userIDs that have no associated packages
2694            mSettings.pruneSharedUsersLPw();
2695
2696            if (!mOnlyCore) {
2697                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2698                        SystemClock.uptimeMillis());
2699                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2700
2701                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2702                        | PackageParser.PARSE_FORWARD_LOCK,
2703                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2704
2705                /**
2706                 * Remove disable package settings for any updated system
2707                 * apps that were removed via an OTA. If they're not a
2708                 * previously-updated app, remove them completely.
2709                 * Otherwise, just revoke their system-level permissions.
2710                 */
2711                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2712                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2713                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2714
2715                    String msg;
2716                    if (deletedPkg == null) {
2717                        msg = "Updated system package " + deletedAppName
2718                                + " no longer exists; it's data will be wiped";
2719                        // Actual deletion of code and data will be handled by later
2720                        // reconciliation step
2721                    } else {
2722                        msg = "Updated system app + " + deletedAppName
2723                                + " no longer present; removing system privileges for "
2724                                + deletedAppName;
2725
2726                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2727
2728                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2729                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2730                    }
2731                    logCriticalInfo(Log.WARN, msg);
2732                }
2733
2734                /**
2735                 * Make sure all system apps that we expected to appear on
2736                 * the userdata partition actually showed up. If they never
2737                 * appeared, crawl back and revive the system version.
2738                 */
2739                for (int i = 0; i < mExpectingBetter.size(); i++) {
2740                    final String packageName = mExpectingBetter.keyAt(i);
2741                    if (!mPackages.containsKey(packageName)) {
2742                        final File scanFile = mExpectingBetter.valueAt(i);
2743
2744                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2745                                + " but never showed up; reverting to system");
2746
2747                        int reparseFlags = mDefParseFlags;
2748                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2749                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2750                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2751                                    | PackageParser.PARSE_IS_PRIVILEGED;
2752                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2753                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2754                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2755                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2756                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2757                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2758                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2759                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2760                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2761                        } else {
2762                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2763                            continue;
2764                        }
2765
2766                        mSettings.enableSystemPackageLPw(packageName);
2767
2768                        try {
2769                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2770                        } catch (PackageManagerException e) {
2771                            Slog.e(TAG, "Failed to parse original system package: "
2772                                    + e.getMessage());
2773                        }
2774                    }
2775                }
2776            }
2777            mExpectingBetter.clear();
2778
2779            // Resolve the storage manager.
2780            mStorageManagerPackage = getStorageManagerPackageName();
2781
2782            // Resolve protected action filters. Only the setup wizard is allowed to
2783            // have a high priority filter for these actions.
2784            mSetupWizardPackage = getSetupWizardPackageName();
2785            if (mProtectedFilters.size() > 0) {
2786                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2787                    Slog.i(TAG, "No setup wizard;"
2788                        + " All protected intents capped to priority 0");
2789                }
2790                for (ActivityIntentInfo filter : mProtectedFilters) {
2791                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2792                        if (DEBUG_FILTERS) {
2793                            Slog.i(TAG, "Found setup wizard;"
2794                                + " allow priority " + filter.getPriority() + ";"
2795                                + " package: " + filter.activity.info.packageName
2796                                + " activity: " + filter.activity.className
2797                                + " priority: " + filter.getPriority());
2798                        }
2799                        // skip setup wizard; allow it to keep the high priority filter
2800                        continue;
2801                    }
2802                    if (DEBUG_FILTERS) {
2803                        Slog.i(TAG, "Protected action; cap priority to 0;"
2804                                + " package: " + filter.activity.info.packageName
2805                                + " activity: " + filter.activity.className
2806                                + " origPrio: " + filter.getPriority());
2807                    }
2808                    filter.setPriority(0);
2809                }
2810            }
2811            mDeferProtectedFilters = false;
2812            mProtectedFilters.clear();
2813
2814            // Now that we know all of the shared libraries, update all clients to have
2815            // the correct library paths.
2816            updateAllSharedLibrariesLPw(null);
2817
2818            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2819                // NOTE: We ignore potential failures here during a system scan (like
2820                // the rest of the commands above) because there's precious little we
2821                // can do about it. A settings error is reported, though.
2822                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2823            }
2824
2825            // Now that we know all the packages we are keeping,
2826            // read and update their last usage times.
2827            mPackageUsage.read(mPackages);
2828            mCompilerStats.read();
2829
2830            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2831                    SystemClock.uptimeMillis());
2832            Slog.i(TAG, "Time to scan packages: "
2833                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2834                    + " seconds");
2835
2836            // If the platform SDK has changed since the last time we booted,
2837            // we need to re-grant app permission to catch any new ones that
2838            // appear.  This is really a hack, and means that apps can in some
2839            // cases get permissions that the user didn't initially explicitly
2840            // allow...  it would be nice to have some better way to handle
2841            // this situation.
2842            int updateFlags = UPDATE_PERMISSIONS_ALL;
2843            if (ver.sdkVersion != mSdkVersion) {
2844                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2845                        + mSdkVersion + "; regranting permissions for internal storage");
2846                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2847            }
2848            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2849            ver.sdkVersion = mSdkVersion;
2850
2851            // If this is the first boot or an update from pre-M, and it is a normal
2852            // boot, then we need to initialize the default preferred apps across
2853            // all defined users.
2854            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2855                for (UserInfo user : sUserManager.getUsers(true)) {
2856                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2857                    applyFactoryDefaultBrowserLPw(user.id);
2858                    primeDomainVerificationsLPw(user.id);
2859                }
2860            }
2861
2862            // Prepare storage for system user really early during boot,
2863            // since core system apps like SettingsProvider and SystemUI
2864            // can't wait for user to start
2865            final int storageFlags;
2866            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2867                storageFlags = StorageManager.FLAG_STORAGE_DE;
2868            } else {
2869                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2870            }
2871            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2872                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2873                    true /* onlyCoreApps */);
2874            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2875                BootTimingsTraceLog traceLog = new BootTimingsTraceLog("SystemServerTimingAsync",
2876                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2877                traceLog.traceBegin("AppDataFixup");
2878                try {
2879                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2880                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2881                } catch (InstallerException e) {
2882                    Slog.w(TAG, "Trouble fixing GIDs", e);
2883                }
2884                traceLog.traceEnd();
2885
2886                traceLog.traceBegin("AppDataPrepare");
2887                if (deferPackages == null || deferPackages.isEmpty()) {
2888                    return;
2889                }
2890                int count = 0;
2891                for (String pkgName : deferPackages) {
2892                    PackageParser.Package pkg = null;
2893                    synchronized (mPackages) {
2894                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2895                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2896                            pkg = ps.pkg;
2897                        }
2898                    }
2899                    if (pkg != null) {
2900                        synchronized (mInstallLock) {
2901                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2902                                    true /* maybeMigrateAppData */);
2903                        }
2904                        count++;
2905                    }
2906                }
2907                traceLog.traceEnd();
2908                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2909            }, "prepareAppData");
2910
2911            // If this is first boot after an OTA, and a normal boot, then
2912            // we need to clear code cache directories.
2913            // Note that we do *not* clear the application profiles. These remain valid
2914            // across OTAs and are used to drive profile verification (post OTA) and
2915            // profile compilation (without waiting to collect a fresh set of profiles).
2916            if (mIsUpgrade && !onlyCore) {
2917                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2918                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2919                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2920                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2921                        // No apps are running this early, so no need to freeze
2922                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2923                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2924                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2925                    }
2926                }
2927                ver.fingerprint = Build.FINGERPRINT;
2928            }
2929
2930            checkDefaultBrowser();
2931
2932            // clear only after permissions and other defaults have been updated
2933            mExistingSystemPackages.clear();
2934            mPromoteSystemApps = false;
2935
2936            // All the changes are done during package scanning.
2937            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2938
2939            // can downgrade to reader
2940            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2941            mSettings.writeLPr();
2942            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2943            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2944                    SystemClock.uptimeMillis());
2945
2946            if (!mOnlyCore) {
2947                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2948                mRequiredInstallerPackage = getRequiredInstallerLPr();
2949                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2950                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2951                if (mIntentFilterVerifierComponent != null) {
2952                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2953                            mIntentFilterVerifierComponent);
2954                } else {
2955                    mIntentFilterVerifier = null;
2956                }
2957                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2958                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2959                        SharedLibraryInfo.VERSION_UNDEFINED);
2960                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2961                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2962                        SharedLibraryInfo.VERSION_UNDEFINED);
2963            } else {
2964                mRequiredVerifierPackage = null;
2965                mRequiredInstallerPackage = null;
2966                mRequiredUninstallerPackage = null;
2967                mIntentFilterVerifierComponent = null;
2968                mIntentFilterVerifier = null;
2969                mServicesSystemSharedLibraryPackageName = null;
2970                mSharedSystemSharedLibraryPackageName = null;
2971            }
2972
2973            mInstallerService = new PackageInstallerService(context, this);
2974            final Pair<ComponentName, String> instantAppResolverComponent =
2975                    getInstantAppResolverLPr();
2976            if (instantAppResolverComponent != null) {
2977                if (DEBUG_EPHEMERAL) {
2978                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
2979                }
2980                mInstantAppResolverConnection = new EphemeralResolverConnection(
2981                        mContext, instantAppResolverComponent.first,
2982                        instantAppResolverComponent.second);
2983                mInstantAppResolverSettingsComponent =
2984                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
2985            } else {
2986                mInstantAppResolverConnection = null;
2987                mInstantAppResolverSettingsComponent = null;
2988            }
2989            updateInstantAppInstallerLocked(null);
2990
2991            // Read and update the usage of dex files.
2992            // Do this at the end of PM init so that all the packages have their
2993            // data directory reconciled.
2994            // At this point we know the code paths of the packages, so we can validate
2995            // the disk file and build the internal cache.
2996            // The usage file is expected to be small so loading and verifying it
2997            // should take a fairly small time compare to the other activities (e.g. package
2998            // scanning).
2999            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3000            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3001            for (int userId : currentUserIds) {
3002                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3003            }
3004            mDexManager.load(userPackages);
3005        } // synchronized (mPackages)
3006        } // synchronized (mInstallLock)
3007
3008        // Now after opening every single application zip, make sure they
3009        // are all flushed.  Not really needed, but keeps things nice and
3010        // tidy.
3011        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3012        Runtime.getRuntime().gc();
3013        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3014
3015        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3016        FallbackCategoryProvider.loadFallbacks();
3017        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3018
3019        // The initial scanning above does many calls into installd while
3020        // holding the mPackages lock, but we're mostly interested in yelling
3021        // once we have a booted system.
3022        mInstaller.setWarnIfHeld(mPackages);
3023
3024        // Expose private service for system components to use.
3025        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3026        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3027    }
3028
3029    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3030        // we're only interested in updating the installer appliction when 1) it's not
3031        // already set or 2) the modified package is the installer
3032        if (mInstantAppInstallerActivity != null
3033                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3034                        .equals(modifiedPackage)) {
3035            return;
3036        }
3037        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3038    }
3039
3040    private static File preparePackageParserCache(boolean isUpgrade) {
3041        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3042            return null;
3043        }
3044
3045        // Disable package parsing on eng builds to allow for faster incremental development.
3046        if ("eng".equals(Build.TYPE)) {
3047            return null;
3048        }
3049
3050        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3051            Slog.i(TAG, "Disabling package parser cache due to system property.");
3052            return null;
3053        }
3054
3055        // The base directory for the package parser cache lives under /data/system/.
3056        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3057                "package_cache");
3058        if (cacheBaseDir == null) {
3059            return null;
3060        }
3061
3062        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3063        // This also serves to "GC" unused entries when the package cache version changes (which
3064        // can only happen during upgrades).
3065        if (isUpgrade) {
3066            FileUtils.deleteContents(cacheBaseDir);
3067        }
3068
3069
3070        // Return the versioned package cache directory. This is something like
3071        // "/data/system/package_cache/1"
3072        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3073
3074        // The following is a workaround to aid development on non-numbered userdebug
3075        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3076        // the system partition is newer.
3077        //
3078        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3079        // that starts with "eng." to signify that this is an engineering build and not
3080        // destined for release.
3081        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3082            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3083
3084            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3085            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3086            // in general and should not be used for production changes. In this specific case,
3087            // we know that they will work.
3088            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3089            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3090                FileUtils.deleteContents(cacheBaseDir);
3091                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3092            }
3093        }
3094
3095        return cacheDir;
3096    }
3097
3098    @Override
3099    public boolean isFirstBoot() {
3100        // allow instant applications
3101        return mFirstBoot;
3102    }
3103
3104    @Override
3105    public boolean isOnlyCoreApps() {
3106        // allow instant applications
3107        return mOnlyCore;
3108    }
3109
3110    @Override
3111    public boolean isUpgrade() {
3112        // allow instant applications
3113        return mIsUpgrade;
3114    }
3115
3116    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3117        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3118
3119        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3120                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3121                UserHandle.USER_SYSTEM);
3122        if (matches.size() == 1) {
3123            return matches.get(0).getComponentInfo().packageName;
3124        } else if (matches.size() == 0) {
3125            Log.e(TAG, "There should probably be a verifier, but, none were found");
3126            return null;
3127        }
3128        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3129    }
3130
3131    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3132        synchronized (mPackages) {
3133            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3134            if (libraryEntry == null) {
3135                throw new IllegalStateException("Missing required shared library:" + name);
3136            }
3137            return libraryEntry.apk;
3138        }
3139    }
3140
3141    private @NonNull String getRequiredInstallerLPr() {
3142        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3143        intent.addCategory(Intent.CATEGORY_DEFAULT);
3144        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3145
3146        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3147                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3148                UserHandle.USER_SYSTEM);
3149        if (matches.size() == 1) {
3150            ResolveInfo resolveInfo = matches.get(0);
3151            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3152                throw new RuntimeException("The installer must be a privileged app");
3153            }
3154            return matches.get(0).getComponentInfo().packageName;
3155        } else {
3156            throw new RuntimeException("There must be exactly one installer; found " + matches);
3157        }
3158    }
3159
3160    private @NonNull String getRequiredUninstallerLPr() {
3161        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3162        intent.addCategory(Intent.CATEGORY_DEFAULT);
3163        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3164
3165        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3166                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3167                UserHandle.USER_SYSTEM);
3168        if (resolveInfo == null ||
3169                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3170            throw new RuntimeException("There must be exactly one uninstaller; found "
3171                    + resolveInfo);
3172        }
3173        return resolveInfo.getComponentInfo().packageName;
3174    }
3175
3176    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3177        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3178
3179        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3180                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3181                UserHandle.USER_SYSTEM);
3182        ResolveInfo best = null;
3183        final int N = matches.size();
3184        for (int i = 0; i < N; i++) {
3185            final ResolveInfo cur = matches.get(i);
3186            final String packageName = cur.getComponentInfo().packageName;
3187            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3188                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3189                continue;
3190            }
3191
3192            if (best == null || cur.priority > best.priority) {
3193                best = cur;
3194            }
3195        }
3196
3197        if (best != null) {
3198            return best.getComponentInfo().getComponentName();
3199        }
3200        Slog.w(TAG, "Intent filter verifier not found");
3201        return null;
3202    }
3203
3204    @Override
3205    public @Nullable ComponentName getInstantAppResolverComponent() {
3206        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3207            return null;
3208        }
3209        synchronized (mPackages) {
3210            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3211            if (instantAppResolver == null) {
3212                return null;
3213            }
3214            return instantAppResolver.first;
3215        }
3216    }
3217
3218    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3219        final String[] packageArray =
3220                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3221        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3222            if (DEBUG_EPHEMERAL) {
3223                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3224            }
3225            return null;
3226        }
3227
3228        final int callingUid = Binder.getCallingUid();
3229        final int resolveFlags =
3230                MATCH_DIRECT_BOOT_AWARE
3231                | MATCH_DIRECT_BOOT_UNAWARE
3232                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3233        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3234        final Intent resolverIntent = new Intent(actionName);
3235        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3236                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3237        // temporarily look for the old action
3238        if (resolvers.size() == 0) {
3239            if (DEBUG_EPHEMERAL) {
3240                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3241            }
3242            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3243            resolverIntent.setAction(actionName);
3244            resolvers = queryIntentServicesInternal(resolverIntent, null,
3245                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3246        }
3247        final int N = resolvers.size();
3248        if (N == 0) {
3249            if (DEBUG_EPHEMERAL) {
3250                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3251            }
3252            return null;
3253        }
3254
3255        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3256        for (int i = 0; i < N; i++) {
3257            final ResolveInfo info = resolvers.get(i);
3258
3259            if (info.serviceInfo == null) {
3260                continue;
3261            }
3262
3263            final String packageName = info.serviceInfo.packageName;
3264            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3265                if (DEBUG_EPHEMERAL) {
3266                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3267                            + " pkg: " + packageName + ", info:" + info);
3268                }
3269                continue;
3270            }
3271
3272            if (DEBUG_EPHEMERAL) {
3273                Slog.v(TAG, "Ephemeral resolver found;"
3274                        + " pkg: " + packageName + ", info:" + info);
3275            }
3276            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3277        }
3278        if (DEBUG_EPHEMERAL) {
3279            Slog.v(TAG, "Ephemeral resolver NOT found");
3280        }
3281        return null;
3282    }
3283
3284    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3285        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3286        intent.addCategory(Intent.CATEGORY_DEFAULT);
3287        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3288
3289        final int resolveFlags =
3290                MATCH_DIRECT_BOOT_AWARE
3291                | MATCH_DIRECT_BOOT_UNAWARE
3292                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3293        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3294                resolveFlags, UserHandle.USER_SYSTEM);
3295        // temporarily look for the old action
3296        if (matches.isEmpty()) {
3297            if (DEBUG_EPHEMERAL) {
3298                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3299            }
3300            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3301            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3302                    resolveFlags, UserHandle.USER_SYSTEM);
3303        }
3304        Iterator<ResolveInfo> iter = matches.iterator();
3305        while (iter.hasNext()) {
3306            final ResolveInfo rInfo = iter.next();
3307            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3308            if (ps != null) {
3309                final PermissionsState permissionsState = ps.getPermissionsState();
3310                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3311                    continue;
3312                }
3313            }
3314            iter.remove();
3315        }
3316        if (matches.size() == 0) {
3317            return null;
3318        } else if (matches.size() == 1) {
3319            return (ActivityInfo) matches.get(0).getComponentInfo();
3320        } else {
3321            throw new RuntimeException(
3322                    "There must be at most one ephemeral installer; found " + matches);
3323        }
3324    }
3325
3326    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3327            @NonNull ComponentName resolver) {
3328        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3329                .addCategory(Intent.CATEGORY_DEFAULT)
3330                .setPackage(resolver.getPackageName());
3331        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3332        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3333                UserHandle.USER_SYSTEM);
3334        // temporarily look for the old action
3335        if (matches.isEmpty()) {
3336            if (DEBUG_EPHEMERAL) {
3337                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3338            }
3339            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3340            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3341                    UserHandle.USER_SYSTEM);
3342        }
3343        if (matches.isEmpty()) {
3344            return null;
3345        }
3346        return matches.get(0).getComponentInfo().getComponentName();
3347    }
3348
3349    private void primeDomainVerificationsLPw(int userId) {
3350        if (DEBUG_DOMAIN_VERIFICATION) {
3351            Slog.d(TAG, "Priming domain verifications in user " + userId);
3352        }
3353
3354        SystemConfig systemConfig = SystemConfig.getInstance();
3355        ArraySet<String> packages = systemConfig.getLinkedApps();
3356
3357        for (String packageName : packages) {
3358            PackageParser.Package pkg = mPackages.get(packageName);
3359            if (pkg != null) {
3360                if (!pkg.isSystemApp()) {
3361                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3362                    continue;
3363                }
3364
3365                ArraySet<String> domains = null;
3366                for (PackageParser.Activity a : pkg.activities) {
3367                    for (ActivityIntentInfo filter : a.intents) {
3368                        if (hasValidDomains(filter)) {
3369                            if (domains == null) {
3370                                domains = new ArraySet<String>();
3371                            }
3372                            domains.addAll(filter.getHostsList());
3373                        }
3374                    }
3375                }
3376
3377                if (domains != null && domains.size() > 0) {
3378                    if (DEBUG_DOMAIN_VERIFICATION) {
3379                        Slog.v(TAG, "      + " + packageName);
3380                    }
3381                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3382                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3383                    // and then 'always' in the per-user state actually used for intent resolution.
3384                    final IntentFilterVerificationInfo ivi;
3385                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3386                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3387                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3388                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3389                } else {
3390                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3391                            + "' does not handle web links");
3392                }
3393            } else {
3394                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3395            }
3396        }
3397
3398        scheduleWritePackageRestrictionsLocked(userId);
3399        scheduleWriteSettingsLocked();
3400    }
3401
3402    private void applyFactoryDefaultBrowserLPw(int userId) {
3403        // The default browser app's package name is stored in a string resource,
3404        // with a product-specific overlay used for vendor customization.
3405        String browserPkg = mContext.getResources().getString(
3406                com.android.internal.R.string.default_browser);
3407        if (!TextUtils.isEmpty(browserPkg)) {
3408            // non-empty string => required to be a known package
3409            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3410            if (ps == null) {
3411                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3412                browserPkg = null;
3413            } else {
3414                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3415            }
3416        }
3417
3418        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3419        // default.  If there's more than one, just leave everything alone.
3420        if (browserPkg == null) {
3421            calculateDefaultBrowserLPw(userId);
3422        }
3423    }
3424
3425    private void calculateDefaultBrowserLPw(int userId) {
3426        List<String> allBrowsers = resolveAllBrowserApps(userId);
3427        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3428        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3429    }
3430
3431    private List<String> resolveAllBrowserApps(int userId) {
3432        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3433        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3434                PackageManager.MATCH_ALL, userId);
3435
3436        final int count = list.size();
3437        List<String> result = new ArrayList<String>(count);
3438        for (int i=0; i<count; i++) {
3439            ResolveInfo info = list.get(i);
3440            if (info.activityInfo == null
3441                    || !info.handleAllWebDataURI
3442                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3443                    || result.contains(info.activityInfo.packageName)) {
3444                continue;
3445            }
3446            result.add(info.activityInfo.packageName);
3447        }
3448
3449        return result;
3450    }
3451
3452    private boolean packageIsBrowser(String packageName, int userId) {
3453        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3454                PackageManager.MATCH_ALL, userId);
3455        final int N = list.size();
3456        for (int i = 0; i < N; i++) {
3457            ResolveInfo info = list.get(i);
3458            if (packageName.equals(info.activityInfo.packageName)) {
3459                return true;
3460            }
3461        }
3462        return false;
3463    }
3464
3465    private void checkDefaultBrowser() {
3466        final int myUserId = UserHandle.myUserId();
3467        final String packageName = getDefaultBrowserPackageName(myUserId);
3468        if (packageName != null) {
3469            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3470            if (info == null) {
3471                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3472                synchronized (mPackages) {
3473                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3474                }
3475            }
3476        }
3477    }
3478
3479    @Override
3480    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3481            throws RemoteException {
3482        try {
3483            return super.onTransact(code, data, reply, flags);
3484        } catch (RuntimeException e) {
3485            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3486                Slog.wtf(TAG, "Package Manager Crash", e);
3487            }
3488            throw e;
3489        }
3490    }
3491
3492    static int[] appendInts(int[] cur, int[] add) {
3493        if (add == null) return cur;
3494        if (cur == null) return add;
3495        final int N = add.length;
3496        for (int i=0; i<N; i++) {
3497            cur = appendInt(cur, add[i]);
3498        }
3499        return cur;
3500    }
3501
3502    /**
3503     * Returns whether or not a full application can see an instant application.
3504     * <p>
3505     * Currently, there are three cases in which this can occur:
3506     * <ol>
3507     * <li>The calling application is a "special" process. The special
3508     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3509     *     and {@code 0}</li>
3510     * <li>The calling application has the permission
3511     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3512     * <li>The calling application is the default launcher on the
3513     *     system partition.</li>
3514     * </ol>
3515     */
3516    private boolean canViewInstantApps(int callingUid, int userId) {
3517        if (callingUid == Process.SYSTEM_UID
3518                || callingUid == Process.SHELL_UID
3519                || callingUid == Process.ROOT_UID) {
3520            return true;
3521        }
3522        if (mContext.checkCallingOrSelfPermission(
3523                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3524            return true;
3525        }
3526        if (mContext.checkCallingOrSelfPermission(
3527                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3528            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3529            if (homeComponent != null
3530                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3531                return true;
3532            }
3533        }
3534        return false;
3535    }
3536
3537    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3538        if (!sUserManager.exists(userId)) return null;
3539        if (ps == null) {
3540            return null;
3541        }
3542        PackageParser.Package p = ps.pkg;
3543        if (p == null) {
3544            return null;
3545        }
3546        final int callingUid = Binder.getCallingUid();
3547        // Filter out ephemeral app metadata:
3548        //   * The system/shell/root can see metadata for any app
3549        //   * An installed app can see metadata for 1) other installed apps
3550        //     and 2) ephemeral apps that have explicitly interacted with it
3551        //   * Ephemeral apps can only see their own data and exposed installed apps
3552        //   * Holding a signature permission allows seeing instant apps
3553        if (filterAppAccessLPr(ps, callingUid, userId)) {
3554            return null;
3555        }
3556
3557        final PermissionsState permissionsState = ps.getPermissionsState();
3558
3559        // Compute GIDs only if requested
3560        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3561                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3562        // Compute granted permissions only if package has requested permissions
3563        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3564                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3565        final PackageUserState state = ps.readUserState(userId);
3566
3567        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3568                && ps.isSystem()) {
3569            flags |= MATCH_ANY_USER;
3570        }
3571
3572        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3573                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3574
3575        if (packageInfo == null) {
3576            return null;
3577        }
3578
3579        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3580                resolveExternalPackageNameLPr(p);
3581
3582        return packageInfo;
3583    }
3584
3585    @Override
3586    public void checkPackageStartable(String packageName, int userId) {
3587        final int callingUid = Binder.getCallingUid();
3588        if (getInstantAppPackageName(callingUid) != null) {
3589            throw new SecurityException("Instant applications don't have access to this method");
3590        }
3591        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3592        synchronized (mPackages) {
3593            final PackageSetting ps = mSettings.mPackages.get(packageName);
3594            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3595                throw new SecurityException("Package " + packageName + " was not found!");
3596            }
3597
3598            if (!ps.getInstalled(userId)) {
3599                throw new SecurityException(
3600                        "Package " + packageName + " was not installed for user " + userId + "!");
3601            }
3602
3603            if (mSafeMode && !ps.isSystem()) {
3604                throw new SecurityException("Package " + packageName + " not a system app!");
3605            }
3606
3607            if (mFrozenPackages.contains(packageName)) {
3608                throw new SecurityException("Package " + packageName + " is currently frozen!");
3609            }
3610
3611            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3612                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3613                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3614            }
3615        }
3616    }
3617
3618    @Override
3619    public boolean isPackageAvailable(String packageName, int userId) {
3620        if (!sUserManager.exists(userId)) return false;
3621        final int callingUid = Binder.getCallingUid();
3622        enforceCrossUserPermission(callingUid, userId,
3623                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3624        synchronized (mPackages) {
3625            PackageParser.Package p = mPackages.get(packageName);
3626            if (p != null) {
3627                final PackageSetting ps = (PackageSetting) p.mExtras;
3628                if (filterAppAccessLPr(ps, callingUid, userId)) {
3629                    return false;
3630                }
3631                if (ps != null) {
3632                    final PackageUserState state = ps.readUserState(userId);
3633                    if (state != null) {
3634                        return PackageParser.isAvailable(state);
3635                    }
3636                }
3637            }
3638        }
3639        return false;
3640    }
3641
3642    @Override
3643    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3644        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3645                flags, Binder.getCallingUid(), userId);
3646    }
3647
3648    @Override
3649    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3650            int flags, int userId) {
3651        return getPackageInfoInternal(versionedPackage.getPackageName(),
3652                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3653    }
3654
3655    /**
3656     * Important: The provided filterCallingUid is used exclusively to filter out packages
3657     * that can be seen based on user state. It's typically the original caller uid prior
3658     * to clearing. Because it can only be provided by trusted code, it's value can be
3659     * trusted and will be used as-is; unlike userId which will be validated by this method.
3660     */
3661    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3662            int flags, int filterCallingUid, int userId) {
3663        if (!sUserManager.exists(userId)) return null;
3664        flags = updateFlagsForPackage(flags, userId, packageName);
3665        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3666                false /* requireFullPermission */, false /* checkShell */, "get package info");
3667
3668        // reader
3669        synchronized (mPackages) {
3670            // Normalize package name to handle renamed packages and static libs
3671            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3672
3673            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3674            if (matchFactoryOnly) {
3675                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3676                if (ps != null) {
3677                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3678                        return null;
3679                    }
3680                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3681                        return null;
3682                    }
3683                    return generatePackageInfo(ps, flags, userId);
3684                }
3685            }
3686
3687            PackageParser.Package p = mPackages.get(packageName);
3688            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3689                return null;
3690            }
3691            if (DEBUG_PACKAGE_INFO)
3692                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3693            if (p != null) {
3694                final PackageSetting ps = (PackageSetting) p.mExtras;
3695                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3696                    return null;
3697                }
3698                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3699                    return null;
3700                }
3701                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3702            }
3703            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3704                final PackageSetting ps = mSettings.mPackages.get(packageName);
3705                if (ps == null) return null;
3706                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3707                    return null;
3708                }
3709                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3710                    return null;
3711                }
3712                return generatePackageInfo(ps, flags, userId);
3713            }
3714        }
3715        return null;
3716    }
3717
3718    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3719        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3720            return true;
3721        }
3722        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3723            return true;
3724        }
3725        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3726            return true;
3727        }
3728        return false;
3729    }
3730
3731    private boolean isComponentVisibleToInstantApp(
3732            @Nullable ComponentName component, @ComponentType int type) {
3733        if (type == TYPE_ACTIVITY) {
3734            final PackageParser.Activity activity = mActivities.mActivities.get(component);
3735            return activity != null
3736                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3737                    : false;
3738        } else if (type == TYPE_RECEIVER) {
3739            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
3740            return activity != null
3741                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3742                    : false;
3743        } else if (type == TYPE_SERVICE) {
3744            final PackageParser.Service service = mServices.mServices.get(component);
3745            return service != null
3746                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3747                    : false;
3748        } else if (type == TYPE_PROVIDER) {
3749            final PackageParser.Provider provider = mProviders.mProviders.get(component);
3750            return provider != null
3751                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3752                    : false;
3753        } else if (type == TYPE_UNKNOWN) {
3754            return isComponentVisibleToInstantApp(component);
3755        }
3756        return false;
3757    }
3758
3759    /**
3760     * Returns whether or not access to the application should be filtered.
3761     * <p>
3762     * Access may be limited based upon whether the calling or target applications
3763     * are instant applications.
3764     *
3765     * @see #canAccessInstantApps(int)
3766     */
3767    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
3768            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
3769        // if we're in an isolated process, get the real calling UID
3770        if (Process.isIsolated(callingUid)) {
3771            callingUid = mIsolatedOwners.get(callingUid);
3772        }
3773        final String instantAppPkgName = getInstantAppPackageName(callingUid);
3774        final boolean callerIsInstantApp = instantAppPkgName != null;
3775        if (ps == null) {
3776            if (callerIsInstantApp) {
3777                // pretend the application exists, but, needs to be filtered
3778                return true;
3779            }
3780            return false;
3781        }
3782        // if the target and caller are the same application, don't filter
3783        if (isCallerSameApp(ps.name, callingUid)) {
3784            return false;
3785        }
3786        if (callerIsInstantApp) {
3787            // request for a specific component; if it hasn't been explicitly exposed, filter
3788            if (component != null) {
3789                return !isComponentVisibleToInstantApp(component, componentType);
3790            }
3791            // request for application; if no components have been explicitly exposed, filter
3792            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
3793        }
3794        if (ps.getInstantApp(userId)) {
3795            // caller can see all components of all instant applications, don't filter
3796            if (canViewInstantApps(callingUid, userId)) {
3797                return false;
3798            }
3799            // request for a specific instant application component, filter
3800            if (component != null) {
3801                return true;
3802            }
3803            // request for an instant application; if the caller hasn't been granted access, filter
3804            return !mInstantAppRegistry.isInstantAccessGranted(
3805                    userId, UserHandle.getAppId(callingUid), ps.appId);
3806        }
3807        return false;
3808    }
3809
3810    /**
3811     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
3812     */
3813    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
3814        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
3815    }
3816
3817    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
3818            int flags) {
3819        // Callers can access only the libs they depend on, otherwise they need to explicitly
3820        // ask for the shared libraries given the caller is allowed to access all static libs.
3821        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
3822            // System/shell/root get to see all static libs
3823            final int appId = UserHandle.getAppId(uid);
3824            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3825                    || appId == Process.ROOT_UID) {
3826                return false;
3827            }
3828        }
3829
3830        // No package means no static lib as it is always on internal storage
3831        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3832            return false;
3833        }
3834
3835        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3836                ps.pkg.staticSharedLibVersion);
3837        if (libEntry == null) {
3838            return false;
3839        }
3840
3841        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3842        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3843        if (uidPackageNames == null) {
3844            return true;
3845        }
3846
3847        for (String uidPackageName : uidPackageNames) {
3848            if (ps.name.equals(uidPackageName)) {
3849                return false;
3850            }
3851            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3852            if (uidPs != null) {
3853                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3854                        libEntry.info.getName());
3855                if (index < 0) {
3856                    continue;
3857                }
3858                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3859                    return false;
3860                }
3861            }
3862        }
3863        return true;
3864    }
3865
3866    @Override
3867    public String[] currentToCanonicalPackageNames(String[] names) {
3868        final int callingUid = Binder.getCallingUid();
3869        if (getInstantAppPackageName(callingUid) != null) {
3870            return names;
3871        }
3872        final String[] out = new String[names.length];
3873        // reader
3874        synchronized (mPackages) {
3875            final int callingUserId = UserHandle.getUserId(callingUid);
3876            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
3877            for (int i=names.length-1; i>=0; i--) {
3878                final PackageSetting ps = mSettings.mPackages.get(names[i]);
3879                boolean translateName = false;
3880                if (ps != null && ps.realName != null) {
3881                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
3882                    translateName = !targetIsInstantApp
3883                            || canViewInstantApps
3884                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
3885                                    UserHandle.getAppId(callingUid), ps.appId);
3886                }
3887                out[i] = translateName ? ps.realName : names[i];
3888            }
3889        }
3890        return out;
3891    }
3892
3893    @Override
3894    public String[] canonicalToCurrentPackageNames(String[] names) {
3895        final int callingUid = Binder.getCallingUid();
3896        if (getInstantAppPackageName(callingUid) != null) {
3897            return names;
3898        }
3899        final String[] out = new String[names.length];
3900        // reader
3901        synchronized (mPackages) {
3902            final int callingUserId = UserHandle.getUserId(callingUid);
3903            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
3904            for (int i=names.length-1; i>=0; i--) {
3905                final String cur = mSettings.getRenamedPackageLPr(names[i]);
3906                boolean translateName = false;
3907                if (cur != null) {
3908                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
3909                    final boolean targetIsInstantApp =
3910                            ps != null && ps.getInstantApp(callingUserId);
3911                    translateName = !targetIsInstantApp
3912                            || canViewInstantApps
3913                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
3914                                    UserHandle.getAppId(callingUid), ps.appId);
3915                }
3916                out[i] = translateName ? cur : names[i];
3917            }
3918        }
3919        return out;
3920    }
3921
3922    @Override
3923    public int getPackageUid(String packageName, int flags, int userId) {
3924        if (!sUserManager.exists(userId)) return -1;
3925        final int callingUid = Binder.getCallingUid();
3926        flags = updateFlagsForPackage(flags, userId, packageName);
3927        enforceCrossUserPermission(callingUid, userId,
3928                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
3929
3930        // reader
3931        synchronized (mPackages) {
3932            final PackageParser.Package p = mPackages.get(packageName);
3933            if (p != null && p.isMatch(flags)) {
3934                PackageSetting ps = (PackageSetting) p.mExtras;
3935                if (filterAppAccessLPr(ps, callingUid, userId)) {
3936                    return -1;
3937                }
3938                return UserHandle.getUid(userId, p.applicationInfo.uid);
3939            }
3940            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3941                final PackageSetting ps = mSettings.mPackages.get(packageName);
3942                if (ps != null && ps.isMatch(flags)
3943                        && !filterAppAccessLPr(ps, callingUid, userId)) {
3944                    return UserHandle.getUid(userId, ps.appId);
3945                }
3946            }
3947        }
3948
3949        return -1;
3950    }
3951
3952    @Override
3953    public int[] getPackageGids(String packageName, int flags, int userId) {
3954        if (!sUserManager.exists(userId)) return null;
3955        final int callingUid = Binder.getCallingUid();
3956        flags = updateFlagsForPackage(flags, userId, packageName);
3957        enforceCrossUserPermission(callingUid, userId,
3958                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
3959
3960        // reader
3961        synchronized (mPackages) {
3962            final PackageParser.Package p = mPackages.get(packageName);
3963            if (p != null && p.isMatch(flags)) {
3964                PackageSetting ps = (PackageSetting) p.mExtras;
3965                if (filterAppAccessLPr(ps, callingUid, userId)) {
3966                    return null;
3967                }
3968                // TODO: Shouldn't this be checking for package installed state for userId and
3969                // return null?
3970                return ps.getPermissionsState().computeGids(userId);
3971            }
3972            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3973                final PackageSetting ps = mSettings.mPackages.get(packageName);
3974                if (ps != null && ps.isMatch(flags)
3975                        && !filterAppAccessLPr(ps, callingUid, userId)) {
3976                    return ps.getPermissionsState().computeGids(userId);
3977                }
3978            }
3979        }
3980
3981        return null;
3982    }
3983
3984    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3985        if (bp.perm != null) {
3986            return PackageParser.generatePermissionInfo(bp.perm, flags);
3987        }
3988        PermissionInfo pi = new PermissionInfo();
3989        pi.name = bp.name;
3990        pi.packageName = bp.sourcePackage;
3991        pi.nonLocalizedLabel = bp.name;
3992        pi.protectionLevel = bp.protectionLevel;
3993        return pi;
3994    }
3995
3996    @Override
3997    public PermissionInfo getPermissionInfo(String name, int flags) {
3998        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3999            return null;
4000        }
4001        // reader
4002        synchronized (mPackages) {
4003            final BasePermission p = mSettings.mPermissions.get(name);
4004            if (p != null) {
4005                return generatePermissionInfo(p, flags);
4006            }
4007            return null;
4008        }
4009    }
4010
4011    @Override
4012    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
4013            int flags) {
4014        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4015            return null;
4016        }
4017        // reader
4018        synchronized (mPackages) {
4019            if (group != null && !mPermissionGroups.containsKey(group)) {
4020                // This is thrown as NameNotFoundException
4021                return null;
4022            }
4023
4024            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4025            for (BasePermission p : mSettings.mPermissions.values()) {
4026                if (group == null) {
4027                    if (p.perm == null || p.perm.info.group == null) {
4028                        out.add(generatePermissionInfo(p, flags));
4029                    }
4030                } else {
4031                    if (p.perm != null && group.equals(p.perm.info.group)) {
4032                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
4033                    }
4034                }
4035            }
4036            return new ParceledListSlice<>(out);
4037        }
4038    }
4039
4040    @Override
4041    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4042        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4043            return null;
4044        }
4045        // reader
4046        synchronized (mPackages) {
4047            return PackageParser.generatePermissionGroupInfo(
4048                    mPermissionGroups.get(name), flags);
4049        }
4050    }
4051
4052    @Override
4053    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4054        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4055            return ParceledListSlice.emptyList();
4056        }
4057        // reader
4058        synchronized (mPackages) {
4059            final int N = mPermissionGroups.size();
4060            ArrayList<PermissionGroupInfo> out
4061                    = new ArrayList<PermissionGroupInfo>(N);
4062            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4063                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4064            }
4065            return new ParceledListSlice<>(out);
4066        }
4067    }
4068
4069    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4070            int filterCallingUid, int userId) {
4071        if (!sUserManager.exists(userId)) return null;
4072        PackageSetting ps = mSettings.mPackages.get(packageName);
4073        if (ps != null) {
4074            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4075                return null;
4076            }
4077            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4078                return null;
4079            }
4080            if (ps.pkg == null) {
4081                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4082                if (pInfo != null) {
4083                    return pInfo.applicationInfo;
4084                }
4085                return null;
4086            }
4087            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4088                    ps.readUserState(userId), userId);
4089            if (ai != null) {
4090                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4091            }
4092            return ai;
4093        }
4094        return null;
4095    }
4096
4097    @Override
4098    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4099        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4100    }
4101
4102    /**
4103     * Important: The provided filterCallingUid is used exclusively to filter out applications
4104     * that can be seen based on user state. It's typically the original caller uid prior
4105     * to clearing. Because it can only be provided by trusted code, it's value can be
4106     * trusted and will be used as-is; unlike userId which will be validated by this method.
4107     */
4108    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4109            int filterCallingUid, int userId) {
4110        if (!sUserManager.exists(userId)) return null;
4111        flags = updateFlagsForApplication(flags, userId, packageName);
4112        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4113                false /* requireFullPermission */, false /* checkShell */, "get application info");
4114
4115        // writer
4116        synchronized (mPackages) {
4117            // Normalize package name to handle renamed packages and static libs
4118            packageName = resolveInternalPackageNameLPr(packageName,
4119                    PackageManager.VERSION_CODE_HIGHEST);
4120
4121            PackageParser.Package p = mPackages.get(packageName);
4122            if (DEBUG_PACKAGE_INFO) Log.v(
4123                    TAG, "getApplicationInfo " + packageName
4124                    + ": " + p);
4125            if (p != null) {
4126                PackageSetting ps = mSettings.mPackages.get(packageName);
4127                if (ps == null) return null;
4128                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4129                    return null;
4130                }
4131                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4132                    return null;
4133                }
4134                // Note: isEnabledLP() does not apply here - always return info
4135                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4136                        p, flags, ps.readUserState(userId), userId);
4137                if (ai != null) {
4138                    ai.packageName = resolveExternalPackageNameLPr(p);
4139                }
4140                return ai;
4141            }
4142            if ("android".equals(packageName)||"system".equals(packageName)) {
4143                return mAndroidApplication;
4144            }
4145            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4146                // Already generates the external package name
4147                return generateApplicationInfoFromSettingsLPw(packageName,
4148                        flags, filterCallingUid, userId);
4149            }
4150        }
4151        return null;
4152    }
4153
4154    private String normalizePackageNameLPr(String packageName) {
4155        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4156        return normalizedPackageName != null ? normalizedPackageName : packageName;
4157    }
4158
4159    @Override
4160    public void deletePreloadsFileCache() {
4161        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4162            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4163        }
4164        File dir = Environment.getDataPreloadsFileCacheDirectory();
4165        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4166        FileUtils.deleteContents(dir);
4167    }
4168
4169    @Override
4170    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4171            final int storageFlags, final IPackageDataObserver observer) {
4172        mContext.enforceCallingOrSelfPermission(
4173                android.Manifest.permission.CLEAR_APP_CACHE, null);
4174        mHandler.post(() -> {
4175            boolean success = false;
4176            try {
4177                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4178                success = true;
4179            } catch (IOException e) {
4180                Slog.w(TAG, e);
4181            }
4182            if (observer != null) {
4183                try {
4184                    observer.onRemoveCompleted(null, success);
4185                } catch (RemoteException e) {
4186                    Slog.w(TAG, e);
4187                }
4188            }
4189        });
4190    }
4191
4192    @Override
4193    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4194            final int storageFlags, final IntentSender pi) {
4195        mContext.enforceCallingOrSelfPermission(
4196                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4197        mHandler.post(() -> {
4198            boolean success = false;
4199            try {
4200                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4201                success = true;
4202            } catch (IOException e) {
4203                Slog.w(TAG, e);
4204            }
4205            if (pi != null) {
4206                try {
4207                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4208                } catch (SendIntentException e) {
4209                    Slog.w(TAG, e);
4210                }
4211            }
4212        });
4213    }
4214
4215    /**
4216     * Blocking call to clear various types of cached data across the system
4217     * until the requested bytes are available.
4218     */
4219    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4220        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4221        final File file = storage.findPathForUuid(volumeUuid);
4222        if (file.getUsableSpace() >= bytes) return;
4223
4224        if (ENABLE_FREE_CACHE_V2) {
4225            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4226                    volumeUuid);
4227            final boolean aggressive = (storageFlags
4228                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4229            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4230
4231            // 1. Pre-flight to determine if we have any chance to succeed
4232            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4233            if (internalVolume && (aggressive || SystemProperties
4234                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4235                deletePreloadsFileCache();
4236                if (file.getUsableSpace() >= bytes) return;
4237            }
4238
4239            // 3. Consider parsed APK data (aggressive only)
4240            if (internalVolume && aggressive) {
4241                FileUtils.deleteContents(mCacheDir);
4242                if (file.getUsableSpace() >= bytes) return;
4243            }
4244
4245            // 4. Consider cached app data (above quotas)
4246            try {
4247                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4248                        Installer.FLAG_FREE_CACHE_V2);
4249            } catch (InstallerException ignored) {
4250            }
4251            if (file.getUsableSpace() >= bytes) return;
4252
4253            // 5. Consider shared libraries with refcount=0 and age>min cache period
4254            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4255                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4256                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4257                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4258                return;
4259            }
4260
4261            // 6. Consider dexopt output (aggressive only)
4262            // TODO: Implement
4263
4264            // 7. Consider installed instant apps unused longer than min cache period
4265            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4266                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4267                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4268                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4269                return;
4270            }
4271
4272            // 8. Consider cached app data (below quotas)
4273            try {
4274                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4275                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4276            } catch (InstallerException ignored) {
4277            }
4278            if (file.getUsableSpace() >= bytes) return;
4279
4280            // 9. Consider DropBox entries
4281            // TODO: Implement
4282
4283            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4284            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4285                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4286                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4287                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4288                return;
4289            }
4290        } else {
4291            try {
4292                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4293            } catch (InstallerException ignored) {
4294            }
4295            if (file.getUsableSpace() >= bytes) return;
4296        }
4297
4298        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4299    }
4300
4301    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4302            throws IOException {
4303        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4304        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4305
4306        List<VersionedPackage> packagesToDelete = null;
4307        final long now = System.currentTimeMillis();
4308
4309        synchronized (mPackages) {
4310            final int[] allUsers = sUserManager.getUserIds();
4311            final int libCount = mSharedLibraries.size();
4312            for (int i = 0; i < libCount; i++) {
4313                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4314                if (versionedLib == null) {
4315                    continue;
4316                }
4317                final int versionCount = versionedLib.size();
4318                for (int j = 0; j < versionCount; j++) {
4319                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4320                    // Skip packages that are not static shared libs.
4321                    if (!libInfo.isStatic()) {
4322                        break;
4323                    }
4324                    // Important: We skip static shared libs used for some user since
4325                    // in such a case we need to keep the APK on the device. The check for
4326                    // a lib being used for any user is performed by the uninstall call.
4327                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4328                    // Resolve the package name - we use synthetic package names internally
4329                    final String internalPackageName = resolveInternalPackageNameLPr(
4330                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4331                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4332                    // Skip unused static shared libs cached less than the min period
4333                    // to prevent pruning a lib needed by a subsequently installed package.
4334                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4335                        continue;
4336                    }
4337                    if (packagesToDelete == null) {
4338                        packagesToDelete = new ArrayList<>();
4339                    }
4340                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4341                            declaringPackage.getVersionCode()));
4342                }
4343            }
4344        }
4345
4346        if (packagesToDelete != null) {
4347            final int packageCount = packagesToDelete.size();
4348            for (int i = 0; i < packageCount; i++) {
4349                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4350                // Delete the package synchronously (will fail of the lib used for any user).
4351                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4352                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4353                                == PackageManager.DELETE_SUCCEEDED) {
4354                    if (volume.getUsableSpace() >= neededSpace) {
4355                        return true;
4356                    }
4357                }
4358            }
4359        }
4360
4361        return false;
4362    }
4363
4364    /**
4365     * Update given flags based on encryption status of current user.
4366     */
4367    private int updateFlags(int flags, int userId) {
4368        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4369                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4370            // Caller expressed an explicit opinion about what encryption
4371            // aware/unaware components they want to see, so fall through and
4372            // give them what they want
4373        } else {
4374            // Caller expressed no opinion, so match based on user state
4375            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4376                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4377            } else {
4378                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4379            }
4380        }
4381        return flags;
4382    }
4383
4384    private UserManagerInternal getUserManagerInternal() {
4385        if (mUserManagerInternal == null) {
4386            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4387        }
4388        return mUserManagerInternal;
4389    }
4390
4391    private DeviceIdleController.LocalService getDeviceIdleController() {
4392        if (mDeviceIdleController == null) {
4393            mDeviceIdleController =
4394                    LocalServices.getService(DeviceIdleController.LocalService.class);
4395        }
4396        return mDeviceIdleController;
4397    }
4398
4399    /**
4400     * Update given flags when being used to request {@link PackageInfo}.
4401     */
4402    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4403        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4404        boolean triaged = true;
4405        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4406                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4407            // Caller is asking for component details, so they'd better be
4408            // asking for specific encryption matching behavior, or be triaged
4409            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4410                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4411                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4412                triaged = false;
4413            }
4414        }
4415        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4416                | PackageManager.MATCH_SYSTEM_ONLY
4417                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4418            triaged = false;
4419        }
4420        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4421            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4422                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4423                    + Debug.getCallers(5));
4424        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4425                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4426            // If the caller wants all packages and has a restricted profile associated with it,
4427            // then match all users. This is to make sure that launchers that need to access work
4428            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4429            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4430            flags |= PackageManager.MATCH_ANY_USER;
4431        }
4432        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4433            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4434                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4435        }
4436        return updateFlags(flags, userId);
4437    }
4438
4439    /**
4440     * Update given flags when being used to request {@link ApplicationInfo}.
4441     */
4442    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4443        return updateFlagsForPackage(flags, userId, cookie);
4444    }
4445
4446    /**
4447     * Update given flags when being used to request {@link ComponentInfo}.
4448     */
4449    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4450        if (cookie instanceof Intent) {
4451            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4452                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4453            }
4454        }
4455
4456        boolean triaged = true;
4457        // Caller is asking for component details, so they'd better be
4458        // asking for specific encryption matching behavior, or be triaged
4459        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4460                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4461                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4462            triaged = false;
4463        }
4464        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4465            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4466                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4467        }
4468
4469        return updateFlags(flags, userId);
4470    }
4471
4472    /**
4473     * Update given intent when being used to request {@link ResolveInfo}.
4474     */
4475    private Intent updateIntentForResolve(Intent intent) {
4476        if (intent.getSelector() != null) {
4477            intent = intent.getSelector();
4478        }
4479        if (DEBUG_PREFERRED) {
4480            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4481        }
4482        return intent;
4483    }
4484
4485    /**
4486     * Update given flags when being used to request {@link ResolveInfo}.
4487     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4488     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4489     * flag set. However, this flag is only honoured in three circumstances:
4490     * <ul>
4491     * <li>when called from a system process</li>
4492     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4493     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4494     * action and a {@code android.intent.category.BROWSABLE} category</li>
4495     * </ul>
4496     */
4497    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4498        return updateFlagsForResolve(flags, userId, intent, callingUid,
4499                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4500    }
4501    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4502            boolean wantInstantApps) {
4503        return updateFlagsForResolve(flags, userId, intent, callingUid,
4504                wantInstantApps, false /*onlyExposedExplicitly*/);
4505    }
4506    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4507            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4508        // Safe mode means we shouldn't match any third-party components
4509        if (mSafeMode) {
4510            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4511        }
4512        if (getInstantAppPackageName(callingUid) != null) {
4513            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4514            if (onlyExposedExplicitly) {
4515                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4516            }
4517            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4518            flags |= PackageManager.MATCH_INSTANT;
4519        } else {
4520            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4521            final boolean allowMatchInstant =
4522                    (wantInstantApps
4523                            && Intent.ACTION_VIEW.equals(intent.getAction())
4524                            && hasWebURI(intent))
4525                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4526            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4527                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4528            if (!allowMatchInstant) {
4529                flags &= ~PackageManager.MATCH_INSTANT;
4530            }
4531        }
4532        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4533    }
4534
4535    @Override
4536    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4537        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4538    }
4539
4540    /**
4541     * Important: The provided filterCallingUid is used exclusively to filter out activities
4542     * that can be seen based on user state. It's typically the original caller uid prior
4543     * to clearing. Because it can only be provided by trusted code, it's value can be
4544     * trusted and will be used as-is; unlike userId which will be validated by this method.
4545     */
4546    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4547            int filterCallingUid, int userId) {
4548        if (!sUserManager.exists(userId)) return null;
4549        flags = updateFlagsForComponent(flags, userId, component);
4550        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4551                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4552        synchronized (mPackages) {
4553            PackageParser.Activity a = mActivities.mActivities.get(component);
4554
4555            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4556            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4557                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4558                if (ps == null) return null;
4559                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4560                    return null;
4561                }
4562                return PackageParser.generateActivityInfo(
4563                        a, flags, ps.readUserState(userId), userId);
4564            }
4565            if (mResolveComponentName.equals(component)) {
4566                return PackageParser.generateActivityInfo(
4567                        mResolveActivity, flags, new PackageUserState(), userId);
4568            }
4569        }
4570        return null;
4571    }
4572
4573    @Override
4574    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4575            String resolvedType) {
4576        synchronized (mPackages) {
4577            if (component.equals(mResolveComponentName)) {
4578                // The resolver supports EVERYTHING!
4579                return true;
4580            }
4581            final int callingUid = Binder.getCallingUid();
4582            final int callingUserId = UserHandle.getUserId(callingUid);
4583            PackageParser.Activity a = mActivities.mActivities.get(component);
4584            if (a == null) {
4585                return false;
4586            }
4587            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4588            if (ps == null) {
4589                return false;
4590            }
4591            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4592                return false;
4593            }
4594            for (int i=0; i<a.intents.size(); i++) {
4595                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4596                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4597                    return true;
4598                }
4599            }
4600            return false;
4601        }
4602    }
4603
4604    @Override
4605    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4606        if (!sUserManager.exists(userId)) return null;
4607        final int callingUid = Binder.getCallingUid();
4608        flags = updateFlagsForComponent(flags, userId, component);
4609        enforceCrossUserPermission(callingUid, userId,
4610                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4611        synchronized (mPackages) {
4612            PackageParser.Activity a = mReceivers.mActivities.get(component);
4613            if (DEBUG_PACKAGE_INFO) Log.v(
4614                TAG, "getReceiverInfo " + component + ": " + a);
4615            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4616                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4617                if (ps == null) return null;
4618                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4619                    return null;
4620                }
4621                return PackageParser.generateActivityInfo(
4622                        a, flags, ps.readUserState(userId), userId);
4623            }
4624        }
4625        return null;
4626    }
4627
4628    @Override
4629    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4630            int flags, int userId) {
4631        if (!sUserManager.exists(userId)) return null;
4632        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4633        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4634            return null;
4635        }
4636
4637        flags = updateFlagsForPackage(flags, userId, null);
4638
4639        final boolean canSeeStaticLibraries =
4640                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4641                        == PERMISSION_GRANTED
4642                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4643                        == PERMISSION_GRANTED
4644                || canRequestPackageInstallsInternal(packageName,
4645                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4646                        false  /* throwIfPermNotDeclared*/)
4647                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4648                        == PERMISSION_GRANTED;
4649
4650        synchronized (mPackages) {
4651            List<SharedLibraryInfo> result = null;
4652
4653            final int libCount = mSharedLibraries.size();
4654            for (int i = 0; i < libCount; i++) {
4655                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4656                if (versionedLib == null) {
4657                    continue;
4658                }
4659
4660                final int versionCount = versionedLib.size();
4661                for (int j = 0; j < versionCount; j++) {
4662                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4663                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4664                        break;
4665                    }
4666                    final long identity = Binder.clearCallingIdentity();
4667                    try {
4668                        PackageInfo packageInfo = getPackageInfoVersioned(
4669                                libInfo.getDeclaringPackage(), flags
4670                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4671                        if (packageInfo == null) {
4672                            continue;
4673                        }
4674                    } finally {
4675                        Binder.restoreCallingIdentity(identity);
4676                    }
4677
4678                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4679                            libInfo.getVersion(), libInfo.getType(),
4680                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4681                            flags, userId));
4682
4683                    if (result == null) {
4684                        result = new ArrayList<>();
4685                    }
4686                    result.add(resLibInfo);
4687                }
4688            }
4689
4690            return result != null ? new ParceledListSlice<>(result) : null;
4691        }
4692    }
4693
4694    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4695            SharedLibraryInfo libInfo, int flags, int userId) {
4696        List<VersionedPackage> versionedPackages = null;
4697        final int packageCount = mSettings.mPackages.size();
4698        for (int i = 0; i < packageCount; i++) {
4699            PackageSetting ps = mSettings.mPackages.valueAt(i);
4700
4701            if (ps == null) {
4702                continue;
4703            }
4704
4705            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4706                continue;
4707            }
4708
4709            final String libName = libInfo.getName();
4710            if (libInfo.isStatic()) {
4711                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4712                if (libIdx < 0) {
4713                    continue;
4714                }
4715                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4716                    continue;
4717                }
4718                if (versionedPackages == null) {
4719                    versionedPackages = new ArrayList<>();
4720                }
4721                // If the dependent is a static shared lib, use the public package name
4722                String dependentPackageName = ps.name;
4723                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4724                    dependentPackageName = ps.pkg.manifestPackageName;
4725                }
4726                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4727            } else if (ps.pkg != null) {
4728                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4729                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4730                    if (versionedPackages == null) {
4731                        versionedPackages = new ArrayList<>();
4732                    }
4733                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4734                }
4735            }
4736        }
4737
4738        return versionedPackages;
4739    }
4740
4741    @Override
4742    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4743        if (!sUserManager.exists(userId)) return null;
4744        final int callingUid = Binder.getCallingUid();
4745        flags = updateFlagsForComponent(flags, userId, component);
4746        enforceCrossUserPermission(callingUid, userId,
4747                false /* requireFullPermission */, false /* checkShell */, "get service info");
4748        synchronized (mPackages) {
4749            PackageParser.Service s = mServices.mServices.get(component);
4750            if (DEBUG_PACKAGE_INFO) Log.v(
4751                TAG, "getServiceInfo " + component + ": " + s);
4752            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4753                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4754                if (ps == null) return null;
4755                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
4756                    return null;
4757                }
4758                return PackageParser.generateServiceInfo(
4759                        s, flags, ps.readUserState(userId), userId);
4760            }
4761        }
4762        return null;
4763    }
4764
4765    @Override
4766    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4767        if (!sUserManager.exists(userId)) return null;
4768        final int callingUid = Binder.getCallingUid();
4769        flags = updateFlagsForComponent(flags, userId, component);
4770        enforceCrossUserPermission(callingUid, userId,
4771                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4772        synchronized (mPackages) {
4773            PackageParser.Provider p = mProviders.mProviders.get(component);
4774            if (DEBUG_PACKAGE_INFO) Log.v(
4775                TAG, "getProviderInfo " + component + ": " + p);
4776            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4777                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4778                if (ps == null) return null;
4779                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
4780                    return null;
4781                }
4782                return PackageParser.generateProviderInfo(
4783                        p, flags, ps.readUserState(userId), userId);
4784            }
4785        }
4786        return null;
4787    }
4788
4789    @Override
4790    public String[] getSystemSharedLibraryNames() {
4791        // allow instant applications
4792        synchronized (mPackages) {
4793            Set<String> libs = null;
4794            final int libCount = mSharedLibraries.size();
4795            for (int i = 0; i < libCount; i++) {
4796                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4797                if (versionedLib == null) {
4798                    continue;
4799                }
4800                final int versionCount = versionedLib.size();
4801                for (int j = 0; j < versionCount; j++) {
4802                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4803                    if (!libEntry.info.isStatic()) {
4804                        if (libs == null) {
4805                            libs = new ArraySet<>();
4806                        }
4807                        libs.add(libEntry.info.getName());
4808                        break;
4809                    }
4810                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4811                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4812                            UserHandle.getUserId(Binder.getCallingUid()),
4813                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
4814                        if (libs == null) {
4815                            libs = new ArraySet<>();
4816                        }
4817                        libs.add(libEntry.info.getName());
4818                        break;
4819                    }
4820                }
4821            }
4822
4823            if (libs != null) {
4824                String[] libsArray = new String[libs.size()];
4825                libs.toArray(libsArray);
4826                return libsArray;
4827            }
4828
4829            return null;
4830        }
4831    }
4832
4833    @Override
4834    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4835        // allow instant applications
4836        synchronized (mPackages) {
4837            return mServicesSystemSharedLibraryPackageName;
4838        }
4839    }
4840
4841    @Override
4842    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4843        // allow instant applications
4844        synchronized (mPackages) {
4845            return mSharedSystemSharedLibraryPackageName;
4846        }
4847    }
4848
4849    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
4850        for (int i = userList.length - 1; i >= 0; --i) {
4851            final int userId = userList[i];
4852            // don't add instant app to the list of updates
4853            if (pkgSetting.getInstantApp(userId)) {
4854                continue;
4855            }
4856            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4857            if (changedPackages == null) {
4858                changedPackages = new SparseArray<>();
4859                mChangedPackages.put(userId, changedPackages);
4860            }
4861            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4862            if (sequenceNumbers == null) {
4863                sequenceNumbers = new HashMap<>();
4864                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4865            }
4866            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
4867            if (sequenceNumber != null) {
4868                changedPackages.remove(sequenceNumber);
4869            }
4870            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
4871            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
4872        }
4873        mChangedPackagesSequenceNumber++;
4874    }
4875
4876    @Override
4877    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4878        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4879            return null;
4880        }
4881        synchronized (mPackages) {
4882            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4883                return null;
4884            }
4885            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4886            if (changedPackages == null) {
4887                return null;
4888            }
4889            final List<String> packageNames =
4890                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4891            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4892                final String packageName = changedPackages.get(i);
4893                if (packageName != null) {
4894                    packageNames.add(packageName);
4895                }
4896            }
4897            return packageNames.isEmpty()
4898                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4899        }
4900    }
4901
4902    @Override
4903    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4904        // allow instant applications
4905        ArrayList<FeatureInfo> res;
4906        synchronized (mAvailableFeatures) {
4907            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4908            res.addAll(mAvailableFeatures.values());
4909        }
4910        final FeatureInfo fi = new FeatureInfo();
4911        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4912                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4913        res.add(fi);
4914
4915        return new ParceledListSlice<>(res);
4916    }
4917
4918    @Override
4919    public boolean hasSystemFeature(String name, int version) {
4920        // allow instant applications
4921        synchronized (mAvailableFeatures) {
4922            final FeatureInfo feat = mAvailableFeatures.get(name);
4923            if (feat == null) {
4924                return false;
4925            } else {
4926                return feat.version >= version;
4927            }
4928        }
4929    }
4930
4931    @Override
4932    public int checkPermission(String permName, String pkgName, int userId) {
4933        if (!sUserManager.exists(userId)) {
4934            return PackageManager.PERMISSION_DENIED;
4935        }
4936        final int callingUid = Binder.getCallingUid();
4937
4938        synchronized (mPackages) {
4939            final PackageParser.Package p = mPackages.get(pkgName);
4940            if (p != null && p.mExtras != null) {
4941                final PackageSetting ps = (PackageSetting) p.mExtras;
4942                if (filterAppAccessLPr(ps, callingUid, userId)) {
4943                    return PackageManager.PERMISSION_DENIED;
4944                }
4945                final boolean instantApp = ps.getInstantApp(userId);
4946                final PermissionsState permissionsState = ps.getPermissionsState();
4947                if (permissionsState.hasPermission(permName, userId)) {
4948                    if (instantApp) {
4949                        BasePermission bp = mSettings.mPermissions.get(permName);
4950                        if (bp != null && bp.isInstant()) {
4951                            return PackageManager.PERMISSION_GRANTED;
4952                        }
4953                    } else {
4954                        return PackageManager.PERMISSION_GRANTED;
4955                    }
4956                }
4957                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4958                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4959                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4960                    return PackageManager.PERMISSION_GRANTED;
4961                }
4962            }
4963        }
4964
4965        return PackageManager.PERMISSION_DENIED;
4966    }
4967
4968    @Override
4969    public int checkUidPermission(String permName, int uid) {
4970        final int callingUid = Binder.getCallingUid();
4971        final int callingUserId = UserHandle.getUserId(callingUid);
4972        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
4973        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
4974        final int userId = UserHandle.getUserId(uid);
4975        if (!sUserManager.exists(userId)) {
4976            return PackageManager.PERMISSION_DENIED;
4977        }
4978
4979        synchronized (mPackages) {
4980            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4981            if (obj != null) {
4982                if (obj instanceof SharedUserSetting) {
4983                    if (isCallerInstantApp) {
4984                        return PackageManager.PERMISSION_DENIED;
4985                    }
4986                } else if (obj instanceof PackageSetting) {
4987                    final PackageSetting ps = (PackageSetting) obj;
4988                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
4989                        return PackageManager.PERMISSION_DENIED;
4990                    }
4991                }
4992                final SettingBase settingBase = (SettingBase) obj;
4993                final PermissionsState permissionsState = settingBase.getPermissionsState();
4994                if (permissionsState.hasPermission(permName, userId)) {
4995                    if (isUidInstantApp) {
4996                        BasePermission bp = mSettings.mPermissions.get(permName);
4997                        if (bp != null && bp.isInstant()) {
4998                            return PackageManager.PERMISSION_GRANTED;
4999                        }
5000                    } else {
5001                        return PackageManager.PERMISSION_GRANTED;
5002                    }
5003                }
5004                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5005                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5006                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5007                    return PackageManager.PERMISSION_GRANTED;
5008                }
5009            } else {
5010                ArraySet<String> perms = mSystemPermissions.get(uid);
5011                if (perms != null) {
5012                    if (perms.contains(permName)) {
5013                        return PackageManager.PERMISSION_GRANTED;
5014                    }
5015                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5016                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5017                        return PackageManager.PERMISSION_GRANTED;
5018                    }
5019                }
5020            }
5021        }
5022
5023        return PackageManager.PERMISSION_DENIED;
5024    }
5025
5026    @Override
5027    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5028        if (UserHandle.getCallingUserId() != userId) {
5029            mContext.enforceCallingPermission(
5030                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5031                    "isPermissionRevokedByPolicy for user " + userId);
5032        }
5033
5034        if (checkPermission(permission, packageName, userId)
5035                == PackageManager.PERMISSION_GRANTED) {
5036            return false;
5037        }
5038
5039        final int callingUid = Binder.getCallingUid();
5040        if (getInstantAppPackageName(callingUid) != null) {
5041            if (!isCallerSameApp(packageName, callingUid)) {
5042                return false;
5043            }
5044        } else {
5045            if (isInstantApp(packageName, userId)) {
5046                return false;
5047            }
5048        }
5049
5050        final long identity = Binder.clearCallingIdentity();
5051        try {
5052            final int flags = getPermissionFlags(permission, packageName, userId);
5053            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5054        } finally {
5055            Binder.restoreCallingIdentity(identity);
5056        }
5057    }
5058
5059    @Override
5060    public String getPermissionControllerPackageName() {
5061        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5062            throw new SecurityException("Instant applications don't have access to this method");
5063        }
5064        synchronized (mPackages) {
5065            return mRequiredInstallerPackage;
5066        }
5067    }
5068
5069    /**
5070     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
5071     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
5072     * @param checkShell whether to prevent shell from access if there's a debugging restriction
5073     * @param message the message to log on security exception
5074     */
5075    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
5076            boolean checkShell, String message) {
5077        if (userId < 0) {
5078            throw new IllegalArgumentException("Invalid userId " + userId);
5079        }
5080        if (checkShell) {
5081            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
5082        }
5083        if (userId == UserHandle.getUserId(callingUid)) return;
5084        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5085            if (requireFullPermission) {
5086                mContext.enforceCallingOrSelfPermission(
5087                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5088            } else {
5089                try {
5090                    mContext.enforceCallingOrSelfPermission(
5091                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5092                } catch (SecurityException se) {
5093                    mContext.enforceCallingOrSelfPermission(
5094                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5095                }
5096            }
5097        }
5098    }
5099
5100    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5101        if (callingUid == Process.SHELL_UID) {
5102            if (userHandle >= 0
5103                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
5104                throw new SecurityException("Shell does not have permission to access user "
5105                        + userHandle);
5106            } else if (userHandle < 0) {
5107                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5108                        + Debug.getCallers(3));
5109            }
5110        }
5111    }
5112
5113    private BasePermission findPermissionTreeLP(String permName) {
5114        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
5115            if (permName.startsWith(bp.name) &&
5116                    permName.length() > bp.name.length() &&
5117                    permName.charAt(bp.name.length()) == '.') {
5118                return bp;
5119            }
5120        }
5121        return null;
5122    }
5123
5124    private BasePermission checkPermissionTreeLP(String permName) {
5125        if (permName != null) {
5126            BasePermission bp = findPermissionTreeLP(permName);
5127            if (bp != null) {
5128                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
5129                    return bp;
5130                }
5131                throw new SecurityException("Calling uid "
5132                        + Binder.getCallingUid()
5133                        + " is not allowed to add to permission tree "
5134                        + bp.name + " owned by uid " + bp.uid);
5135            }
5136        }
5137        throw new SecurityException("No permission tree found for " + permName);
5138    }
5139
5140    static boolean compareStrings(CharSequence s1, CharSequence s2) {
5141        if (s1 == null) {
5142            return s2 == null;
5143        }
5144        if (s2 == null) {
5145            return false;
5146        }
5147        if (s1.getClass() != s2.getClass()) {
5148            return false;
5149        }
5150        return s1.equals(s2);
5151    }
5152
5153    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5154        if (pi1.icon != pi2.icon) return false;
5155        if (pi1.logo != pi2.logo) return false;
5156        if (pi1.protectionLevel != pi2.protectionLevel) return false;
5157        if (!compareStrings(pi1.name, pi2.name)) return false;
5158        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5159        // We'll take care of setting this one.
5160        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5161        // These are not currently stored in settings.
5162        //if (!compareStrings(pi1.group, pi2.group)) return false;
5163        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5164        //if (pi1.labelRes != pi2.labelRes) return false;
5165        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5166        return true;
5167    }
5168
5169    int permissionInfoFootprint(PermissionInfo info) {
5170        int size = info.name.length();
5171        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5172        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5173        return size;
5174    }
5175
5176    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5177        int size = 0;
5178        for (BasePermission perm : mSettings.mPermissions.values()) {
5179            if (perm.uid == tree.uid) {
5180                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5181            }
5182        }
5183        return size;
5184    }
5185
5186    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5187        // We calculate the max size of permissions defined by this uid and throw
5188        // if that plus the size of 'info' would exceed our stated maximum.
5189        if (tree.uid != Process.SYSTEM_UID) {
5190            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5191            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5192                throw new SecurityException("Permission tree size cap exceeded");
5193            }
5194        }
5195    }
5196
5197    boolean addPermissionLocked(PermissionInfo info, boolean async) {
5198        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5199            throw new SecurityException("Instant apps can't add permissions");
5200        }
5201        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5202            throw new SecurityException("Label must be specified in permission");
5203        }
5204        BasePermission tree = checkPermissionTreeLP(info.name);
5205        BasePermission bp = mSettings.mPermissions.get(info.name);
5206        boolean added = bp == null;
5207        boolean changed = true;
5208        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5209        if (added) {
5210            enforcePermissionCapLocked(info, tree);
5211            bp = new BasePermission(info.name, tree.sourcePackage,
5212                    BasePermission.TYPE_DYNAMIC);
5213        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5214            throw new SecurityException(
5215                    "Not allowed to modify non-dynamic permission "
5216                    + info.name);
5217        } else {
5218            if (bp.protectionLevel == fixedLevel
5219                    && bp.perm.owner.equals(tree.perm.owner)
5220                    && bp.uid == tree.uid
5221                    && comparePermissionInfos(bp.perm.info, info)) {
5222                changed = false;
5223            }
5224        }
5225        bp.protectionLevel = fixedLevel;
5226        info = new PermissionInfo(info);
5227        info.protectionLevel = fixedLevel;
5228        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5229        bp.perm.info.packageName = tree.perm.info.packageName;
5230        bp.uid = tree.uid;
5231        if (added) {
5232            mSettings.mPermissions.put(info.name, bp);
5233        }
5234        if (changed) {
5235            if (!async) {
5236                mSettings.writeLPr();
5237            } else {
5238                scheduleWriteSettingsLocked();
5239            }
5240        }
5241        return added;
5242    }
5243
5244    @Override
5245    public boolean addPermission(PermissionInfo info) {
5246        synchronized (mPackages) {
5247            return addPermissionLocked(info, false);
5248        }
5249    }
5250
5251    @Override
5252    public boolean addPermissionAsync(PermissionInfo info) {
5253        synchronized (mPackages) {
5254            return addPermissionLocked(info, true);
5255        }
5256    }
5257
5258    @Override
5259    public void removePermission(String name) {
5260        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5261            throw new SecurityException("Instant applications don't have access to this method");
5262        }
5263        synchronized (mPackages) {
5264            checkPermissionTreeLP(name);
5265            BasePermission bp = mSettings.mPermissions.get(name);
5266            if (bp != null) {
5267                if (bp.type != BasePermission.TYPE_DYNAMIC) {
5268                    throw new SecurityException(
5269                            "Not allowed to modify non-dynamic permission "
5270                            + name);
5271                }
5272                mSettings.mPermissions.remove(name);
5273                mSettings.writeLPr();
5274            }
5275        }
5276    }
5277
5278    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5279            PackageParser.Package pkg, BasePermission bp) {
5280        int index = pkg.requestedPermissions.indexOf(bp.name);
5281        if (index == -1) {
5282            throw new SecurityException("Package " + pkg.packageName
5283                    + " has not requested permission " + bp.name);
5284        }
5285        if (!bp.isRuntime() && !bp.isDevelopment()) {
5286            throw new SecurityException("Permission " + bp.name
5287                    + " is not a changeable permission type");
5288        }
5289    }
5290
5291    @Override
5292    public void grantRuntimePermission(String packageName, String name, final int userId) {
5293        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5294    }
5295
5296    private void grantRuntimePermission(String packageName, String name, final int userId,
5297            boolean overridePolicy) {
5298        if (!sUserManager.exists(userId)) {
5299            Log.e(TAG, "No such user:" + userId);
5300            return;
5301        }
5302        final int callingUid = Binder.getCallingUid();
5303
5304        mContext.enforceCallingOrSelfPermission(
5305                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5306                "grantRuntimePermission");
5307
5308        enforceCrossUserPermission(callingUid, userId,
5309                true /* requireFullPermission */, true /* checkShell */,
5310                "grantRuntimePermission");
5311
5312        final int uid;
5313        final PackageSetting ps;
5314
5315        synchronized (mPackages) {
5316            final PackageParser.Package pkg = mPackages.get(packageName);
5317            if (pkg == null) {
5318                throw new IllegalArgumentException("Unknown package: " + packageName);
5319            }
5320            final BasePermission bp = mSettings.mPermissions.get(name);
5321            if (bp == null) {
5322                throw new IllegalArgumentException("Unknown permission: " + name);
5323            }
5324            ps = (PackageSetting) pkg.mExtras;
5325            if (ps == null
5326                    || filterAppAccessLPr(ps, callingUid, userId)) {
5327                throw new IllegalArgumentException("Unknown package: " + packageName);
5328            }
5329
5330            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5331
5332            // If a permission review is required for legacy apps we represent
5333            // their permissions as always granted runtime ones since we need
5334            // to keep the review required permission flag per user while an
5335            // install permission's state is shared across all users.
5336            if (mPermissionReviewRequired
5337                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5338                    && bp.isRuntime()) {
5339                return;
5340            }
5341
5342            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5343
5344            final PermissionsState permissionsState = ps.getPermissionsState();
5345
5346            final int flags = permissionsState.getPermissionFlags(name, userId);
5347            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5348                throw new SecurityException("Cannot grant system fixed permission "
5349                        + name + " for package " + packageName);
5350            }
5351            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5352                throw new SecurityException("Cannot grant policy fixed permission "
5353                        + name + " for package " + packageName);
5354            }
5355
5356            if (bp.isDevelopment()) {
5357                // Development permissions must be handled specially, since they are not
5358                // normal runtime permissions.  For now they apply to all users.
5359                if (permissionsState.grantInstallPermission(bp) !=
5360                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5361                    scheduleWriteSettingsLocked();
5362                }
5363                return;
5364            }
5365
5366            if (ps.getInstantApp(userId) && !bp.isInstant()) {
5367                throw new SecurityException("Cannot grant non-ephemeral permission"
5368                        + name + " for package " + packageName);
5369            }
5370
5371            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5372                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5373                return;
5374            }
5375
5376            final int result = permissionsState.grantRuntimePermission(bp, userId);
5377            switch (result) {
5378                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5379                    return;
5380                }
5381
5382                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5383                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5384                    mHandler.post(new Runnable() {
5385                        @Override
5386                        public void run() {
5387                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5388                        }
5389                    });
5390                }
5391                break;
5392            }
5393
5394            if (bp.isRuntime()) {
5395                logPermissionGranted(mContext, name, packageName);
5396            }
5397
5398            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5399
5400            // Not critical if that is lost - app has to request again.
5401            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5402        }
5403
5404        // Only need to do this if user is initialized. Otherwise it's a new user
5405        // and there are no processes running as the user yet and there's no need
5406        // to make an expensive call to remount processes for the changed permissions.
5407        if (READ_EXTERNAL_STORAGE.equals(name)
5408                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5409            final long token = Binder.clearCallingIdentity();
5410            try {
5411                if (sUserManager.isInitialized(userId)) {
5412                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5413                            StorageManagerInternal.class);
5414                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5415                }
5416            } finally {
5417                Binder.restoreCallingIdentity(token);
5418            }
5419        }
5420    }
5421
5422    @Override
5423    public void revokeRuntimePermission(String packageName, String name, int userId) {
5424        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5425    }
5426
5427    private void revokeRuntimePermission(String packageName, String name, int userId,
5428            boolean overridePolicy) {
5429        if (!sUserManager.exists(userId)) {
5430            Log.e(TAG, "No such user:" + userId);
5431            return;
5432        }
5433
5434        mContext.enforceCallingOrSelfPermission(
5435                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5436                "revokeRuntimePermission");
5437
5438        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5439                true /* requireFullPermission */, true /* checkShell */,
5440                "revokeRuntimePermission");
5441
5442        final int appId;
5443
5444        synchronized (mPackages) {
5445            final PackageParser.Package pkg = mPackages.get(packageName);
5446            if (pkg == null) {
5447                throw new IllegalArgumentException("Unknown package: " + packageName);
5448            }
5449            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5450            if (ps == null
5451                    || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
5452                throw new IllegalArgumentException("Unknown package: " + packageName);
5453            }
5454            final BasePermission bp = mSettings.mPermissions.get(name);
5455            if (bp == null) {
5456                throw new IllegalArgumentException("Unknown permission: " + name);
5457            }
5458
5459            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5460
5461            // If a permission review is required for legacy apps we represent
5462            // their permissions as always granted runtime ones since we need
5463            // to keep the review required permission flag per user while an
5464            // install permission's state is shared across all users.
5465            if (mPermissionReviewRequired
5466                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5467                    && bp.isRuntime()) {
5468                return;
5469            }
5470
5471            final PermissionsState permissionsState = ps.getPermissionsState();
5472
5473            final int flags = permissionsState.getPermissionFlags(name, userId);
5474            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5475                throw new SecurityException("Cannot revoke system fixed permission "
5476                        + name + " for package " + packageName);
5477            }
5478            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5479                throw new SecurityException("Cannot revoke policy fixed permission "
5480                        + name + " for package " + packageName);
5481            }
5482
5483            if (bp.isDevelopment()) {
5484                // Development permissions must be handled specially, since they are not
5485                // normal runtime permissions.  For now they apply to all users.
5486                if (permissionsState.revokeInstallPermission(bp) !=
5487                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5488                    scheduleWriteSettingsLocked();
5489                }
5490                return;
5491            }
5492
5493            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5494                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5495                return;
5496            }
5497
5498            if (bp.isRuntime()) {
5499                logPermissionRevoked(mContext, name, packageName);
5500            }
5501
5502            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5503
5504            // Critical, after this call app should never have the permission.
5505            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5506
5507            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5508        }
5509
5510        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5511    }
5512
5513    /**
5514     * Get the first event id for the permission.
5515     *
5516     * <p>There are four events for each permission: <ul>
5517     *     <li>Request permission: first id + 0</li>
5518     *     <li>Grant permission: first id + 1</li>
5519     *     <li>Request for permission denied: first id + 2</li>
5520     *     <li>Revoke permission: first id + 3</li>
5521     * </ul></p>
5522     *
5523     * @param name name of the permission
5524     *
5525     * @return The first event id for the permission
5526     */
5527    private static int getBaseEventId(@NonNull String name) {
5528        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5529
5530        if (eventIdIndex == -1) {
5531            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5532                    || "user".equals(Build.TYPE)) {
5533                Log.i(TAG, "Unknown permission " + name);
5534
5535                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5536            } else {
5537                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5538                //
5539                // Also update
5540                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5541                // - metrics_constants.proto
5542                throw new IllegalStateException("Unknown permission " + name);
5543            }
5544        }
5545
5546        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5547    }
5548
5549    /**
5550     * Log that a permission was revoked.
5551     *
5552     * @param context Context of the caller
5553     * @param name name of the permission
5554     * @param packageName package permission if for
5555     */
5556    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5557            @NonNull String packageName) {
5558        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5559    }
5560
5561    /**
5562     * Log that a permission request was granted.
5563     *
5564     * @param context Context of the caller
5565     * @param name name of the permission
5566     * @param packageName package permission if for
5567     */
5568    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5569            @NonNull String packageName) {
5570        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5571    }
5572
5573    @Override
5574    public void resetRuntimePermissions() {
5575        mContext.enforceCallingOrSelfPermission(
5576                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5577                "revokeRuntimePermission");
5578
5579        int callingUid = Binder.getCallingUid();
5580        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5581            mContext.enforceCallingOrSelfPermission(
5582                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5583                    "resetRuntimePermissions");
5584        }
5585
5586        synchronized (mPackages) {
5587            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5588            for (int userId : UserManagerService.getInstance().getUserIds()) {
5589                final int packageCount = mPackages.size();
5590                for (int i = 0; i < packageCount; i++) {
5591                    PackageParser.Package pkg = mPackages.valueAt(i);
5592                    if (!(pkg.mExtras instanceof PackageSetting)) {
5593                        continue;
5594                    }
5595                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5596                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5597                }
5598            }
5599        }
5600    }
5601
5602    @Override
5603    public int getPermissionFlags(String name, String packageName, int userId) {
5604        if (!sUserManager.exists(userId)) {
5605            return 0;
5606        }
5607
5608        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5609
5610        final int callingUid = Binder.getCallingUid();
5611        enforceCrossUserPermission(callingUid, userId,
5612                true /* requireFullPermission */, false /* checkShell */,
5613                "getPermissionFlags");
5614
5615        synchronized (mPackages) {
5616            final PackageParser.Package pkg = mPackages.get(packageName);
5617            if (pkg == null) {
5618                return 0;
5619            }
5620            final BasePermission bp = mSettings.mPermissions.get(name);
5621            if (bp == null) {
5622                return 0;
5623            }
5624            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5625            if (ps == null
5626                    || filterAppAccessLPr(ps, callingUid, userId)) {
5627                return 0;
5628            }
5629            PermissionsState permissionsState = ps.getPermissionsState();
5630            return permissionsState.getPermissionFlags(name, userId);
5631        }
5632    }
5633
5634    @Override
5635    public void updatePermissionFlags(String name, String packageName, int flagMask,
5636            int flagValues, int userId) {
5637        if (!sUserManager.exists(userId)) {
5638            return;
5639        }
5640
5641        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5642
5643        final int callingUid = Binder.getCallingUid();
5644        enforceCrossUserPermission(callingUid, userId,
5645                true /* requireFullPermission */, true /* checkShell */,
5646                "updatePermissionFlags");
5647
5648        // Only the system can change these flags and nothing else.
5649        if (getCallingUid() != Process.SYSTEM_UID) {
5650            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5651            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5652            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5653            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5654            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5655        }
5656
5657        synchronized (mPackages) {
5658            final PackageParser.Package pkg = mPackages.get(packageName);
5659            if (pkg == null) {
5660                throw new IllegalArgumentException("Unknown package: " + packageName);
5661            }
5662            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5663            if (ps == null
5664                    || filterAppAccessLPr(ps, callingUid, userId)) {
5665                throw new IllegalArgumentException("Unknown package: " + packageName);
5666            }
5667
5668            final BasePermission bp = mSettings.mPermissions.get(name);
5669            if (bp == null) {
5670                throw new IllegalArgumentException("Unknown permission: " + name);
5671            }
5672
5673            PermissionsState permissionsState = ps.getPermissionsState();
5674
5675            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5676
5677            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5678                // Install and runtime permissions are stored in different places,
5679                // so figure out what permission changed and persist the change.
5680                if (permissionsState.getInstallPermissionState(name) != null) {
5681                    scheduleWriteSettingsLocked();
5682                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5683                        || hadState) {
5684                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5685                }
5686            }
5687        }
5688    }
5689
5690    /**
5691     * Update the permission flags for all packages and runtime permissions of a user in order
5692     * to allow device or profile owner to remove POLICY_FIXED.
5693     */
5694    @Override
5695    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5696        if (!sUserManager.exists(userId)) {
5697            return;
5698        }
5699
5700        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5701
5702        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5703                true /* requireFullPermission */, true /* checkShell */,
5704                "updatePermissionFlagsForAllApps");
5705
5706        // Only the system can change system fixed flags.
5707        if (getCallingUid() != Process.SYSTEM_UID) {
5708            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5709            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5710        }
5711
5712        synchronized (mPackages) {
5713            boolean changed = false;
5714            final int packageCount = mPackages.size();
5715            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5716                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5717                final PackageSetting ps = (PackageSetting) pkg.mExtras;
5718                if (ps == null) {
5719                    continue;
5720                }
5721                PermissionsState permissionsState = ps.getPermissionsState();
5722                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5723                        userId, flagMask, flagValues);
5724            }
5725            if (changed) {
5726                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5727            }
5728        }
5729    }
5730
5731    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5732        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5733                != PackageManager.PERMISSION_GRANTED
5734            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5735                != PackageManager.PERMISSION_GRANTED) {
5736            throw new SecurityException(message + " requires "
5737                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5738                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5739        }
5740    }
5741
5742    @Override
5743    public boolean shouldShowRequestPermissionRationale(String permissionName,
5744            String packageName, int userId) {
5745        if (UserHandle.getCallingUserId() != userId) {
5746            mContext.enforceCallingPermission(
5747                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5748                    "canShowRequestPermissionRationale for user " + userId);
5749        }
5750
5751        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5752        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5753            return false;
5754        }
5755
5756        if (checkPermission(permissionName, packageName, userId)
5757                == PackageManager.PERMISSION_GRANTED) {
5758            return false;
5759        }
5760
5761        final int flags;
5762
5763        final long identity = Binder.clearCallingIdentity();
5764        try {
5765            flags = getPermissionFlags(permissionName,
5766                    packageName, userId);
5767        } finally {
5768            Binder.restoreCallingIdentity(identity);
5769        }
5770
5771        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5772                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5773                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5774
5775        if ((flags & fixedFlags) != 0) {
5776            return false;
5777        }
5778
5779        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5780    }
5781
5782    @Override
5783    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5784        mContext.enforceCallingOrSelfPermission(
5785                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5786                "addOnPermissionsChangeListener");
5787
5788        synchronized (mPackages) {
5789            mOnPermissionChangeListeners.addListenerLocked(listener);
5790        }
5791    }
5792
5793    @Override
5794    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5795        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5796            throw new SecurityException("Instant applications don't have access to this method");
5797        }
5798        synchronized (mPackages) {
5799            mOnPermissionChangeListeners.removeListenerLocked(listener);
5800        }
5801    }
5802
5803    @Override
5804    public boolean isProtectedBroadcast(String actionName) {
5805        // allow instant applications
5806        synchronized (mProtectedBroadcasts) {
5807            if (mProtectedBroadcasts.contains(actionName)) {
5808                return true;
5809            } else if (actionName != null) {
5810                // TODO: remove these terrible hacks
5811                if (actionName.startsWith("android.net.netmon.lingerExpired")
5812                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5813                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5814                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5815                    return true;
5816                }
5817            }
5818        }
5819        return false;
5820    }
5821
5822    @Override
5823    public int checkSignatures(String pkg1, String pkg2) {
5824        synchronized (mPackages) {
5825            final PackageParser.Package p1 = mPackages.get(pkg1);
5826            final PackageParser.Package p2 = mPackages.get(pkg2);
5827            if (p1 == null || p1.mExtras == null
5828                    || p2 == null || p2.mExtras == null) {
5829                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5830            }
5831            final int callingUid = Binder.getCallingUid();
5832            final int callingUserId = UserHandle.getUserId(callingUid);
5833            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5834            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5835            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5836                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5837                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5838            }
5839            return compareSignatures(p1.mSignatures, p2.mSignatures);
5840        }
5841    }
5842
5843    @Override
5844    public int checkUidSignatures(int uid1, int uid2) {
5845        final int callingUid = Binder.getCallingUid();
5846        final int callingUserId = UserHandle.getUserId(callingUid);
5847        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5848        // Map to base uids.
5849        uid1 = UserHandle.getAppId(uid1);
5850        uid2 = UserHandle.getAppId(uid2);
5851        // reader
5852        synchronized (mPackages) {
5853            Signature[] s1;
5854            Signature[] s2;
5855            Object obj = mSettings.getUserIdLPr(uid1);
5856            if (obj != null) {
5857                if (obj instanceof SharedUserSetting) {
5858                    if (isCallerInstantApp) {
5859                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5860                    }
5861                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5862                } else if (obj instanceof PackageSetting) {
5863                    final PackageSetting ps = (PackageSetting) obj;
5864                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5865                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5866                    }
5867                    s1 = ps.signatures.mSignatures;
5868                } else {
5869                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5870                }
5871            } else {
5872                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5873            }
5874            obj = mSettings.getUserIdLPr(uid2);
5875            if (obj != null) {
5876                if (obj instanceof SharedUserSetting) {
5877                    if (isCallerInstantApp) {
5878                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5879                    }
5880                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5881                } else if (obj instanceof PackageSetting) {
5882                    final PackageSetting ps = (PackageSetting) obj;
5883                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5884                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5885                    }
5886                    s2 = ps.signatures.mSignatures;
5887                } else {
5888                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5889                }
5890            } else {
5891                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5892            }
5893            return compareSignatures(s1, s2);
5894        }
5895    }
5896
5897    /**
5898     * This method should typically only be used when granting or revoking
5899     * permissions, since the app may immediately restart after this call.
5900     * <p>
5901     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5902     * guard your work against the app being relaunched.
5903     */
5904    private void killUid(int appId, int userId, String reason) {
5905        final long identity = Binder.clearCallingIdentity();
5906        try {
5907            IActivityManager am = ActivityManager.getService();
5908            if (am != null) {
5909                try {
5910                    am.killUid(appId, userId, reason);
5911                } catch (RemoteException e) {
5912                    /* ignore - same process */
5913                }
5914            }
5915        } finally {
5916            Binder.restoreCallingIdentity(identity);
5917        }
5918    }
5919
5920    /**
5921     * Compares two sets of signatures. Returns:
5922     * <br />
5923     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5924     * <br />
5925     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5926     * <br />
5927     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5928     * <br />
5929     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5930     * <br />
5931     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5932     */
5933    static int compareSignatures(Signature[] s1, Signature[] s2) {
5934        if (s1 == null) {
5935            return s2 == null
5936                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5937                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5938        }
5939
5940        if (s2 == null) {
5941            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5942        }
5943
5944        if (s1.length != s2.length) {
5945            return PackageManager.SIGNATURE_NO_MATCH;
5946        }
5947
5948        // Since both signature sets are of size 1, we can compare without HashSets.
5949        if (s1.length == 1) {
5950            return s1[0].equals(s2[0]) ?
5951                    PackageManager.SIGNATURE_MATCH :
5952                    PackageManager.SIGNATURE_NO_MATCH;
5953        }
5954
5955        ArraySet<Signature> set1 = new ArraySet<Signature>();
5956        for (Signature sig : s1) {
5957            set1.add(sig);
5958        }
5959        ArraySet<Signature> set2 = new ArraySet<Signature>();
5960        for (Signature sig : s2) {
5961            set2.add(sig);
5962        }
5963        // Make sure s2 contains all signatures in s1.
5964        if (set1.equals(set2)) {
5965            return PackageManager.SIGNATURE_MATCH;
5966        }
5967        return PackageManager.SIGNATURE_NO_MATCH;
5968    }
5969
5970    /**
5971     * If the database version for this type of package (internal storage or
5972     * external storage) is less than the version where package signatures
5973     * were updated, return true.
5974     */
5975    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5976        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5977        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5978    }
5979
5980    /**
5981     * Used for backward compatibility to make sure any packages with
5982     * certificate chains get upgraded to the new style. {@code existingSigs}
5983     * will be in the old format (since they were stored on disk from before the
5984     * system upgrade) and {@code scannedSigs} will be in the newer format.
5985     */
5986    private int compareSignaturesCompat(PackageSignatures existingSigs,
5987            PackageParser.Package scannedPkg) {
5988        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5989            return PackageManager.SIGNATURE_NO_MATCH;
5990        }
5991
5992        ArraySet<Signature> existingSet = new ArraySet<Signature>();
5993        for (Signature sig : existingSigs.mSignatures) {
5994            existingSet.add(sig);
5995        }
5996        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
5997        for (Signature sig : scannedPkg.mSignatures) {
5998            try {
5999                Signature[] chainSignatures = sig.getChainSignatures();
6000                for (Signature chainSig : chainSignatures) {
6001                    scannedCompatSet.add(chainSig);
6002                }
6003            } catch (CertificateEncodingException e) {
6004                scannedCompatSet.add(sig);
6005            }
6006        }
6007        /*
6008         * Make sure the expanded scanned set contains all signatures in the
6009         * existing one.
6010         */
6011        if (scannedCompatSet.equals(existingSet)) {
6012            // Migrate the old signatures to the new scheme.
6013            existingSigs.assignSignatures(scannedPkg.mSignatures);
6014            // The new KeySets will be re-added later in the scanning process.
6015            synchronized (mPackages) {
6016                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
6017            }
6018            return PackageManager.SIGNATURE_MATCH;
6019        }
6020        return PackageManager.SIGNATURE_NO_MATCH;
6021    }
6022
6023    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6024        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6025        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6026    }
6027
6028    private int compareSignaturesRecover(PackageSignatures existingSigs,
6029            PackageParser.Package scannedPkg) {
6030        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
6031            return PackageManager.SIGNATURE_NO_MATCH;
6032        }
6033
6034        String msg = null;
6035        try {
6036            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
6037                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
6038                        + scannedPkg.packageName);
6039                return PackageManager.SIGNATURE_MATCH;
6040            }
6041        } catch (CertificateException e) {
6042            msg = e.getMessage();
6043        }
6044
6045        logCriticalInfo(Log.INFO,
6046                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
6047        return PackageManager.SIGNATURE_NO_MATCH;
6048    }
6049
6050    @Override
6051    public List<String> getAllPackages() {
6052        final int callingUid = Binder.getCallingUid();
6053        final int callingUserId = UserHandle.getUserId(callingUid);
6054        synchronized (mPackages) {
6055            if (canViewInstantApps(callingUid, callingUserId)) {
6056                return new ArrayList<String>(mPackages.keySet());
6057            }
6058            final String instantAppPkgName = getInstantAppPackageName(callingUid);
6059            final List<String> result = new ArrayList<>();
6060            if (instantAppPkgName != null) {
6061                // caller is an instant application; filter unexposed applications
6062                for (PackageParser.Package pkg : mPackages.values()) {
6063                    if (!pkg.visibleToInstantApps) {
6064                        continue;
6065                    }
6066                    result.add(pkg.packageName);
6067                }
6068            } else {
6069                // caller is a normal application; filter instant applications
6070                for (PackageParser.Package pkg : mPackages.values()) {
6071                    final PackageSetting ps =
6072                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6073                    if (ps != null
6074                            && ps.getInstantApp(callingUserId)
6075                            && !mInstantAppRegistry.isInstantAccessGranted(
6076                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6077                        continue;
6078                    }
6079                    result.add(pkg.packageName);
6080                }
6081            }
6082            return result;
6083        }
6084    }
6085
6086    @Override
6087    public String[] getPackagesForUid(int uid) {
6088        final int callingUid = Binder.getCallingUid();
6089        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6090        final int userId = UserHandle.getUserId(uid);
6091        uid = UserHandle.getAppId(uid);
6092        // reader
6093        synchronized (mPackages) {
6094            Object obj = mSettings.getUserIdLPr(uid);
6095            if (obj instanceof SharedUserSetting) {
6096                if (isCallerInstantApp) {
6097                    return null;
6098                }
6099                final SharedUserSetting sus = (SharedUserSetting) obj;
6100                final int N = sus.packages.size();
6101                String[] res = new String[N];
6102                final Iterator<PackageSetting> it = sus.packages.iterator();
6103                int i = 0;
6104                while (it.hasNext()) {
6105                    PackageSetting ps = it.next();
6106                    if (ps.getInstalled(userId)) {
6107                        res[i++] = ps.name;
6108                    } else {
6109                        res = ArrayUtils.removeElement(String.class, res, res[i]);
6110                    }
6111                }
6112                return res;
6113            } else if (obj instanceof PackageSetting) {
6114                final PackageSetting ps = (PackageSetting) obj;
6115                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6116                    return new String[]{ps.name};
6117                }
6118            }
6119        }
6120        return null;
6121    }
6122
6123    @Override
6124    public String getNameForUid(int uid) {
6125        final int callingUid = Binder.getCallingUid();
6126        if (getInstantAppPackageName(callingUid) != null) {
6127            return null;
6128        }
6129        synchronized (mPackages) {
6130            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6131            if (obj instanceof SharedUserSetting) {
6132                final SharedUserSetting sus = (SharedUserSetting) obj;
6133                return sus.name + ":" + sus.userId;
6134            } else if (obj instanceof PackageSetting) {
6135                final PackageSetting ps = (PackageSetting) obj;
6136                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6137                    return null;
6138                }
6139                return ps.name;
6140            }
6141        }
6142        return null;
6143    }
6144
6145    @Override
6146    public int getUidForSharedUser(String sharedUserName) {
6147        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6148            return -1;
6149        }
6150        if (sharedUserName == null) {
6151            return -1;
6152        }
6153        // reader
6154        synchronized (mPackages) {
6155            SharedUserSetting suid;
6156            try {
6157                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6158                if (suid != null) {
6159                    return suid.userId;
6160                }
6161            } catch (PackageManagerException ignore) {
6162                // can't happen, but, still need to catch it
6163            }
6164            return -1;
6165        }
6166    }
6167
6168    @Override
6169    public int getFlagsForUid(int uid) {
6170        final int callingUid = Binder.getCallingUid();
6171        if (getInstantAppPackageName(callingUid) != null) {
6172            return 0;
6173        }
6174        synchronized (mPackages) {
6175            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6176            if (obj instanceof SharedUserSetting) {
6177                final SharedUserSetting sus = (SharedUserSetting) obj;
6178                return sus.pkgFlags;
6179            } else if (obj instanceof PackageSetting) {
6180                final PackageSetting ps = (PackageSetting) obj;
6181                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6182                    return 0;
6183                }
6184                return ps.pkgFlags;
6185            }
6186        }
6187        return 0;
6188    }
6189
6190    @Override
6191    public int getPrivateFlagsForUid(int uid) {
6192        final int callingUid = Binder.getCallingUid();
6193        if (getInstantAppPackageName(callingUid) != null) {
6194            return 0;
6195        }
6196        synchronized (mPackages) {
6197            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6198            if (obj instanceof SharedUserSetting) {
6199                final SharedUserSetting sus = (SharedUserSetting) obj;
6200                return sus.pkgPrivateFlags;
6201            } else if (obj instanceof PackageSetting) {
6202                final PackageSetting ps = (PackageSetting) obj;
6203                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6204                    return 0;
6205                }
6206                return ps.pkgPrivateFlags;
6207            }
6208        }
6209        return 0;
6210    }
6211
6212    @Override
6213    public boolean isUidPrivileged(int uid) {
6214        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6215            return false;
6216        }
6217        uid = UserHandle.getAppId(uid);
6218        // reader
6219        synchronized (mPackages) {
6220            Object obj = mSettings.getUserIdLPr(uid);
6221            if (obj instanceof SharedUserSetting) {
6222                final SharedUserSetting sus = (SharedUserSetting) obj;
6223                final Iterator<PackageSetting> it = sus.packages.iterator();
6224                while (it.hasNext()) {
6225                    if (it.next().isPrivileged()) {
6226                        return true;
6227                    }
6228                }
6229            } else if (obj instanceof PackageSetting) {
6230                final PackageSetting ps = (PackageSetting) obj;
6231                return ps.isPrivileged();
6232            }
6233        }
6234        return false;
6235    }
6236
6237    @Override
6238    public String[] getAppOpPermissionPackages(String permissionName) {
6239        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6240            return null;
6241        }
6242        synchronized (mPackages) {
6243            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6244            if (pkgs == null) {
6245                return null;
6246            }
6247            return pkgs.toArray(new String[pkgs.size()]);
6248        }
6249    }
6250
6251    @Override
6252    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6253            int flags, int userId) {
6254        return resolveIntentInternal(
6255                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6256    }
6257
6258    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6259            int flags, int userId, boolean resolveForStart) {
6260        try {
6261            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6262
6263            if (!sUserManager.exists(userId)) return null;
6264            final int callingUid = Binder.getCallingUid();
6265            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6266            enforceCrossUserPermission(callingUid, userId,
6267                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6268
6269            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6270            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6271                    flags, callingUid, userId, resolveForStart);
6272            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6273
6274            final ResolveInfo bestChoice =
6275                    chooseBestActivity(intent, resolvedType, flags, query, userId);
6276            return bestChoice;
6277        } finally {
6278            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6279        }
6280    }
6281
6282    @Override
6283    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6284        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6285            throw new SecurityException(
6286                    "findPersistentPreferredActivity can only be run by the system");
6287        }
6288        if (!sUserManager.exists(userId)) {
6289            return null;
6290        }
6291        final int callingUid = Binder.getCallingUid();
6292        intent = updateIntentForResolve(intent);
6293        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6294        final int flags = updateFlagsForResolve(
6295                0, userId, intent, callingUid, false /*includeInstantApps*/);
6296        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6297                userId);
6298        synchronized (mPackages) {
6299            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6300                    userId);
6301        }
6302    }
6303
6304    @Override
6305    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6306            IntentFilter filter, int match, ComponentName activity) {
6307        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6308            return;
6309        }
6310        final int userId = UserHandle.getCallingUserId();
6311        if (DEBUG_PREFERRED) {
6312            Log.v(TAG, "setLastChosenActivity intent=" + intent
6313                + " resolvedType=" + resolvedType
6314                + " flags=" + flags
6315                + " filter=" + filter
6316                + " match=" + match
6317                + " activity=" + activity);
6318            filter.dump(new PrintStreamPrinter(System.out), "    ");
6319        }
6320        intent.setComponent(null);
6321        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6322                userId);
6323        // Find any earlier preferred or last chosen entries and nuke them
6324        findPreferredActivity(intent, resolvedType,
6325                flags, query, 0, false, true, false, userId);
6326        // Add the new activity as the last chosen for this filter
6327        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6328                "Setting last chosen");
6329    }
6330
6331    @Override
6332    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6333        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6334            return null;
6335        }
6336        final int userId = UserHandle.getCallingUserId();
6337        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6338        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6339                userId);
6340        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6341                false, false, false, userId);
6342    }
6343
6344    /**
6345     * Returns whether or not instant apps have been disabled remotely.
6346     */
6347    private boolean isEphemeralDisabled() {
6348        return mEphemeralAppsDisabled;
6349    }
6350
6351    private boolean isInstantAppAllowed(
6352            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6353            boolean skipPackageCheck) {
6354        if (mInstantAppResolverConnection == null) {
6355            return false;
6356        }
6357        if (mInstantAppInstallerActivity == null) {
6358            return false;
6359        }
6360        if (intent.getComponent() != null) {
6361            return false;
6362        }
6363        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6364            return false;
6365        }
6366        if (!skipPackageCheck && intent.getPackage() != null) {
6367            return false;
6368        }
6369        final boolean isWebUri = hasWebURI(intent);
6370        if (!isWebUri || intent.getData().getHost() == null) {
6371            return false;
6372        }
6373        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6374        // Or if there's already an ephemeral app installed that handles the action
6375        synchronized (mPackages) {
6376            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6377            for (int n = 0; n < count; n++) {
6378                final ResolveInfo info = resolvedActivities.get(n);
6379                final String packageName = info.activityInfo.packageName;
6380                final PackageSetting ps = mSettings.mPackages.get(packageName);
6381                if (ps != null) {
6382                    // only check domain verification status if the app is not a browser
6383                    if (!info.handleAllWebDataURI) {
6384                        // Try to get the status from User settings first
6385                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6386                        final int status = (int) (packedStatus >> 32);
6387                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6388                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6389                            if (DEBUG_EPHEMERAL) {
6390                                Slog.v(TAG, "DENY instant app;"
6391                                    + " pkg: " + packageName + ", status: " + status);
6392                            }
6393                            return false;
6394                        }
6395                    }
6396                    if (ps.getInstantApp(userId)) {
6397                        if (DEBUG_EPHEMERAL) {
6398                            Slog.v(TAG, "DENY instant app installed;"
6399                                    + " pkg: " + packageName);
6400                        }
6401                        return false;
6402                    }
6403                }
6404            }
6405        }
6406        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6407        return true;
6408    }
6409
6410    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6411            Intent origIntent, String resolvedType, String callingPackage,
6412            Bundle verificationBundle, int userId) {
6413        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6414                new InstantAppRequest(responseObj, origIntent, resolvedType,
6415                        callingPackage, userId, verificationBundle));
6416        mHandler.sendMessage(msg);
6417    }
6418
6419    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6420            int flags, List<ResolveInfo> query, int userId) {
6421        if (query != null) {
6422            final int N = query.size();
6423            if (N == 1) {
6424                return query.get(0);
6425            } else if (N > 1) {
6426                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6427                // If there is more than one activity with the same priority,
6428                // then let the user decide between them.
6429                ResolveInfo r0 = query.get(0);
6430                ResolveInfo r1 = query.get(1);
6431                if (DEBUG_INTENT_MATCHING || debug) {
6432                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6433                            + r1.activityInfo.name + "=" + r1.priority);
6434                }
6435                // If the first activity has a higher priority, or a different
6436                // default, then it is always desirable to pick it.
6437                if (r0.priority != r1.priority
6438                        || r0.preferredOrder != r1.preferredOrder
6439                        || r0.isDefault != r1.isDefault) {
6440                    return query.get(0);
6441                }
6442                // If we have saved a preference for a preferred activity for
6443                // this Intent, use that.
6444                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6445                        flags, query, r0.priority, true, false, debug, userId);
6446                if (ri != null) {
6447                    return ri;
6448                }
6449                // If we have an ephemeral app, use it
6450                for (int i = 0; i < N; i++) {
6451                    ri = query.get(i);
6452                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6453                        final String packageName = ri.activityInfo.packageName;
6454                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6455                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6456                        final int status = (int)(packedStatus >> 32);
6457                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6458                            return ri;
6459                        }
6460                    }
6461                }
6462                ri = new ResolveInfo(mResolveInfo);
6463                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6464                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6465                // If all of the options come from the same package, show the application's
6466                // label and icon instead of the generic resolver's.
6467                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6468                // and then throw away the ResolveInfo itself, meaning that the caller loses
6469                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6470                // a fallback for this case; we only set the target package's resources on
6471                // the ResolveInfo, not the ActivityInfo.
6472                final String intentPackage = intent.getPackage();
6473                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6474                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6475                    ri.resolvePackageName = intentPackage;
6476                    if (userNeedsBadging(userId)) {
6477                        ri.noResourceId = true;
6478                    } else {
6479                        ri.icon = appi.icon;
6480                    }
6481                    ri.iconResourceId = appi.icon;
6482                    ri.labelRes = appi.labelRes;
6483                }
6484                ri.activityInfo.applicationInfo = new ApplicationInfo(
6485                        ri.activityInfo.applicationInfo);
6486                if (userId != 0) {
6487                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6488                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6489                }
6490                // Make sure that the resolver is displayable in car mode
6491                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6492                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6493                return ri;
6494            }
6495        }
6496        return null;
6497    }
6498
6499    /**
6500     * Return true if the given list is not empty and all of its contents have
6501     * an activityInfo with the given package name.
6502     */
6503    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6504        if (ArrayUtils.isEmpty(list)) {
6505            return false;
6506        }
6507        for (int i = 0, N = list.size(); i < N; i++) {
6508            final ResolveInfo ri = list.get(i);
6509            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6510            if (ai == null || !packageName.equals(ai.packageName)) {
6511                return false;
6512            }
6513        }
6514        return true;
6515    }
6516
6517    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6518            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6519        final int N = query.size();
6520        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6521                .get(userId);
6522        // Get the list of persistent preferred activities that handle the intent
6523        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6524        List<PersistentPreferredActivity> pprefs = ppir != null
6525                ? ppir.queryIntent(intent, resolvedType,
6526                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6527                        userId)
6528                : null;
6529        if (pprefs != null && pprefs.size() > 0) {
6530            final int M = pprefs.size();
6531            for (int i=0; i<M; i++) {
6532                final PersistentPreferredActivity ppa = pprefs.get(i);
6533                if (DEBUG_PREFERRED || debug) {
6534                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6535                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6536                            + "\n  component=" + ppa.mComponent);
6537                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6538                }
6539                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6540                        flags | MATCH_DISABLED_COMPONENTS, userId);
6541                if (DEBUG_PREFERRED || debug) {
6542                    Slog.v(TAG, "Found persistent preferred activity:");
6543                    if (ai != null) {
6544                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6545                    } else {
6546                        Slog.v(TAG, "  null");
6547                    }
6548                }
6549                if (ai == null) {
6550                    // This previously registered persistent preferred activity
6551                    // component is no longer known. Ignore it and do NOT remove it.
6552                    continue;
6553                }
6554                for (int j=0; j<N; j++) {
6555                    final ResolveInfo ri = query.get(j);
6556                    if (!ri.activityInfo.applicationInfo.packageName
6557                            .equals(ai.applicationInfo.packageName)) {
6558                        continue;
6559                    }
6560                    if (!ri.activityInfo.name.equals(ai.name)) {
6561                        continue;
6562                    }
6563                    //  Found a persistent preference that can handle the intent.
6564                    if (DEBUG_PREFERRED || debug) {
6565                        Slog.v(TAG, "Returning persistent preferred activity: " +
6566                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6567                    }
6568                    return ri;
6569                }
6570            }
6571        }
6572        return null;
6573    }
6574
6575    // TODO: handle preferred activities missing while user has amnesia
6576    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6577            List<ResolveInfo> query, int priority, boolean always,
6578            boolean removeMatches, boolean debug, int userId) {
6579        if (!sUserManager.exists(userId)) return null;
6580        final int callingUid = Binder.getCallingUid();
6581        flags = updateFlagsForResolve(
6582                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6583        intent = updateIntentForResolve(intent);
6584        // writer
6585        synchronized (mPackages) {
6586            // Try to find a matching persistent preferred activity.
6587            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6588                    debug, userId);
6589
6590            // If a persistent preferred activity matched, use it.
6591            if (pri != null) {
6592                return pri;
6593            }
6594
6595            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6596            // Get the list of preferred activities that handle the intent
6597            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6598            List<PreferredActivity> prefs = pir != null
6599                    ? pir.queryIntent(intent, resolvedType,
6600                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6601                            userId)
6602                    : null;
6603            if (prefs != null && prefs.size() > 0) {
6604                boolean changed = false;
6605                try {
6606                    // First figure out how good the original match set is.
6607                    // We will only allow preferred activities that came
6608                    // from the same match quality.
6609                    int match = 0;
6610
6611                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6612
6613                    final int N = query.size();
6614                    for (int j=0; j<N; j++) {
6615                        final ResolveInfo ri = query.get(j);
6616                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6617                                + ": 0x" + Integer.toHexString(match));
6618                        if (ri.match > match) {
6619                            match = ri.match;
6620                        }
6621                    }
6622
6623                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6624                            + Integer.toHexString(match));
6625
6626                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6627                    final int M = prefs.size();
6628                    for (int i=0; i<M; i++) {
6629                        final PreferredActivity pa = prefs.get(i);
6630                        if (DEBUG_PREFERRED || debug) {
6631                            Slog.v(TAG, "Checking PreferredActivity ds="
6632                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6633                                    + "\n  component=" + pa.mPref.mComponent);
6634                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6635                        }
6636                        if (pa.mPref.mMatch != match) {
6637                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6638                                    + Integer.toHexString(pa.mPref.mMatch));
6639                            continue;
6640                        }
6641                        // If it's not an "always" type preferred activity and that's what we're
6642                        // looking for, skip it.
6643                        if (always && !pa.mPref.mAlways) {
6644                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6645                            continue;
6646                        }
6647                        final ActivityInfo ai = getActivityInfo(
6648                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6649                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6650                                userId);
6651                        if (DEBUG_PREFERRED || debug) {
6652                            Slog.v(TAG, "Found preferred activity:");
6653                            if (ai != null) {
6654                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6655                            } else {
6656                                Slog.v(TAG, "  null");
6657                            }
6658                        }
6659                        if (ai == null) {
6660                            // This previously registered preferred activity
6661                            // component is no longer known.  Most likely an update
6662                            // to the app was installed and in the new version this
6663                            // component no longer exists.  Clean it up by removing
6664                            // it from the preferred activities list, and skip it.
6665                            Slog.w(TAG, "Removing dangling preferred activity: "
6666                                    + pa.mPref.mComponent);
6667                            pir.removeFilter(pa);
6668                            changed = true;
6669                            continue;
6670                        }
6671                        for (int j=0; j<N; j++) {
6672                            final ResolveInfo ri = query.get(j);
6673                            if (!ri.activityInfo.applicationInfo.packageName
6674                                    .equals(ai.applicationInfo.packageName)) {
6675                                continue;
6676                            }
6677                            if (!ri.activityInfo.name.equals(ai.name)) {
6678                                continue;
6679                            }
6680
6681                            if (removeMatches) {
6682                                pir.removeFilter(pa);
6683                                changed = true;
6684                                if (DEBUG_PREFERRED) {
6685                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6686                                }
6687                                break;
6688                            }
6689
6690                            // Okay we found a previously set preferred or last chosen app.
6691                            // If the result set is different from when this
6692                            // was created, we need to clear it and re-ask the
6693                            // user their preference, if we're looking for an "always" type entry.
6694                            if (always && !pa.mPref.sameSet(query)) {
6695                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6696                                        + intent + " type " + resolvedType);
6697                                if (DEBUG_PREFERRED) {
6698                                    Slog.v(TAG, "Removing preferred activity since set changed "
6699                                            + pa.mPref.mComponent);
6700                                }
6701                                pir.removeFilter(pa);
6702                                // Re-add the filter as a "last chosen" entry (!always)
6703                                PreferredActivity lastChosen = new PreferredActivity(
6704                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6705                                pir.addFilter(lastChosen);
6706                                changed = true;
6707                                return null;
6708                            }
6709
6710                            // Yay! Either the set matched or we're looking for the last chosen
6711                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6712                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6713                            return ri;
6714                        }
6715                    }
6716                } finally {
6717                    if (changed) {
6718                        if (DEBUG_PREFERRED) {
6719                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6720                        }
6721                        scheduleWritePackageRestrictionsLocked(userId);
6722                    }
6723                }
6724            }
6725        }
6726        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6727        return null;
6728    }
6729
6730    /*
6731     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6732     */
6733    @Override
6734    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6735            int targetUserId) {
6736        mContext.enforceCallingOrSelfPermission(
6737                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6738        List<CrossProfileIntentFilter> matches =
6739                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6740        if (matches != null) {
6741            int size = matches.size();
6742            for (int i = 0; i < size; i++) {
6743                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6744            }
6745        }
6746        if (hasWebURI(intent)) {
6747            // cross-profile app linking works only towards the parent.
6748            final int callingUid = Binder.getCallingUid();
6749            final UserInfo parent = getProfileParent(sourceUserId);
6750            synchronized(mPackages) {
6751                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6752                        false /*includeInstantApps*/);
6753                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6754                        intent, resolvedType, flags, sourceUserId, parent.id);
6755                return xpDomainInfo != null;
6756            }
6757        }
6758        return false;
6759    }
6760
6761    private UserInfo getProfileParent(int userId) {
6762        final long identity = Binder.clearCallingIdentity();
6763        try {
6764            return sUserManager.getProfileParent(userId);
6765        } finally {
6766            Binder.restoreCallingIdentity(identity);
6767        }
6768    }
6769
6770    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6771            String resolvedType, int userId) {
6772        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6773        if (resolver != null) {
6774            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6775        }
6776        return null;
6777    }
6778
6779    @Override
6780    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6781            String resolvedType, int flags, int userId) {
6782        try {
6783            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6784
6785            return new ParceledListSlice<>(
6786                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6787        } finally {
6788            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6789        }
6790    }
6791
6792    /**
6793     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6794     * instant, returns {@code null}.
6795     */
6796    private String getInstantAppPackageName(int callingUid) {
6797        synchronized (mPackages) {
6798            // If the caller is an isolated app use the owner's uid for the lookup.
6799            if (Process.isIsolated(callingUid)) {
6800                callingUid = mIsolatedOwners.get(callingUid);
6801            }
6802            final int appId = UserHandle.getAppId(callingUid);
6803            final Object obj = mSettings.getUserIdLPr(appId);
6804            if (obj instanceof PackageSetting) {
6805                final PackageSetting ps = (PackageSetting) obj;
6806                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6807                return isInstantApp ? ps.pkg.packageName : null;
6808            }
6809        }
6810        return null;
6811    }
6812
6813    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6814            String resolvedType, int flags, int userId) {
6815        return queryIntentActivitiesInternal(
6816                intent, resolvedType, flags, Binder.getCallingUid(), userId, false);
6817    }
6818
6819    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6820            String resolvedType, int flags, int filterCallingUid, int userId,
6821            boolean resolveForStart) {
6822        if (!sUserManager.exists(userId)) return Collections.emptyList();
6823        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6824        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6825                false /* requireFullPermission */, false /* checkShell */,
6826                "query intent activities");
6827        final String pkgName = intent.getPackage();
6828        ComponentName comp = intent.getComponent();
6829        if (comp == null) {
6830            if (intent.getSelector() != null) {
6831                intent = intent.getSelector();
6832                comp = intent.getComponent();
6833            }
6834        }
6835
6836        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6837                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6838        if (comp != null) {
6839            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6840            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6841            if (ai != null) {
6842                // When specifying an explicit component, we prevent the activity from being
6843                // used when either 1) the calling package is normal and the activity is within
6844                // an ephemeral application or 2) the calling package is ephemeral and the
6845                // activity is not visible to ephemeral applications.
6846                final boolean matchInstantApp =
6847                        (flags & PackageManager.MATCH_INSTANT) != 0;
6848                final boolean matchVisibleToInstantAppOnly =
6849                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6850                final boolean matchExplicitlyVisibleOnly =
6851                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6852                final boolean isCallerInstantApp =
6853                        instantAppPkgName != null;
6854                final boolean isTargetSameInstantApp =
6855                        comp.getPackageName().equals(instantAppPkgName);
6856                final boolean isTargetInstantApp =
6857                        (ai.applicationInfo.privateFlags
6858                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6859                final boolean isTargetVisibleToInstantApp =
6860                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6861                final boolean isTargetExplicitlyVisibleToInstantApp =
6862                        isTargetVisibleToInstantApp
6863                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6864                final boolean isTargetHiddenFromInstantApp =
6865                        !isTargetVisibleToInstantApp
6866                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6867                final boolean blockResolution =
6868                        !isTargetSameInstantApp
6869                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6870                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6871                                        && isTargetHiddenFromInstantApp));
6872                if (!blockResolution) {
6873                    final ResolveInfo ri = new ResolveInfo();
6874                    ri.activityInfo = ai;
6875                    list.add(ri);
6876                }
6877            }
6878            return applyPostResolutionFilter(list, instantAppPkgName);
6879        }
6880
6881        // reader
6882        boolean sortResult = false;
6883        boolean addEphemeral = false;
6884        List<ResolveInfo> result;
6885        final boolean ephemeralDisabled = isEphemeralDisabled();
6886        synchronized (mPackages) {
6887            if (pkgName == null) {
6888                List<CrossProfileIntentFilter> matchingFilters =
6889                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6890                // Check for results that need to skip the current profile.
6891                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6892                        resolvedType, flags, userId);
6893                if (xpResolveInfo != null) {
6894                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6895                    xpResult.add(xpResolveInfo);
6896                    return applyPostResolutionFilter(
6897                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6898                }
6899
6900                // Check for results in the current profile.
6901                result = filterIfNotSystemUser(mActivities.queryIntent(
6902                        intent, resolvedType, flags, userId), userId);
6903                addEphemeral = !ephemeralDisabled
6904                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6905                // Check for cross profile results.
6906                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6907                xpResolveInfo = queryCrossProfileIntents(
6908                        matchingFilters, intent, resolvedType, flags, userId,
6909                        hasNonNegativePriorityResult);
6910                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6911                    boolean isVisibleToUser = filterIfNotSystemUser(
6912                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6913                    if (isVisibleToUser) {
6914                        result.add(xpResolveInfo);
6915                        sortResult = true;
6916                    }
6917                }
6918                if (hasWebURI(intent)) {
6919                    CrossProfileDomainInfo xpDomainInfo = null;
6920                    final UserInfo parent = getProfileParent(userId);
6921                    if (parent != null) {
6922                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6923                                flags, userId, parent.id);
6924                    }
6925                    if (xpDomainInfo != null) {
6926                        if (xpResolveInfo != null) {
6927                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6928                            // in the result.
6929                            result.remove(xpResolveInfo);
6930                        }
6931                        if (result.size() == 0 && !addEphemeral) {
6932                            // No result in current profile, but found candidate in parent user.
6933                            // And we are not going to add emphemeral app, so we can return the
6934                            // result straight away.
6935                            result.add(xpDomainInfo.resolveInfo);
6936                            return applyPostResolutionFilter(result, instantAppPkgName);
6937                        }
6938                    } else if (result.size() <= 1 && !addEphemeral) {
6939                        // No result in parent user and <= 1 result in current profile, and we
6940                        // are not going to add emphemeral app, so we can return the result without
6941                        // further processing.
6942                        return applyPostResolutionFilter(result, instantAppPkgName);
6943                    }
6944                    // We have more than one candidate (combining results from current and parent
6945                    // profile), so we need filtering and sorting.
6946                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6947                            intent, flags, result, xpDomainInfo, userId);
6948                    sortResult = true;
6949                }
6950            } else {
6951                final PackageParser.Package pkg = mPackages.get(pkgName);
6952                result = null;
6953                if (pkg != null) {
6954                    result = filterIfNotSystemUser(
6955                            mActivities.queryIntentForPackage(
6956                                    intent, resolvedType, flags, pkg.activities, userId),
6957                            userId);
6958                }
6959                if (result == null || result.size() == 0) {
6960                    // the caller wants to resolve for a particular package; however, there
6961                    // were no installed results, so, try to find an ephemeral result
6962                    addEphemeral = !ephemeralDisabled
6963                            && isInstantAppAllowed(
6964                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6965                    if (result == null) {
6966                        result = new ArrayList<>();
6967                    }
6968                }
6969            }
6970        }
6971        if (addEphemeral) {
6972            result = maybeAddInstantAppInstaller(result, intent, resolvedType, flags, userId);
6973        }
6974        if (sortResult) {
6975            Collections.sort(result, mResolvePrioritySorter);
6976        }
6977        return applyPostResolutionFilter(result, instantAppPkgName);
6978    }
6979
6980    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6981            String resolvedType, int flags, int userId) {
6982        // first, check to see if we've got an instant app already installed
6983        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6984        ResolveInfo localInstantApp = null;
6985        boolean blockResolution = false;
6986        if (!alreadyResolvedLocally) {
6987            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6988                    flags
6989                        | PackageManager.GET_RESOLVED_FILTER
6990                        | PackageManager.MATCH_INSTANT
6991                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6992                    userId);
6993            for (int i = instantApps.size() - 1; i >= 0; --i) {
6994                final ResolveInfo info = instantApps.get(i);
6995                final String packageName = info.activityInfo.packageName;
6996                final PackageSetting ps = mSettings.mPackages.get(packageName);
6997                if (ps.getInstantApp(userId)) {
6998                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6999                    final int status = (int)(packedStatus >> 32);
7000                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7001                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7002                        // there's a local instant application installed, but, the user has
7003                        // chosen to never use it; skip resolution and don't acknowledge
7004                        // an instant application is even available
7005                        if (DEBUG_EPHEMERAL) {
7006                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7007                        }
7008                        blockResolution = true;
7009                        break;
7010                    } else {
7011                        // we have a locally installed instant application; skip resolution
7012                        // but acknowledge there's an instant application available
7013                        if (DEBUG_EPHEMERAL) {
7014                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7015                        }
7016                        localInstantApp = info;
7017                        break;
7018                    }
7019                }
7020            }
7021        }
7022        // no app installed, let's see if one's available
7023        AuxiliaryResolveInfo auxiliaryResponse = null;
7024        if (!blockResolution) {
7025            if (localInstantApp == null) {
7026                // we don't have an instant app locally, resolve externally
7027                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7028                final InstantAppRequest requestObject = new InstantAppRequest(
7029                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
7030                        null /*callingPackage*/, userId, null /*verificationBundle*/);
7031                auxiliaryResponse =
7032                        InstantAppResolver.doInstantAppResolutionPhaseOne(
7033                                mContext, mInstantAppResolverConnection, requestObject);
7034                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7035            } else {
7036                // we have an instant application locally, but, we can't admit that since
7037                // callers shouldn't be able to determine prior browsing. create a dummy
7038                // auxiliary response so the downstream code behaves as if there's an
7039                // instant application available externally. when it comes time to start
7040                // the instant application, we'll do the right thing.
7041                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7042                auxiliaryResponse = new AuxiliaryResolveInfo(
7043                        ai.packageName, null /*splitName*/, ai.versionCode, null /*failureIntent*/);
7044            }
7045        }
7046        if (auxiliaryResponse != null) {
7047            if (DEBUG_EPHEMERAL) {
7048                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7049            }
7050            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7051            final PackageSetting ps =
7052                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7053            if (ps != null) {
7054                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7055                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7056                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
7057                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7058                // make sure this resolver is the default
7059                ephemeralInstaller.isDefault = true;
7060                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7061                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7062                // add a non-generic filter
7063                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
7064                ephemeralInstaller.filter.addDataPath(
7065                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7066                ephemeralInstaller.isInstantAppAvailable = true;
7067                result.add(ephemeralInstaller);
7068            }
7069        }
7070        return result;
7071    }
7072
7073    private static class CrossProfileDomainInfo {
7074        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7075        ResolveInfo resolveInfo;
7076        /* Best domain verification status of the activities found in the other profile */
7077        int bestDomainVerificationStatus;
7078    }
7079
7080    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7081            String resolvedType, int flags, int sourceUserId, int parentUserId) {
7082        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7083                sourceUserId)) {
7084            return null;
7085        }
7086        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7087                resolvedType, flags, parentUserId);
7088
7089        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7090            return null;
7091        }
7092        CrossProfileDomainInfo result = null;
7093        int size = resultTargetUser.size();
7094        for (int i = 0; i < size; i++) {
7095            ResolveInfo riTargetUser = resultTargetUser.get(i);
7096            // Intent filter verification is only for filters that specify a host. So don't return
7097            // those that handle all web uris.
7098            if (riTargetUser.handleAllWebDataURI) {
7099                continue;
7100            }
7101            String packageName = riTargetUser.activityInfo.packageName;
7102            PackageSetting ps = mSettings.mPackages.get(packageName);
7103            if (ps == null) {
7104                continue;
7105            }
7106            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7107            int status = (int)(verificationState >> 32);
7108            if (result == null) {
7109                result = new CrossProfileDomainInfo();
7110                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7111                        sourceUserId, parentUserId);
7112                result.bestDomainVerificationStatus = status;
7113            } else {
7114                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7115                        result.bestDomainVerificationStatus);
7116            }
7117        }
7118        // Don't consider matches with status NEVER across profiles.
7119        if (result != null && result.bestDomainVerificationStatus
7120                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7121            return null;
7122        }
7123        return result;
7124    }
7125
7126    /**
7127     * Verification statuses are ordered from the worse to the best, except for
7128     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7129     */
7130    private int bestDomainVerificationStatus(int status1, int status2) {
7131        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7132            return status2;
7133        }
7134        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7135            return status1;
7136        }
7137        return (int) MathUtils.max(status1, status2);
7138    }
7139
7140    private boolean isUserEnabled(int userId) {
7141        long callingId = Binder.clearCallingIdentity();
7142        try {
7143            UserInfo userInfo = sUserManager.getUserInfo(userId);
7144            return userInfo != null && userInfo.isEnabled();
7145        } finally {
7146            Binder.restoreCallingIdentity(callingId);
7147        }
7148    }
7149
7150    /**
7151     * Filter out activities with systemUserOnly flag set, when current user is not System.
7152     *
7153     * @return filtered list
7154     */
7155    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7156        if (userId == UserHandle.USER_SYSTEM) {
7157            return resolveInfos;
7158        }
7159        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7160            ResolveInfo info = resolveInfos.get(i);
7161            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7162                resolveInfos.remove(i);
7163            }
7164        }
7165        return resolveInfos;
7166    }
7167
7168    /**
7169     * Filters out ephemeral activities.
7170     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7171     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7172     *
7173     * @param resolveInfos The pre-filtered list of resolved activities
7174     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7175     *          is performed.
7176     * @return A filtered list of resolved activities.
7177     */
7178    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7179            String ephemeralPkgName) {
7180        // TODO: When adding on-demand split support for non-instant apps, remove this check
7181        // and always apply post filtering
7182        if (ephemeralPkgName == null) {
7183            return resolveInfos;
7184        }
7185        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7186            final ResolveInfo info = resolveInfos.get(i);
7187            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7188            // allow activities that are defined in the provided package
7189            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
7190                if (info.activityInfo.splitName != null
7191                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7192                                info.activityInfo.splitName)) {
7193                    // requested activity is defined in a split that hasn't been installed yet.
7194                    // add the installer to the resolve list
7195                    if (DEBUG_EPHEMERAL) {
7196                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7197                    }
7198                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7199                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7200                            info.activityInfo.packageName, info.activityInfo.splitName,
7201                            info.activityInfo.applicationInfo.versionCode, null /*failureIntent*/);
7202                    // make sure this resolver is the default
7203                    installerInfo.isDefault = true;
7204                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7205                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7206                    // add a non-generic filter
7207                    installerInfo.filter = new IntentFilter();
7208                    // load resources from the correct package
7209                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7210                    resolveInfos.set(i, installerInfo);
7211                }
7212                continue;
7213            }
7214            // allow activities that have been explicitly exposed to ephemeral apps
7215            if (!isEphemeralApp
7216                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7217                continue;
7218            }
7219            resolveInfos.remove(i);
7220        }
7221        return resolveInfos;
7222    }
7223
7224    /**
7225     * @param resolveInfos list of resolve infos in descending priority order
7226     * @return if the list contains a resolve info with non-negative priority
7227     */
7228    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7229        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7230    }
7231
7232    private static boolean hasWebURI(Intent intent) {
7233        if (intent.getData() == null) {
7234            return false;
7235        }
7236        final String scheme = intent.getScheme();
7237        if (TextUtils.isEmpty(scheme)) {
7238            return false;
7239        }
7240        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7241    }
7242
7243    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7244            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7245            int userId) {
7246        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7247
7248        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7249            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7250                    candidates.size());
7251        }
7252
7253        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7254        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7255        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7256        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7257        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7258        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7259
7260        synchronized (mPackages) {
7261            final int count = candidates.size();
7262            // First, try to use linked apps. Partition the candidates into four lists:
7263            // one for the final results, one for the "do not use ever", one for "undefined status"
7264            // and finally one for "browser app type".
7265            for (int n=0; n<count; n++) {
7266                ResolveInfo info = candidates.get(n);
7267                String packageName = info.activityInfo.packageName;
7268                PackageSetting ps = mSettings.mPackages.get(packageName);
7269                if (ps != null) {
7270                    // Add to the special match all list (Browser use case)
7271                    if (info.handleAllWebDataURI) {
7272                        matchAllList.add(info);
7273                        continue;
7274                    }
7275                    // Try to get the status from User settings first
7276                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7277                    int status = (int)(packedStatus >> 32);
7278                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7279                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7280                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7281                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7282                                    + " : linkgen=" + linkGeneration);
7283                        }
7284                        // Use link-enabled generation as preferredOrder, i.e.
7285                        // prefer newly-enabled over earlier-enabled.
7286                        info.preferredOrder = linkGeneration;
7287                        alwaysList.add(info);
7288                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7289                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7290                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7291                        }
7292                        neverList.add(info);
7293                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7294                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7295                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7296                        }
7297                        alwaysAskList.add(info);
7298                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7299                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7300                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7301                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7302                        }
7303                        undefinedList.add(info);
7304                    }
7305                }
7306            }
7307
7308            // We'll want to include browser possibilities in a few cases
7309            boolean includeBrowser = false;
7310
7311            // First try to add the "always" resolution(s) for the current user, if any
7312            if (alwaysList.size() > 0) {
7313                result.addAll(alwaysList);
7314            } else {
7315                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7316                result.addAll(undefinedList);
7317                // Maybe add one for the other profile.
7318                if (xpDomainInfo != null && (
7319                        xpDomainInfo.bestDomainVerificationStatus
7320                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7321                    result.add(xpDomainInfo.resolveInfo);
7322                }
7323                includeBrowser = true;
7324            }
7325
7326            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7327            // If there were 'always' entries their preferred order has been set, so we also
7328            // back that off to make the alternatives equivalent
7329            if (alwaysAskList.size() > 0) {
7330                for (ResolveInfo i : result) {
7331                    i.preferredOrder = 0;
7332                }
7333                result.addAll(alwaysAskList);
7334                includeBrowser = true;
7335            }
7336
7337            if (includeBrowser) {
7338                // Also add browsers (all of them or only the default one)
7339                if (DEBUG_DOMAIN_VERIFICATION) {
7340                    Slog.v(TAG, "   ...including browsers in candidate set");
7341                }
7342                if ((matchFlags & MATCH_ALL) != 0) {
7343                    result.addAll(matchAllList);
7344                } else {
7345                    // Browser/generic handling case.  If there's a default browser, go straight
7346                    // to that (but only if there is no other higher-priority match).
7347                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7348                    int maxMatchPrio = 0;
7349                    ResolveInfo defaultBrowserMatch = null;
7350                    final int numCandidates = matchAllList.size();
7351                    for (int n = 0; n < numCandidates; n++) {
7352                        ResolveInfo info = matchAllList.get(n);
7353                        // track the highest overall match priority...
7354                        if (info.priority > maxMatchPrio) {
7355                            maxMatchPrio = info.priority;
7356                        }
7357                        // ...and the highest-priority default browser match
7358                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7359                            if (defaultBrowserMatch == null
7360                                    || (defaultBrowserMatch.priority < info.priority)) {
7361                                if (debug) {
7362                                    Slog.v(TAG, "Considering default browser match " + info);
7363                                }
7364                                defaultBrowserMatch = info;
7365                            }
7366                        }
7367                    }
7368                    if (defaultBrowserMatch != null
7369                            && defaultBrowserMatch.priority >= maxMatchPrio
7370                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7371                    {
7372                        if (debug) {
7373                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7374                        }
7375                        result.add(defaultBrowserMatch);
7376                    } else {
7377                        result.addAll(matchAllList);
7378                    }
7379                }
7380
7381                // If there is nothing selected, add all candidates and remove the ones that the user
7382                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7383                if (result.size() == 0) {
7384                    result.addAll(candidates);
7385                    result.removeAll(neverList);
7386                }
7387            }
7388        }
7389        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7390            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7391                    result.size());
7392            for (ResolveInfo info : result) {
7393                Slog.v(TAG, "  + " + info.activityInfo);
7394            }
7395        }
7396        return result;
7397    }
7398
7399    // Returns a packed value as a long:
7400    //
7401    // high 'int'-sized word: link status: undefined/ask/never/always.
7402    // low 'int'-sized word: relative priority among 'always' results.
7403    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7404        long result = ps.getDomainVerificationStatusForUser(userId);
7405        // if none available, get the master status
7406        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7407            if (ps.getIntentFilterVerificationInfo() != null) {
7408                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7409            }
7410        }
7411        return result;
7412    }
7413
7414    private ResolveInfo querySkipCurrentProfileIntents(
7415            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7416            int flags, int sourceUserId) {
7417        if (matchingFilters != null) {
7418            int size = matchingFilters.size();
7419            for (int i = 0; i < size; i ++) {
7420                CrossProfileIntentFilter filter = matchingFilters.get(i);
7421                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7422                    // Checking if there are activities in the target user that can handle the
7423                    // intent.
7424                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7425                            resolvedType, flags, sourceUserId);
7426                    if (resolveInfo != null) {
7427                        return resolveInfo;
7428                    }
7429                }
7430            }
7431        }
7432        return null;
7433    }
7434
7435    // Return matching ResolveInfo in target user if any.
7436    private ResolveInfo queryCrossProfileIntents(
7437            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7438            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7439        if (matchingFilters != null) {
7440            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7441            // match the same intent. For performance reasons, it is better not to
7442            // run queryIntent twice for the same userId
7443            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7444            int size = matchingFilters.size();
7445            for (int i = 0; i < size; i++) {
7446                CrossProfileIntentFilter filter = matchingFilters.get(i);
7447                int targetUserId = filter.getTargetUserId();
7448                boolean skipCurrentProfile =
7449                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7450                boolean skipCurrentProfileIfNoMatchFound =
7451                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7452                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7453                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7454                    // Checking if there are activities in the target user that can handle the
7455                    // intent.
7456                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7457                            resolvedType, flags, sourceUserId);
7458                    if (resolveInfo != null) return resolveInfo;
7459                    alreadyTriedUserIds.put(targetUserId, true);
7460                }
7461            }
7462        }
7463        return null;
7464    }
7465
7466    /**
7467     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7468     * will forward the intent to the filter's target user.
7469     * Otherwise, returns null.
7470     */
7471    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7472            String resolvedType, int flags, int sourceUserId) {
7473        int targetUserId = filter.getTargetUserId();
7474        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7475                resolvedType, flags, targetUserId);
7476        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7477            // If all the matches in the target profile are suspended, return null.
7478            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7479                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7480                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7481                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7482                            targetUserId);
7483                }
7484            }
7485        }
7486        return null;
7487    }
7488
7489    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7490            int sourceUserId, int targetUserId) {
7491        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7492        long ident = Binder.clearCallingIdentity();
7493        boolean targetIsProfile;
7494        try {
7495            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7496        } finally {
7497            Binder.restoreCallingIdentity(ident);
7498        }
7499        String className;
7500        if (targetIsProfile) {
7501            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7502        } else {
7503            className = FORWARD_INTENT_TO_PARENT;
7504        }
7505        ComponentName forwardingActivityComponentName = new ComponentName(
7506                mAndroidApplication.packageName, className);
7507        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7508                sourceUserId);
7509        if (!targetIsProfile) {
7510            forwardingActivityInfo.showUserIcon = targetUserId;
7511            forwardingResolveInfo.noResourceId = true;
7512        }
7513        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7514        forwardingResolveInfo.priority = 0;
7515        forwardingResolveInfo.preferredOrder = 0;
7516        forwardingResolveInfo.match = 0;
7517        forwardingResolveInfo.isDefault = true;
7518        forwardingResolveInfo.filter = filter;
7519        forwardingResolveInfo.targetUserId = targetUserId;
7520        return forwardingResolveInfo;
7521    }
7522
7523    @Override
7524    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7525            Intent[] specifics, String[] specificTypes, Intent intent,
7526            String resolvedType, int flags, int userId) {
7527        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7528                specificTypes, intent, resolvedType, flags, userId));
7529    }
7530
7531    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7532            Intent[] specifics, String[] specificTypes, Intent intent,
7533            String resolvedType, int flags, int userId) {
7534        if (!sUserManager.exists(userId)) return Collections.emptyList();
7535        final int callingUid = Binder.getCallingUid();
7536        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7537                false /*includeInstantApps*/);
7538        enforceCrossUserPermission(callingUid, userId,
7539                false /*requireFullPermission*/, false /*checkShell*/,
7540                "query intent activity options");
7541        final String resultsAction = intent.getAction();
7542
7543        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7544                | PackageManager.GET_RESOLVED_FILTER, userId);
7545
7546        if (DEBUG_INTENT_MATCHING) {
7547            Log.v(TAG, "Query " + intent + ": " + results);
7548        }
7549
7550        int specificsPos = 0;
7551        int N;
7552
7553        // todo: note that the algorithm used here is O(N^2).  This
7554        // isn't a problem in our current environment, but if we start running
7555        // into situations where we have more than 5 or 10 matches then this
7556        // should probably be changed to something smarter...
7557
7558        // First we go through and resolve each of the specific items
7559        // that were supplied, taking care of removing any corresponding
7560        // duplicate items in the generic resolve list.
7561        if (specifics != null) {
7562            for (int i=0; i<specifics.length; i++) {
7563                final Intent sintent = specifics[i];
7564                if (sintent == null) {
7565                    continue;
7566                }
7567
7568                if (DEBUG_INTENT_MATCHING) {
7569                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7570                }
7571
7572                String action = sintent.getAction();
7573                if (resultsAction != null && resultsAction.equals(action)) {
7574                    // If this action was explicitly requested, then don't
7575                    // remove things that have it.
7576                    action = null;
7577                }
7578
7579                ResolveInfo ri = null;
7580                ActivityInfo ai = null;
7581
7582                ComponentName comp = sintent.getComponent();
7583                if (comp == null) {
7584                    ri = resolveIntent(
7585                        sintent,
7586                        specificTypes != null ? specificTypes[i] : null,
7587                            flags, userId);
7588                    if (ri == null) {
7589                        continue;
7590                    }
7591                    if (ri == mResolveInfo) {
7592                        // ACK!  Must do something better with this.
7593                    }
7594                    ai = ri.activityInfo;
7595                    comp = new ComponentName(ai.applicationInfo.packageName,
7596                            ai.name);
7597                } else {
7598                    ai = getActivityInfo(comp, flags, userId);
7599                    if (ai == null) {
7600                        continue;
7601                    }
7602                }
7603
7604                // Look for any generic query activities that are duplicates
7605                // of this specific one, and remove them from the results.
7606                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7607                N = results.size();
7608                int j;
7609                for (j=specificsPos; j<N; j++) {
7610                    ResolveInfo sri = results.get(j);
7611                    if ((sri.activityInfo.name.equals(comp.getClassName())
7612                            && sri.activityInfo.applicationInfo.packageName.equals(
7613                                    comp.getPackageName()))
7614                        || (action != null && sri.filter.matchAction(action))) {
7615                        results.remove(j);
7616                        if (DEBUG_INTENT_MATCHING) Log.v(
7617                            TAG, "Removing duplicate item from " + j
7618                            + " due to specific " + specificsPos);
7619                        if (ri == null) {
7620                            ri = sri;
7621                        }
7622                        j--;
7623                        N--;
7624                    }
7625                }
7626
7627                // Add this specific item to its proper place.
7628                if (ri == null) {
7629                    ri = new ResolveInfo();
7630                    ri.activityInfo = ai;
7631                }
7632                results.add(specificsPos, ri);
7633                ri.specificIndex = i;
7634                specificsPos++;
7635            }
7636        }
7637
7638        // Now we go through the remaining generic results and remove any
7639        // duplicate actions that are found here.
7640        N = results.size();
7641        for (int i=specificsPos; i<N-1; i++) {
7642            final ResolveInfo rii = results.get(i);
7643            if (rii.filter == null) {
7644                continue;
7645            }
7646
7647            // Iterate over all of the actions of this result's intent
7648            // filter...  typically this should be just one.
7649            final Iterator<String> it = rii.filter.actionsIterator();
7650            if (it == null) {
7651                continue;
7652            }
7653            while (it.hasNext()) {
7654                final String action = it.next();
7655                if (resultsAction != null && resultsAction.equals(action)) {
7656                    // If this action was explicitly requested, then don't
7657                    // remove things that have it.
7658                    continue;
7659                }
7660                for (int j=i+1; j<N; j++) {
7661                    final ResolveInfo rij = results.get(j);
7662                    if (rij.filter != null && rij.filter.hasAction(action)) {
7663                        results.remove(j);
7664                        if (DEBUG_INTENT_MATCHING) Log.v(
7665                            TAG, "Removing duplicate item from " + j
7666                            + " due to action " + action + " at " + i);
7667                        j--;
7668                        N--;
7669                    }
7670                }
7671            }
7672
7673            // If the caller didn't request filter information, drop it now
7674            // so we don't have to marshall/unmarshall it.
7675            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7676                rii.filter = null;
7677            }
7678        }
7679
7680        // Filter out the caller activity if so requested.
7681        if (caller != null) {
7682            N = results.size();
7683            for (int i=0; i<N; i++) {
7684                ActivityInfo ainfo = results.get(i).activityInfo;
7685                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7686                        && caller.getClassName().equals(ainfo.name)) {
7687                    results.remove(i);
7688                    break;
7689                }
7690            }
7691        }
7692
7693        // If the caller didn't request filter information,
7694        // drop them now so we don't have to
7695        // marshall/unmarshall it.
7696        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7697            N = results.size();
7698            for (int i=0; i<N; i++) {
7699                results.get(i).filter = null;
7700            }
7701        }
7702
7703        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7704        return results;
7705    }
7706
7707    @Override
7708    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7709            String resolvedType, int flags, int userId) {
7710        return new ParceledListSlice<>(
7711                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
7712    }
7713
7714    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7715            String resolvedType, int flags, int userId) {
7716        if (!sUserManager.exists(userId)) return Collections.emptyList();
7717        final int callingUid = Binder.getCallingUid();
7718        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7719        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7720                false /*includeInstantApps*/);
7721        ComponentName comp = intent.getComponent();
7722        if (comp == null) {
7723            if (intent.getSelector() != null) {
7724                intent = intent.getSelector();
7725                comp = intent.getComponent();
7726            }
7727        }
7728        if (comp != null) {
7729            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7730            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7731            if (ai != null) {
7732                // When specifying an explicit component, we prevent the activity from being
7733                // used when either 1) the calling package is normal and the activity is within
7734                // an instant application or 2) the calling package is ephemeral and the
7735                // activity is not visible to instant applications.
7736                final boolean matchInstantApp =
7737                        (flags & PackageManager.MATCH_INSTANT) != 0;
7738                final boolean matchVisibleToInstantAppOnly =
7739                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7740                final boolean matchExplicitlyVisibleOnly =
7741                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7742                final boolean isCallerInstantApp =
7743                        instantAppPkgName != null;
7744                final boolean isTargetSameInstantApp =
7745                        comp.getPackageName().equals(instantAppPkgName);
7746                final boolean isTargetInstantApp =
7747                        (ai.applicationInfo.privateFlags
7748                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7749                final boolean isTargetVisibleToInstantApp =
7750                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7751                final boolean isTargetExplicitlyVisibleToInstantApp =
7752                        isTargetVisibleToInstantApp
7753                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7754                final boolean isTargetHiddenFromInstantApp =
7755                        !isTargetVisibleToInstantApp
7756                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7757                final boolean blockResolution =
7758                        !isTargetSameInstantApp
7759                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7760                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7761                                        && isTargetHiddenFromInstantApp));
7762                if (!blockResolution) {
7763                    ResolveInfo ri = new ResolveInfo();
7764                    ri.activityInfo = ai;
7765                    list.add(ri);
7766                }
7767            }
7768            return applyPostResolutionFilter(list, instantAppPkgName);
7769        }
7770
7771        // reader
7772        synchronized (mPackages) {
7773            String pkgName = intent.getPackage();
7774            if (pkgName == null) {
7775                final List<ResolveInfo> result =
7776                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7777                return applyPostResolutionFilter(result, instantAppPkgName);
7778            }
7779            final PackageParser.Package pkg = mPackages.get(pkgName);
7780            if (pkg != null) {
7781                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7782                        intent, resolvedType, flags, pkg.receivers, userId);
7783                return applyPostResolutionFilter(result, instantAppPkgName);
7784            }
7785            return Collections.emptyList();
7786        }
7787    }
7788
7789    @Override
7790    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7791        final int callingUid = Binder.getCallingUid();
7792        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7793    }
7794
7795    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7796            int userId, int callingUid) {
7797        if (!sUserManager.exists(userId)) return null;
7798        flags = updateFlagsForResolve(
7799                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7800        List<ResolveInfo> query = queryIntentServicesInternal(
7801                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7802        if (query != null) {
7803            if (query.size() >= 1) {
7804                // If there is more than one service with the same priority,
7805                // just arbitrarily pick the first one.
7806                return query.get(0);
7807            }
7808        }
7809        return null;
7810    }
7811
7812    @Override
7813    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7814            String resolvedType, int flags, int userId) {
7815        final int callingUid = Binder.getCallingUid();
7816        return new ParceledListSlice<>(queryIntentServicesInternal(
7817                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7818    }
7819
7820    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7821            String resolvedType, int flags, int userId, int callingUid,
7822            boolean includeInstantApps) {
7823        if (!sUserManager.exists(userId)) return Collections.emptyList();
7824        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7825        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7826        ComponentName comp = intent.getComponent();
7827        if (comp == null) {
7828            if (intent.getSelector() != null) {
7829                intent = intent.getSelector();
7830                comp = intent.getComponent();
7831            }
7832        }
7833        if (comp != null) {
7834            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7835            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7836            if (si != null) {
7837                // When specifying an explicit component, we prevent the service from being
7838                // used when either 1) the service is in an instant application and the
7839                // caller is not the same instant application or 2) the calling package is
7840                // ephemeral and the activity is not visible to ephemeral applications.
7841                final boolean matchInstantApp =
7842                        (flags & PackageManager.MATCH_INSTANT) != 0;
7843                final boolean matchVisibleToInstantAppOnly =
7844                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7845                final boolean isCallerInstantApp =
7846                        instantAppPkgName != null;
7847                final boolean isTargetSameInstantApp =
7848                        comp.getPackageName().equals(instantAppPkgName);
7849                final boolean isTargetInstantApp =
7850                        (si.applicationInfo.privateFlags
7851                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7852                final boolean isTargetHiddenFromInstantApp =
7853                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7854                final boolean blockResolution =
7855                        !isTargetSameInstantApp
7856                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7857                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7858                                        && isTargetHiddenFromInstantApp));
7859                if (!blockResolution) {
7860                    final ResolveInfo ri = new ResolveInfo();
7861                    ri.serviceInfo = si;
7862                    list.add(ri);
7863                }
7864            }
7865            return list;
7866        }
7867
7868        // reader
7869        synchronized (mPackages) {
7870            String pkgName = intent.getPackage();
7871            if (pkgName == null) {
7872                return applyPostServiceResolutionFilter(
7873                        mServices.queryIntent(intent, resolvedType, flags, userId),
7874                        instantAppPkgName);
7875            }
7876            final PackageParser.Package pkg = mPackages.get(pkgName);
7877            if (pkg != null) {
7878                return applyPostServiceResolutionFilter(
7879                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7880                                userId),
7881                        instantAppPkgName);
7882            }
7883            return Collections.emptyList();
7884        }
7885    }
7886
7887    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7888            String instantAppPkgName) {
7889        // TODO: When adding on-demand split support for non-instant apps, remove this check
7890        // and always apply post filtering
7891        if (instantAppPkgName == null) {
7892            return resolveInfos;
7893        }
7894        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7895            final ResolveInfo info = resolveInfos.get(i);
7896            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7897            // allow services that are defined in the provided package
7898            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7899                if (info.serviceInfo.splitName != null
7900                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7901                                info.serviceInfo.splitName)) {
7902                    // requested service is defined in a split that hasn't been installed yet.
7903                    // add the installer to the resolve list
7904                    if (DEBUG_EPHEMERAL) {
7905                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7906                    }
7907                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7908                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7909                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7910                            info.serviceInfo.applicationInfo.versionCode, null /*failureIntent*/);
7911                    // make sure this resolver is the default
7912                    installerInfo.isDefault = true;
7913                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7914                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7915                    // add a non-generic filter
7916                    installerInfo.filter = new IntentFilter();
7917                    // load resources from the correct package
7918                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7919                    resolveInfos.set(i, installerInfo);
7920                }
7921                continue;
7922            }
7923            // allow services that have been explicitly exposed to ephemeral apps
7924            if (!isEphemeralApp
7925                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7926                continue;
7927            }
7928            resolveInfos.remove(i);
7929        }
7930        return resolveInfos;
7931    }
7932
7933    @Override
7934    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7935            String resolvedType, int flags, int userId) {
7936        return new ParceledListSlice<>(
7937                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7938    }
7939
7940    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7941            Intent intent, String resolvedType, int flags, int userId) {
7942        if (!sUserManager.exists(userId)) return Collections.emptyList();
7943        final int callingUid = Binder.getCallingUid();
7944        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7945        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7946                false /*includeInstantApps*/);
7947        ComponentName comp = intent.getComponent();
7948        if (comp == null) {
7949            if (intent.getSelector() != null) {
7950                intent = intent.getSelector();
7951                comp = intent.getComponent();
7952            }
7953        }
7954        if (comp != null) {
7955            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7956            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7957            if (pi != null) {
7958                // When specifying an explicit component, we prevent the provider from being
7959                // used when either 1) the provider is in an instant application and the
7960                // caller is not the same instant application or 2) the calling package is an
7961                // instant application and the provider is not visible to instant applications.
7962                final boolean matchInstantApp =
7963                        (flags & PackageManager.MATCH_INSTANT) != 0;
7964                final boolean matchVisibleToInstantAppOnly =
7965                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7966                final boolean isCallerInstantApp =
7967                        instantAppPkgName != null;
7968                final boolean isTargetSameInstantApp =
7969                        comp.getPackageName().equals(instantAppPkgName);
7970                final boolean isTargetInstantApp =
7971                        (pi.applicationInfo.privateFlags
7972                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7973                final boolean isTargetHiddenFromInstantApp =
7974                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7975                final boolean blockResolution =
7976                        !isTargetSameInstantApp
7977                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7978                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7979                                        && isTargetHiddenFromInstantApp));
7980                if (!blockResolution) {
7981                    final ResolveInfo ri = new ResolveInfo();
7982                    ri.providerInfo = pi;
7983                    list.add(ri);
7984                }
7985            }
7986            return list;
7987        }
7988
7989        // reader
7990        synchronized (mPackages) {
7991            String pkgName = intent.getPackage();
7992            if (pkgName == null) {
7993                return applyPostContentProviderResolutionFilter(
7994                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7995                        instantAppPkgName);
7996            }
7997            final PackageParser.Package pkg = mPackages.get(pkgName);
7998            if (pkg != null) {
7999                return applyPostContentProviderResolutionFilter(
8000                        mProviders.queryIntentForPackage(
8001                        intent, resolvedType, flags, pkg.providers, userId),
8002                        instantAppPkgName);
8003            }
8004            return Collections.emptyList();
8005        }
8006    }
8007
8008    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8009            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8010        // TODO: When adding on-demand split support for non-instant applications, remove
8011        // this check and always apply post filtering
8012        if (instantAppPkgName == null) {
8013            return resolveInfos;
8014        }
8015        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8016            final ResolveInfo info = resolveInfos.get(i);
8017            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8018            // allow providers that are defined in the provided package
8019            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8020                if (info.providerInfo.splitName != null
8021                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8022                                info.providerInfo.splitName)) {
8023                    // requested provider is defined in a split that hasn't been installed yet.
8024                    // add the installer to the resolve list
8025                    if (DEBUG_EPHEMERAL) {
8026                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8027                    }
8028                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8029                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8030                            info.providerInfo.packageName, info.providerInfo.splitName,
8031                            info.providerInfo.applicationInfo.versionCode, null /*failureIntent*/);
8032                    // make sure this resolver is the default
8033                    installerInfo.isDefault = true;
8034                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8035                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8036                    // add a non-generic filter
8037                    installerInfo.filter = new IntentFilter();
8038                    // load resources from the correct package
8039                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8040                    resolveInfos.set(i, installerInfo);
8041                }
8042                continue;
8043            }
8044            // allow providers that have been explicitly exposed to instant applications
8045            if (!isEphemeralApp
8046                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8047                continue;
8048            }
8049            resolveInfos.remove(i);
8050        }
8051        return resolveInfos;
8052    }
8053
8054    @Override
8055    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8056        final int callingUid = Binder.getCallingUid();
8057        if (getInstantAppPackageName(callingUid) != null) {
8058            return ParceledListSlice.emptyList();
8059        }
8060        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8061        flags = updateFlagsForPackage(flags, userId, null);
8062        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8063        enforceCrossUserPermission(callingUid, userId,
8064                true /* requireFullPermission */, false /* checkShell */,
8065                "get installed packages");
8066
8067        // writer
8068        synchronized (mPackages) {
8069            ArrayList<PackageInfo> list;
8070            if (listUninstalled) {
8071                list = new ArrayList<>(mSettings.mPackages.size());
8072                for (PackageSetting ps : mSettings.mPackages.values()) {
8073                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8074                        continue;
8075                    }
8076                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8077                        return null;
8078                    }
8079                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8080                    if (pi != null) {
8081                        list.add(pi);
8082                    }
8083                }
8084            } else {
8085                list = new ArrayList<>(mPackages.size());
8086                for (PackageParser.Package p : mPackages.values()) {
8087                    final PackageSetting ps = (PackageSetting) p.mExtras;
8088                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8089                        continue;
8090                    }
8091                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8092                        return null;
8093                    }
8094                    final PackageInfo pi = generatePackageInfo((PackageSetting)
8095                            p.mExtras, flags, userId);
8096                    if (pi != null) {
8097                        list.add(pi);
8098                    }
8099                }
8100            }
8101
8102            return new ParceledListSlice<>(list);
8103        }
8104    }
8105
8106    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8107            String[] permissions, boolean[] tmp, int flags, int userId) {
8108        int numMatch = 0;
8109        final PermissionsState permissionsState = ps.getPermissionsState();
8110        for (int i=0; i<permissions.length; i++) {
8111            final String permission = permissions[i];
8112            if (permissionsState.hasPermission(permission, userId)) {
8113                tmp[i] = true;
8114                numMatch++;
8115            } else {
8116                tmp[i] = false;
8117            }
8118        }
8119        if (numMatch == 0) {
8120            return;
8121        }
8122        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8123
8124        // The above might return null in cases of uninstalled apps or install-state
8125        // skew across users/profiles.
8126        if (pi != null) {
8127            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8128                if (numMatch == permissions.length) {
8129                    pi.requestedPermissions = permissions;
8130                } else {
8131                    pi.requestedPermissions = new String[numMatch];
8132                    numMatch = 0;
8133                    for (int i=0; i<permissions.length; i++) {
8134                        if (tmp[i]) {
8135                            pi.requestedPermissions[numMatch] = permissions[i];
8136                            numMatch++;
8137                        }
8138                    }
8139                }
8140            }
8141            list.add(pi);
8142        }
8143    }
8144
8145    @Override
8146    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8147            String[] permissions, int flags, int userId) {
8148        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8149        flags = updateFlagsForPackage(flags, userId, permissions);
8150        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8151                true /* requireFullPermission */, false /* checkShell */,
8152                "get packages holding permissions");
8153        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8154
8155        // writer
8156        synchronized (mPackages) {
8157            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8158            boolean[] tmpBools = new boolean[permissions.length];
8159            if (listUninstalled) {
8160                for (PackageSetting ps : mSettings.mPackages.values()) {
8161                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8162                            userId);
8163                }
8164            } else {
8165                for (PackageParser.Package pkg : mPackages.values()) {
8166                    PackageSetting ps = (PackageSetting)pkg.mExtras;
8167                    if (ps != null) {
8168                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8169                                userId);
8170                    }
8171                }
8172            }
8173
8174            return new ParceledListSlice<PackageInfo>(list);
8175        }
8176    }
8177
8178    @Override
8179    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8180        final int callingUid = Binder.getCallingUid();
8181        if (getInstantAppPackageName(callingUid) != null) {
8182            return ParceledListSlice.emptyList();
8183        }
8184        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8185        flags = updateFlagsForApplication(flags, userId, null);
8186        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8187
8188        // writer
8189        synchronized (mPackages) {
8190            ArrayList<ApplicationInfo> list;
8191            if (listUninstalled) {
8192                list = new ArrayList<>(mSettings.mPackages.size());
8193                for (PackageSetting ps : mSettings.mPackages.values()) {
8194                    ApplicationInfo ai;
8195                    int effectiveFlags = flags;
8196                    if (ps.isSystem()) {
8197                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8198                    }
8199                    if (ps.pkg != null) {
8200                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8201                            continue;
8202                        }
8203                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8204                            return null;
8205                        }
8206                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8207                                ps.readUserState(userId), userId);
8208                        if (ai != null) {
8209                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8210                        }
8211                    } else {
8212                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8213                        // and already converts to externally visible package name
8214                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8215                                callingUid, effectiveFlags, userId);
8216                    }
8217                    if (ai != null) {
8218                        list.add(ai);
8219                    }
8220                }
8221            } else {
8222                list = new ArrayList<>(mPackages.size());
8223                for (PackageParser.Package p : mPackages.values()) {
8224                    if (p.mExtras != null) {
8225                        PackageSetting ps = (PackageSetting) p.mExtras;
8226                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8227                            continue;
8228                        }
8229                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8230                            return null;
8231                        }
8232                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8233                                ps.readUserState(userId), userId);
8234                        if (ai != null) {
8235                            ai.packageName = resolveExternalPackageNameLPr(p);
8236                            list.add(ai);
8237                        }
8238                    }
8239                }
8240            }
8241
8242            return new ParceledListSlice<>(list);
8243        }
8244    }
8245
8246    @Override
8247    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8248        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8249            return null;
8250        }
8251        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8252                "getEphemeralApplications");
8253        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8254                true /* requireFullPermission */, false /* checkShell */,
8255                "getEphemeralApplications");
8256        synchronized (mPackages) {
8257            List<InstantAppInfo> instantApps = mInstantAppRegistry
8258                    .getInstantAppsLPr(userId);
8259            if (instantApps != null) {
8260                return new ParceledListSlice<>(instantApps);
8261            }
8262        }
8263        return null;
8264    }
8265
8266    @Override
8267    public boolean isInstantApp(String packageName, int userId) {
8268        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8269                true /* requireFullPermission */, false /* checkShell */,
8270                "isInstantApp");
8271        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8272            return false;
8273        }
8274
8275        synchronized (mPackages) {
8276            int callingUid = Binder.getCallingUid();
8277            if (Process.isIsolated(callingUid)) {
8278                callingUid = mIsolatedOwners.get(callingUid);
8279            }
8280            final PackageSetting ps = mSettings.mPackages.get(packageName);
8281            PackageParser.Package pkg = mPackages.get(packageName);
8282            final boolean returnAllowed =
8283                    ps != null
8284                    && (isCallerSameApp(packageName, callingUid)
8285                            || canViewInstantApps(callingUid, userId)
8286                            || mInstantAppRegistry.isInstantAccessGranted(
8287                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8288            if (returnAllowed) {
8289                return ps.getInstantApp(userId);
8290            }
8291        }
8292        return false;
8293    }
8294
8295    @Override
8296    public byte[] getInstantAppCookie(String packageName, int userId) {
8297        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8298            return null;
8299        }
8300
8301        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8302                true /* requireFullPermission */, false /* checkShell */,
8303                "getInstantAppCookie");
8304        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8305            return null;
8306        }
8307        synchronized (mPackages) {
8308            return mInstantAppRegistry.getInstantAppCookieLPw(
8309                    packageName, userId);
8310        }
8311    }
8312
8313    @Override
8314    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8315        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8316            return true;
8317        }
8318
8319        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8320                true /* requireFullPermission */, true /* checkShell */,
8321                "setInstantAppCookie");
8322        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8323            return false;
8324        }
8325        synchronized (mPackages) {
8326            return mInstantAppRegistry.setInstantAppCookieLPw(
8327                    packageName, cookie, userId);
8328        }
8329    }
8330
8331    @Override
8332    public Bitmap getInstantAppIcon(String packageName, int userId) {
8333        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8334            return null;
8335        }
8336
8337        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8338                "getInstantAppIcon");
8339
8340        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8341                true /* requireFullPermission */, false /* checkShell */,
8342                "getInstantAppIcon");
8343
8344        synchronized (mPackages) {
8345            return mInstantAppRegistry.getInstantAppIconLPw(
8346                    packageName, userId);
8347        }
8348    }
8349
8350    private boolean isCallerSameApp(String packageName, int uid) {
8351        PackageParser.Package pkg = mPackages.get(packageName);
8352        return pkg != null
8353                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8354    }
8355
8356    @Override
8357    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8358        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8359            return ParceledListSlice.emptyList();
8360        }
8361        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8362    }
8363
8364    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8365        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8366
8367        // reader
8368        synchronized (mPackages) {
8369            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8370            final int userId = UserHandle.getCallingUserId();
8371            while (i.hasNext()) {
8372                final PackageParser.Package p = i.next();
8373                if (p.applicationInfo == null) continue;
8374
8375                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8376                        && !p.applicationInfo.isDirectBootAware();
8377                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8378                        && p.applicationInfo.isDirectBootAware();
8379
8380                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8381                        && (!mSafeMode || isSystemApp(p))
8382                        && (matchesUnaware || matchesAware)) {
8383                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8384                    if (ps != null) {
8385                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8386                                ps.readUserState(userId), userId);
8387                        if (ai != null) {
8388                            finalList.add(ai);
8389                        }
8390                    }
8391                }
8392            }
8393        }
8394
8395        return finalList;
8396    }
8397
8398    @Override
8399    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8400        if (!sUserManager.exists(userId)) return null;
8401        flags = updateFlagsForComponent(flags, userId, name);
8402        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8403        // reader
8404        synchronized (mPackages) {
8405            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8406            PackageSetting ps = provider != null
8407                    ? mSettings.mPackages.get(provider.owner.packageName)
8408                    : null;
8409            if (ps != null) {
8410                final boolean isInstantApp = ps.getInstantApp(userId);
8411                // normal application; filter out instant application provider
8412                if (instantAppPkgName == null && isInstantApp) {
8413                    return null;
8414                }
8415                // instant application; filter out other instant applications
8416                if (instantAppPkgName != null
8417                        && isInstantApp
8418                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8419                    return null;
8420                }
8421                // instant application; filter out non-exposed provider
8422                if (instantAppPkgName != null
8423                        && !isInstantApp
8424                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8425                    return null;
8426                }
8427                // provider not enabled
8428                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8429                    return null;
8430                }
8431                return PackageParser.generateProviderInfo(
8432                        provider, flags, ps.readUserState(userId), userId);
8433            }
8434            return null;
8435        }
8436    }
8437
8438    /**
8439     * @deprecated
8440     */
8441    @Deprecated
8442    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8443        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8444            return;
8445        }
8446        // reader
8447        synchronized (mPackages) {
8448            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8449                    .entrySet().iterator();
8450            final int userId = UserHandle.getCallingUserId();
8451            while (i.hasNext()) {
8452                Map.Entry<String, PackageParser.Provider> entry = i.next();
8453                PackageParser.Provider p = entry.getValue();
8454                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8455
8456                if (ps != null && p.syncable
8457                        && (!mSafeMode || (p.info.applicationInfo.flags
8458                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8459                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8460                            ps.readUserState(userId), userId);
8461                    if (info != null) {
8462                        outNames.add(entry.getKey());
8463                        outInfo.add(info);
8464                    }
8465                }
8466            }
8467        }
8468    }
8469
8470    @Override
8471    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8472            int uid, int flags, String metaDataKey) {
8473        final int callingUid = Binder.getCallingUid();
8474        final int userId = processName != null ? UserHandle.getUserId(uid)
8475                : UserHandle.getCallingUserId();
8476        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8477        flags = updateFlagsForComponent(flags, userId, processName);
8478        ArrayList<ProviderInfo> finalList = null;
8479        // reader
8480        synchronized (mPackages) {
8481            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8482            while (i.hasNext()) {
8483                final PackageParser.Provider p = i.next();
8484                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8485                if (ps != null && p.info.authority != null
8486                        && (processName == null
8487                                || (p.info.processName.equals(processName)
8488                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8489                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8490
8491                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8492                    // parameter.
8493                    if (metaDataKey != null
8494                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8495                        continue;
8496                    }
8497                    final ComponentName component =
8498                            new ComponentName(p.info.packageName, p.info.name);
8499                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8500                        continue;
8501                    }
8502                    if (finalList == null) {
8503                        finalList = new ArrayList<ProviderInfo>(3);
8504                    }
8505                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8506                            ps.readUserState(userId), userId);
8507                    if (info != null) {
8508                        finalList.add(info);
8509                    }
8510                }
8511            }
8512        }
8513
8514        if (finalList != null) {
8515            Collections.sort(finalList, mProviderInitOrderSorter);
8516            return new ParceledListSlice<ProviderInfo>(finalList);
8517        }
8518
8519        return ParceledListSlice.emptyList();
8520    }
8521
8522    @Override
8523    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8524        // reader
8525        synchronized (mPackages) {
8526            final int callingUid = Binder.getCallingUid();
8527            final int callingUserId = UserHandle.getUserId(callingUid);
8528            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8529            if (ps == null) return null;
8530            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8531                return null;
8532            }
8533            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8534            return PackageParser.generateInstrumentationInfo(i, flags);
8535        }
8536    }
8537
8538    @Override
8539    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8540            String targetPackage, int flags) {
8541        final int callingUid = Binder.getCallingUid();
8542        final int callingUserId = UserHandle.getUserId(callingUid);
8543        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8544        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8545            return ParceledListSlice.emptyList();
8546        }
8547        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8548    }
8549
8550    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8551            int flags) {
8552        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8553
8554        // reader
8555        synchronized (mPackages) {
8556            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8557            while (i.hasNext()) {
8558                final PackageParser.Instrumentation p = i.next();
8559                if (targetPackage == null
8560                        || targetPackage.equals(p.info.targetPackage)) {
8561                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8562                            flags);
8563                    if (ii != null) {
8564                        finalList.add(ii);
8565                    }
8566                }
8567            }
8568        }
8569
8570        return finalList;
8571    }
8572
8573    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8574        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8575        try {
8576            scanDirLI(dir, parseFlags, scanFlags, currentTime);
8577        } finally {
8578            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8579        }
8580    }
8581
8582    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8583        final File[] files = dir.listFiles();
8584        if (ArrayUtils.isEmpty(files)) {
8585            Log.d(TAG, "No files in app dir " + dir);
8586            return;
8587        }
8588
8589        if (DEBUG_PACKAGE_SCANNING) {
8590            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8591                    + " flags=0x" + Integer.toHexString(parseFlags));
8592        }
8593        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8594                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8595                mParallelPackageParserCallback);
8596
8597        // Submit files for parsing in parallel
8598        int fileCount = 0;
8599        for (File file : files) {
8600            final boolean isPackage = (isApkFile(file) || file.isDirectory())
8601                    && !PackageInstallerService.isStageName(file.getName());
8602            if (!isPackage) {
8603                // Ignore entries which are not packages
8604                continue;
8605            }
8606            parallelPackageParser.submit(file, parseFlags);
8607            fileCount++;
8608        }
8609
8610        // Process results one by one
8611        for (; fileCount > 0; fileCount--) {
8612            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8613            Throwable throwable = parseResult.throwable;
8614            int errorCode = PackageManager.INSTALL_SUCCEEDED;
8615
8616            if (throwable == null) {
8617                // Static shared libraries have synthetic package names
8618                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8619                    renameStaticSharedLibraryPackage(parseResult.pkg);
8620                }
8621                try {
8622                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8623                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8624                                currentTime, null);
8625                    }
8626                } catch (PackageManagerException e) {
8627                    errorCode = e.error;
8628                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8629                }
8630            } else if (throwable instanceof PackageParser.PackageParserException) {
8631                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8632                        throwable;
8633                errorCode = e.error;
8634                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8635            } else {
8636                throw new IllegalStateException("Unexpected exception occurred while parsing "
8637                        + parseResult.scanFile, throwable);
8638            }
8639
8640            // Delete invalid userdata apps
8641            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
8642                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8643                logCriticalInfo(Log.WARN,
8644                        "Deleting invalid package at " + parseResult.scanFile);
8645                removeCodePathLI(parseResult.scanFile);
8646            }
8647        }
8648        parallelPackageParser.close();
8649    }
8650
8651    private static File getSettingsProblemFile() {
8652        File dataDir = Environment.getDataDirectory();
8653        File systemDir = new File(dataDir, "system");
8654        File fname = new File(systemDir, "uiderrors.txt");
8655        return fname;
8656    }
8657
8658    static void reportSettingsProblem(int priority, String msg) {
8659        logCriticalInfo(priority, msg);
8660    }
8661
8662    public static void logCriticalInfo(int priority, String msg) {
8663        Slog.println(priority, TAG, msg);
8664        EventLogTags.writePmCriticalInfo(msg);
8665        try {
8666            File fname = getSettingsProblemFile();
8667            FileOutputStream out = new FileOutputStream(fname, true);
8668            PrintWriter pw = new FastPrintWriter(out);
8669            SimpleDateFormat formatter = new SimpleDateFormat();
8670            String dateString = formatter.format(new Date(System.currentTimeMillis()));
8671            pw.println(dateString + ": " + msg);
8672            pw.close();
8673            FileUtils.setPermissions(
8674                    fname.toString(),
8675                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
8676                    -1, -1);
8677        } catch (java.io.IOException e) {
8678        }
8679    }
8680
8681    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
8682        if (srcFile.isDirectory()) {
8683            final File baseFile = new File(pkg.baseCodePath);
8684            long maxModifiedTime = baseFile.lastModified();
8685            if (pkg.splitCodePaths != null) {
8686                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
8687                    final File splitFile = new File(pkg.splitCodePaths[i]);
8688                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
8689                }
8690            }
8691            return maxModifiedTime;
8692        }
8693        return srcFile.lastModified();
8694    }
8695
8696    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
8697            final int policyFlags) throws PackageManagerException {
8698        // When upgrading from pre-N MR1, verify the package time stamp using the package
8699        // directory and not the APK file.
8700        final long lastModifiedTime = mIsPreNMR1Upgrade
8701                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
8702        if (ps != null
8703                && ps.codePath.equals(srcFile)
8704                && ps.timeStamp == lastModifiedTime
8705                && !isCompatSignatureUpdateNeeded(pkg)
8706                && !isRecoverSignatureUpdateNeeded(pkg)) {
8707            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
8708            KeySetManagerService ksms = mSettings.mKeySetManagerService;
8709            ArraySet<PublicKey> signingKs;
8710            synchronized (mPackages) {
8711                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
8712            }
8713            if (ps.signatures.mSignatures != null
8714                    && ps.signatures.mSignatures.length != 0
8715                    && signingKs != null) {
8716                // Optimization: reuse the existing cached certificates
8717                // if the package appears to be unchanged.
8718                pkg.mSignatures = ps.signatures.mSignatures;
8719                pkg.mSigningKeys = signingKs;
8720                return;
8721            }
8722
8723            Slog.w(TAG, "PackageSetting for " + ps.name
8724                    + " is missing signatures.  Collecting certs again to recover them.");
8725        } else {
8726            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
8727        }
8728
8729        try {
8730            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8731            PackageParser.collectCertificates(pkg, policyFlags);
8732        } catch (PackageParserException e) {
8733            throw PackageManagerException.from(e);
8734        } finally {
8735            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8736        }
8737    }
8738
8739    /**
8740     *  Traces a package scan.
8741     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8742     */
8743    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8744            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8745        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8746        try {
8747            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8748        } finally {
8749            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8750        }
8751    }
8752
8753    /**
8754     *  Scans a package and returns the newly parsed package.
8755     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8756     */
8757    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8758            long currentTime, UserHandle user) throws PackageManagerException {
8759        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8760        PackageParser pp = new PackageParser();
8761        pp.setSeparateProcesses(mSeparateProcesses);
8762        pp.setOnlyCoreApps(mOnlyCore);
8763        pp.setDisplayMetrics(mMetrics);
8764        pp.setCallback(mPackageParserCallback);
8765
8766        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
8767            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
8768        }
8769
8770        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8771        final PackageParser.Package pkg;
8772        try {
8773            pkg = pp.parsePackage(scanFile, parseFlags);
8774        } catch (PackageParserException e) {
8775            throw PackageManagerException.from(e);
8776        } finally {
8777            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8778        }
8779
8780        // Static shared libraries have synthetic package names
8781        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8782            renameStaticSharedLibraryPackage(pkg);
8783        }
8784
8785        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
8786    }
8787
8788    /**
8789     *  Scans a package and returns the newly parsed package.
8790     *  @throws PackageManagerException on a parse error.
8791     */
8792    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
8793            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8794            throws PackageManagerException {
8795        // If the package has children and this is the first dive in the function
8796        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8797        // packages (parent and children) would be successfully scanned before the
8798        // actual scan since scanning mutates internal state and we want to atomically
8799        // install the package and its children.
8800        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8801            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8802                scanFlags |= SCAN_CHECK_ONLY;
8803            }
8804        } else {
8805            scanFlags &= ~SCAN_CHECK_ONLY;
8806        }
8807
8808        // Scan the parent
8809        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
8810                scanFlags, currentTime, user);
8811
8812        // Scan the children
8813        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8814        for (int i = 0; i < childCount; i++) {
8815            PackageParser.Package childPackage = pkg.childPackages.get(i);
8816            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
8817                    currentTime, user);
8818        }
8819
8820
8821        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8822            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
8823        }
8824
8825        return scannedPkg;
8826    }
8827
8828    /**
8829     *  Scans a package and returns the newly parsed package.
8830     *  @throws PackageManagerException on a parse error.
8831     */
8832    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
8833            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8834            throws PackageManagerException {
8835        PackageSetting ps = null;
8836        PackageSetting updatedPkg;
8837        // reader
8838        synchronized (mPackages) {
8839            // Look to see if we already know about this package.
8840            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
8841            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
8842                // This package has been renamed to its original name.  Let's
8843                // use that.
8844                ps = mSettings.getPackageLPr(oldName);
8845            }
8846            // If there was no original package, see one for the real package name.
8847            if (ps == null) {
8848                ps = mSettings.getPackageLPr(pkg.packageName);
8849            }
8850            // Check to see if this package could be hiding/updating a system
8851            // package.  Must look for it either under the original or real
8852            // package name depending on our state.
8853            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
8854            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
8855
8856            // If this is a package we don't know about on the system partition, we
8857            // may need to remove disabled child packages on the system partition
8858            // or may need to not add child packages if the parent apk is updated
8859            // on the data partition and no longer defines this child package.
8860            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8861                // If this is a parent package for an updated system app and this system
8862                // app got an OTA update which no longer defines some of the child packages
8863                // we have to prune them from the disabled system packages.
8864                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8865                if (disabledPs != null) {
8866                    final int scannedChildCount = (pkg.childPackages != null)
8867                            ? pkg.childPackages.size() : 0;
8868                    final int disabledChildCount = disabledPs.childPackageNames != null
8869                            ? disabledPs.childPackageNames.size() : 0;
8870                    for (int i = 0; i < disabledChildCount; i++) {
8871                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
8872                        boolean disabledPackageAvailable = false;
8873                        for (int j = 0; j < scannedChildCount; j++) {
8874                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8875                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8876                                disabledPackageAvailable = true;
8877                                break;
8878                            }
8879                         }
8880                         if (!disabledPackageAvailable) {
8881                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8882                         }
8883                    }
8884                }
8885            }
8886        }
8887
8888        boolean updatedPkgBetter = false;
8889        // First check if this is a system package that may involve an update
8890        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8891            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8892            // it needs to drop FLAG_PRIVILEGED.
8893            if (locationIsPrivileged(scanFile)) {
8894                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8895            } else {
8896                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8897            }
8898
8899            if (ps != null && !ps.codePath.equals(scanFile)) {
8900                // The path has changed from what was last scanned...  check the
8901                // version of the new path against what we have stored to determine
8902                // what to do.
8903                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8904                if (pkg.mVersionCode <= ps.versionCode) {
8905                    // The system package has been updated and the code path does not match
8906                    // Ignore entry. Skip it.
8907                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
8908                            + " ignored: updated version " + ps.versionCode
8909                            + " better than this " + pkg.mVersionCode);
8910                    if (!updatedPkg.codePath.equals(scanFile)) {
8911                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8912                                + ps.name + " changing from " + updatedPkg.codePathString
8913                                + " to " + scanFile);
8914                        updatedPkg.codePath = scanFile;
8915                        updatedPkg.codePathString = scanFile.toString();
8916                        updatedPkg.resourcePath = scanFile;
8917                        updatedPkg.resourcePathString = scanFile.toString();
8918                    }
8919                    updatedPkg.pkg = pkg;
8920                    updatedPkg.versionCode = pkg.mVersionCode;
8921
8922                    // Update the disabled system child packages to point to the package too.
8923                    final int childCount = updatedPkg.childPackageNames != null
8924                            ? updatedPkg.childPackageNames.size() : 0;
8925                    for (int i = 0; i < childCount; i++) {
8926                        String childPackageName = updatedPkg.childPackageNames.get(i);
8927                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8928                                childPackageName);
8929                        if (updatedChildPkg != null) {
8930                            updatedChildPkg.pkg = pkg;
8931                            updatedChildPkg.versionCode = pkg.mVersionCode;
8932                        }
8933                    }
8934
8935                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
8936                            + scanFile + " ignored: updated version " + ps.versionCode
8937                            + " better than this " + pkg.mVersionCode);
8938                } else {
8939                    // The current app on the system partition is better than
8940                    // what we have updated to on the data partition; switch
8941                    // back to the system partition version.
8942                    // At this point, its safely assumed that package installation for
8943                    // apps in system partition will go through. If not there won't be a working
8944                    // version of the app
8945                    // writer
8946                    synchronized (mPackages) {
8947                        // Just remove the loaded entries from package lists.
8948                        mPackages.remove(ps.name);
8949                    }
8950
8951                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8952                            + " reverting from " + ps.codePathString
8953                            + ": new version " + pkg.mVersionCode
8954                            + " better than installed " + ps.versionCode);
8955
8956                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8957                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8958                    synchronized (mInstallLock) {
8959                        args.cleanUpResourcesLI();
8960                    }
8961                    synchronized (mPackages) {
8962                        mSettings.enableSystemPackageLPw(ps.name);
8963                    }
8964                    updatedPkgBetter = true;
8965                }
8966            }
8967        }
8968
8969        if (updatedPkg != null) {
8970            // An updated system app will not have the PARSE_IS_SYSTEM flag set
8971            // initially
8972            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
8973
8974            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
8975            // flag set initially
8976            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
8977                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
8978            }
8979        }
8980
8981        // Verify certificates against what was last scanned
8982        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
8983
8984        /*
8985         * A new system app appeared, but we already had a non-system one of the
8986         * same name installed earlier.
8987         */
8988        boolean shouldHideSystemApp = false;
8989        if (updatedPkg == null && ps != null
8990                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
8991            /*
8992             * Check to make sure the signatures match first. If they don't,
8993             * wipe the installed application and its data.
8994             */
8995            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
8996                    != PackageManager.SIGNATURE_MATCH) {
8997                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
8998                        + " signatures don't match existing userdata copy; removing");
8999                try (PackageFreezer freezer = freezePackage(pkg.packageName,
9000                        "scanPackageInternalLI")) {
9001                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9002                }
9003                ps = null;
9004            } else {
9005                /*
9006                 * If the newly-added system app is an older version than the
9007                 * already installed version, hide it. It will be scanned later
9008                 * and re-added like an update.
9009                 */
9010                if (pkg.mVersionCode <= ps.versionCode) {
9011                    shouldHideSystemApp = true;
9012                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9013                            + " but new version " + pkg.mVersionCode + " better than installed "
9014                            + ps.versionCode + "; hiding system");
9015                } else {
9016                    /*
9017                     * The newly found system app is a newer version that the
9018                     * one previously installed. Simply remove the
9019                     * already-installed application and replace it with our own
9020                     * while keeping the application data.
9021                     */
9022                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9023                            + " reverting from " + ps.codePathString + ": new version "
9024                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
9025                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9026                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9027                    synchronized (mInstallLock) {
9028                        args.cleanUpResourcesLI();
9029                    }
9030                }
9031            }
9032        }
9033
9034        // The apk is forward locked (not public) if its code and resources
9035        // are kept in different files. (except for app in either system or
9036        // vendor path).
9037        // TODO grab this value from PackageSettings
9038        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9039            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9040                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9041            }
9042        }
9043
9044        // TODO: extend to support forward-locked splits
9045        String resourcePath = null;
9046        String baseResourcePath = null;
9047        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
9048            if (ps != null && ps.resourcePathString != null) {
9049                resourcePath = ps.resourcePathString;
9050                baseResourcePath = ps.resourcePathString;
9051            } else {
9052                // Should not happen at all. Just log an error.
9053                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9054            }
9055        } else {
9056            resourcePath = pkg.codePath;
9057            baseResourcePath = pkg.baseCodePath;
9058        }
9059
9060        // Set application objects path explicitly.
9061        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9062        pkg.setApplicationInfoCodePath(pkg.codePath);
9063        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9064        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9065        pkg.setApplicationInfoResourcePath(resourcePath);
9066        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9067        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9068
9069        final int userId = ((user == null) ? 0 : user.getIdentifier());
9070        if (ps != null && ps.getInstantApp(userId)) {
9071            scanFlags |= SCAN_AS_INSTANT_APP;
9072        }
9073
9074        // Note that we invoke the following method only if we are about to unpack an application
9075        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9076                | SCAN_UPDATE_SIGNATURE, currentTime, user);
9077
9078        /*
9079         * If the system app should be overridden by a previously installed
9080         * data, hide the system app now and let the /data/app scan pick it up
9081         * again.
9082         */
9083        if (shouldHideSystemApp) {
9084            synchronized (mPackages) {
9085                mSettings.disableSystemPackageLPw(pkg.packageName, true);
9086            }
9087        }
9088
9089        return scannedPkg;
9090    }
9091
9092    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9093        // Derive the new package synthetic package name
9094        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9095                + pkg.staticSharedLibVersion);
9096    }
9097
9098    private static String fixProcessName(String defProcessName,
9099            String processName) {
9100        if (processName == null) {
9101            return defProcessName;
9102        }
9103        return processName;
9104    }
9105
9106    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9107            throws PackageManagerException {
9108        if (pkgSetting.signatures.mSignatures != null) {
9109            // Already existing package. Make sure signatures match
9110            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9111                    == PackageManager.SIGNATURE_MATCH;
9112            if (!match) {
9113                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9114                        == PackageManager.SIGNATURE_MATCH;
9115            }
9116            if (!match) {
9117                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9118                        == PackageManager.SIGNATURE_MATCH;
9119            }
9120            if (!match) {
9121                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9122                        + pkg.packageName + " signatures do not match the "
9123                        + "previously installed version; ignoring!");
9124            }
9125        }
9126
9127        // Check for shared user signatures
9128        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9129            // Already existing package. Make sure signatures match
9130            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9131                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9132            if (!match) {
9133                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9134                        == PackageManager.SIGNATURE_MATCH;
9135            }
9136            if (!match) {
9137                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9138                        == PackageManager.SIGNATURE_MATCH;
9139            }
9140            if (!match) {
9141                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9142                        "Package " + pkg.packageName
9143                        + " has no signatures that match those in shared user "
9144                        + pkgSetting.sharedUser.name + "; ignoring!");
9145            }
9146        }
9147    }
9148
9149    /**
9150     * Enforces that only the system UID or root's UID can call a method exposed
9151     * via Binder.
9152     *
9153     * @param message used as message if SecurityException is thrown
9154     * @throws SecurityException if the caller is not system or root
9155     */
9156    private static final void enforceSystemOrRoot(String message) {
9157        final int uid = Binder.getCallingUid();
9158        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9159            throw new SecurityException(message);
9160        }
9161    }
9162
9163    @Override
9164    public void performFstrimIfNeeded() {
9165        enforceSystemOrRoot("Only the system can request fstrim");
9166
9167        // Before everything else, see whether we need to fstrim.
9168        try {
9169            IStorageManager sm = PackageHelper.getStorageManager();
9170            if (sm != null) {
9171                boolean doTrim = false;
9172                final long interval = android.provider.Settings.Global.getLong(
9173                        mContext.getContentResolver(),
9174                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9175                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9176                if (interval > 0) {
9177                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9178                    if (timeSinceLast > interval) {
9179                        doTrim = true;
9180                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9181                                + "; running immediately");
9182                    }
9183                }
9184                if (doTrim) {
9185                    final boolean dexOptDialogShown;
9186                    synchronized (mPackages) {
9187                        dexOptDialogShown = mDexOptDialogShown;
9188                    }
9189                    if (!isFirstBoot() && dexOptDialogShown) {
9190                        try {
9191                            ActivityManager.getService().showBootMessage(
9192                                    mContext.getResources().getString(
9193                                            R.string.android_upgrading_fstrim), true);
9194                        } catch (RemoteException e) {
9195                        }
9196                    }
9197                    sm.runMaintenance();
9198                }
9199            } else {
9200                Slog.e(TAG, "storageManager service unavailable!");
9201            }
9202        } catch (RemoteException e) {
9203            // Can't happen; StorageManagerService is local
9204        }
9205    }
9206
9207    @Override
9208    public void updatePackagesIfNeeded() {
9209        enforceSystemOrRoot("Only the system can request package update");
9210
9211        // We need to re-extract after an OTA.
9212        boolean causeUpgrade = isUpgrade();
9213
9214        // First boot or factory reset.
9215        // Note: we also handle devices that are upgrading to N right now as if it is their
9216        //       first boot, as they do not have profile data.
9217        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9218
9219        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9220        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9221
9222        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9223            return;
9224        }
9225
9226        List<PackageParser.Package> pkgs;
9227        synchronized (mPackages) {
9228            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9229        }
9230
9231        final long startTime = System.nanoTime();
9232        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9233                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
9234                    false /* bootComplete */);
9235
9236        final int elapsedTimeSeconds =
9237                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9238
9239        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9240        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9241        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9242        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9243        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9244    }
9245
9246    /*
9247     * Return the prebuilt profile path given a package base code path.
9248     */
9249    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
9250        return pkg.baseCodePath + ".prof";
9251    }
9252
9253    /**
9254     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9255     * containing statistics about the invocation. The array consists of three elements,
9256     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9257     * and {@code numberOfPackagesFailed}.
9258     */
9259    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9260            String compilerFilter, boolean bootComplete) {
9261
9262        int numberOfPackagesVisited = 0;
9263        int numberOfPackagesOptimized = 0;
9264        int numberOfPackagesSkipped = 0;
9265        int numberOfPackagesFailed = 0;
9266        final int numberOfPackagesToDexopt = pkgs.size();
9267
9268        for (PackageParser.Package pkg : pkgs) {
9269            numberOfPackagesVisited++;
9270
9271            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9272                // Copy over initial preopt profiles since we won't get any JIT samples for methods
9273                // that are already compiled.
9274                File profileFile = new File(getPrebuildProfilePath(pkg));
9275                // Copy profile if it exists.
9276                if (profileFile.exists()) {
9277                    try {
9278                        // We could also do this lazily before calling dexopt in
9279                        // PackageDexOptimizer to prevent this happening on first boot. The issue
9280                        // is that we don't have a good way to say "do this only once".
9281                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9282                                pkg.applicationInfo.uid, pkg.packageName)) {
9283                            Log.e(TAG, "Installer failed to copy system profile!");
9284                        }
9285                    } catch (Exception e) {
9286                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9287                                e);
9288                    }
9289                }
9290            }
9291
9292            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9293                if (DEBUG_DEXOPT) {
9294                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9295                }
9296                numberOfPackagesSkipped++;
9297                continue;
9298            }
9299
9300            if (DEBUG_DEXOPT) {
9301                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9302                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9303            }
9304
9305            if (showDialog) {
9306                try {
9307                    ActivityManager.getService().showBootMessage(
9308                            mContext.getResources().getString(R.string.android_upgrading_apk,
9309                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9310                } catch (RemoteException e) {
9311                }
9312                synchronized (mPackages) {
9313                    mDexOptDialogShown = true;
9314                }
9315            }
9316
9317            // If the OTA updates a system app which was previously preopted to a non-preopted state
9318            // the app might end up being verified at runtime. That's because by default the apps
9319            // are verify-profile but for preopted apps there's no profile.
9320            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
9321            // that before the OTA the app was preopted) the app gets compiled with a non-profile
9322            // filter (by default 'quicken').
9323            // Note that at this stage unused apps are already filtered.
9324            if (isSystemApp(pkg) &&
9325                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
9326                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
9327                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
9328            }
9329
9330            // checkProfiles is false to avoid merging profiles during boot which
9331            // might interfere with background compilation (b/28612421).
9332            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9333            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9334            // trade-off worth doing to save boot time work.
9335            int dexOptStatus = performDexOptTraced(pkg.packageName,
9336                    false /* checkProfiles */,
9337                    compilerFilter,
9338                    false /* force */,
9339                    bootComplete);
9340            switch (dexOptStatus) {
9341                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9342                    numberOfPackagesOptimized++;
9343                    break;
9344                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9345                    numberOfPackagesSkipped++;
9346                    break;
9347                case PackageDexOptimizer.DEX_OPT_FAILED:
9348                    numberOfPackagesFailed++;
9349                    break;
9350                default:
9351                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
9352                    break;
9353            }
9354        }
9355
9356        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9357                numberOfPackagesFailed };
9358    }
9359
9360    @Override
9361    public void notifyPackageUse(String packageName, int reason) {
9362        synchronized (mPackages) {
9363            final int callingUid = Binder.getCallingUid();
9364            final int callingUserId = UserHandle.getUserId(callingUid);
9365            if (getInstantAppPackageName(callingUid) != null) {
9366                if (!isCallerSameApp(packageName, callingUid)) {
9367                    return;
9368                }
9369            } else {
9370                if (isInstantApp(packageName, callingUserId)) {
9371                    return;
9372                }
9373            }
9374            final PackageParser.Package p = mPackages.get(packageName);
9375            if (p == null) {
9376                return;
9377            }
9378            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9379        }
9380    }
9381
9382    @Override
9383    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
9384        int userId = UserHandle.getCallingUserId();
9385        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9386        if (ai == null) {
9387            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9388                + loadingPackageName + ", user=" + userId);
9389            return;
9390        }
9391        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
9392    }
9393
9394    @Override
9395    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9396            IDexModuleRegisterCallback callback) {
9397        int userId = UserHandle.getCallingUserId();
9398        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9399        DexManager.RegisterDexModuleResult result;
9400        if (ai == null) {
9401            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9402                     " calling user. package=" + packageName + ", user=" + userId);
9403            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9404        } else {
9405            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9406        }
9407
9408        if (callback != null) {
9409            mHandler.post(() -> {
9410                try {
9411                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9412                } catch (RemoteException e) {
9413                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9414                }
9415            });
9416        }
9417    }
9418
9419    @Override
9420    public boolean performDexOpt(String packageName,
9421            boolean checkProfiles, int compileReason, boolean force, boolean bootComplete) {
9422        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9423            return false;
9424        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9425            return false;
9426        }
9427        int dexoptStatus = performDexOptWithStatus(
9428              packageName, checkProfiles, compileReason, force, bootComplete);
9429        return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9430    }
9431
9432    /**
9433     * Perform dexopt on the given package and return one of following result:
9434     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9435     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9436     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9437     */
9438    /* package */ int performDexOptWithStatus(String packageName,
9439            boolean checkProfiles, int compileReason, boolean force, boolean bootComplete) {
9440        return performDexOptTraced(packageName, checkProfiles,
9441                getCompilerFilterForReason(compileReason), force, bootComplete);
9442    }
9443
9444    @Override
9445    public boolean performDexOptMode(String packageName,
9446            boolean checkProfiles, String targetCompilerFilter, boolean force,
9447            boolean bootComplete) {
9448        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9449            return false;
9450        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9451            return false;
9452        }
9453        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
9454                targetCompilerFilter, force, bootComplete);
9455        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9456    }
9457
9458    private int performDexOptTraced(String packageName,
9459                boolean checkProfiles, String targetCompilerFilter, boolean force,
9460                boolean bootComplete) {
9461        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9462        try {
9463            return performDexOptInternal(packageName, checkProfiles,
9464                    targetCompilerFilter, force, bootComplete);
9465        } finally {
9466            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9467        }
9468    }
9469
9470    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9471    // if the package can now be considered up to date for the given filter.
9472    private int performDexOptInternal(String packageName,
9473                boolean checkProfiles, String targetCompilerFilter, boolean force,
9474                boolean bootComplete) {
9475        PackageParser.Package p;
9476        synchronized (mPackages) {
9477            p = mPackages.get(packageName);
9478            if (p == null) {
9479                // Package could not be found. Report failure.
9480                return PackageDexOptimizer.DEX_OPT_FAILED;
9481            }
9482            mPackageUsage.maybeWriteAsync(mPackages);
9483            mCompilerStats.maybeWriteAsync();
9484        }
9485        long callingId = Binder.clearCallingIdentity();
9486        try {
9487            synchronized (mInstallLock) {
9488                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
9489                        targetCompilerFilter, force, bootComplete);
9490            }
9491        } finally {
9492            Binder.restoreCallingIdentity(callingId);
9493        }
9494    }
9495
9496    public ArraySet<String> getOptimizablePackages() {
9497        ArraySet<String> pkgs = new ArraySet<String>();
9498        synchronized (mPackages) {
9499            for (PackageParser.Package p : mPackages.values()) {
9500                if (PackageDexOptimizer.canOptimizePackage(p)) {
9501                    pkgs.add(p.packageName);
9502                }
9503            }
9504        }
9505        return pkgs;
9506    }
9507
9508    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9509            boolean checkProfiles, String targetCompilerFilter,
9510            boolean force, boolean bootComplete) {
9511        // Select the dex optimizer based on the force parameter.
9512        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9513        //       allocate an object here.
9514        PackageDexOptimizer pdo = force
9515                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9516                : mPackageDexOptimizer;
9517
9518        // Dexopt all dependencies first. Note: we ignore the return value and march on
9519        // on errors.
9520        // Note that we are going to call performDexOpt on those libraries as many times as
9521        // they are referenced in packages. When we do a batch of performDexOpt (for example
9522        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9523        // and the first package that uses the library will dexopt it. The
9524        // others will see that the compiled code for the library is up to date.
9525        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9526        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9527        if (!deps.isEmpty()) {
9528            for (PackageParser.Package depPackage : deps) {
9529                // TODO: Analyze and investigate if we (should) profile libraries.
9530                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9531                        false /* checkProfiles */,
9532                        targetCompilerFilter,
9533                        getOrCreateCompilerPackageStats(depPackage),
9534                        true /* isUsedByOtherApps */,
9535                        bootComplete);
9536            }
9537        }
9538        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
9539                targetCompilerFilter, getOrCreateCompilerPackageStats(p),
9540                mDexManager.isUsedByOtherApps(p.packageName), bootComplete);
9541    }
9542
9543    // Performs dexopt on the used secondary dex files belonging to the given package.
9544    // Returns true if all dex files were process successfully (which could mean either dexopt or
9545    // skip). Returns false if any of the files caused errors.
9546    @Override
9547    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9548            boolean force) {
9549        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9550            return false;
9551        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9552            return false;
9553        }
9554        mDexManager.reconcileSecondaryDexFiles(packageName);
9555        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
9556    }
9557
9558    public boolean performDexOptSecondary(String packageName, int compileReason,
9559            boolean force) {
9560        return mDexManager.dexoptSecondaryDex(packageName, compileReason, force);
9561    }
9562
9563    /**
9564     * Reconcile the information we have about the secondary dex files belonging to
9565     * {@code packagName} and the actual dex files. For all dex files that were
9566     * deleted, update the internal records and delete the generated oat files.
9567     */
9568    @Override
9569    public void reconcileSecondaryDexFiles(String packageName) {
9570        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9571            return;
9572        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9573            return;
9574        }
9575        mDexManager.reconcileSecondaryDexFiles(packageName);
9576    }
9577
9578    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9579    // a reference there.
9580    /*package*/ DexManager getDexManager() {
9581        return mDexManager;
9582    }
9583
9584    /**
9585     * Execute the background dexopt job immediately.
9586     */
9587    @Override
9588    public boolean runBackgroundDexoptJob() {
9589        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9590            return false;
9591        }
9592        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
9593    }
9594
9595    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9596        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9597                || p.usesStaticLibraries != null) {
9598            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9599            Set<String> collectedNames = new HashSet<>();
9600            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9601
9602            retValue.remove(p);
9603
9604            return retValue;
9605        } else {
9606            return Collections.emptyList();
9607        }
9608    }
9609
9610    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9611            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9612        if (!collectedNames.contains(p.packageName)) {
9613            collectedNames.add(p.packageName);
9614            collected.add(p);
9615
9616            if (p.usesLibraries != null) {
9617                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9618                        null, collected, collectedNames);
9619            }
9620            if (p.usesOptionalLibraries != null) {
9621                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9622                        null, collected, collectedNames);
9623            }
9624            if (p.usesStaticLibraries != null) {
9625                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9626                        p.usesStaticLibrariesVersions, collected, collectedNames);
9627            }
9628        }
9629    }
9630
9631    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
9632            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9633        final int libNameCount = libs.size();
9634        for (int i = 0; i < libNameCount; i++) {
9635            String libName = libs.get(i);
9636            int version = (versions != null && versions.length == libNameCount)
9637                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9638            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9639            if (libPkg != null) {
9640                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9641            }
9642        }
9643    }
9644
9645    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
9646        synchronized (mPackages) {
9647            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9648            if (libEntry != null) {
9649                return mPackages.get(libEntry.apk);
9650            }
9651            return null;
9652        }
9653    }
9654
9655    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
9656        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9657        if (versionedLib == null) {
9658            return null;
9659        }
9660        return versionedLib.get(version);
9661    }
9662
9663    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9664        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9665                pkg.staticSharedLibName);
9666        if (versionedLib == null) {
9667            return null;
9668        }
9669        int previousLibVersion = -1;
9670        final int versionCount = versionedLib.size();
9671        for (int i = 0; i < versionCount; i++) {
9672            final int libVersion = versionedLib.keyAt(i);
9673            if (libVersion < pkg.staticSharedLibVersion) {
9674                previousLibVersion = Math.max(previousLibVersion, libVersion);
9675            }
9676        }
9677        if (previousLibVersion >= 0) {
9678            return versionedLib.get(previousLibVersion);
9679        }
9680        return null;
9681    }
9682
9683    public void shutdown() {
9684        mPackageUsage.writeNow(mPackages);
9685        mCompilerStats.writeNow();
9686    }
9687
9688    @Override
9689    public void dumpProfiles(String packageName) {
9690        PackageParser.Package pkg;
9691        synchronized (mPackages) {
9692            pkg = mPackages.get(packageName);
9693            if (pkg == null) {
9694                throw new IllegalArgumentException("Unknown package: " + packageName);
9695            }
9696        }
9697        /* Only the shell, root, or the app user should be able to dump profiles. */
9698        int callingUid = Binder.getCallingUid();
9699        if (callingUid != Process.SHELL_UID &&
9700            callingUid != Process.ROOT_UID &&
9701            callingUid != pkg.applicationInfo.uid) {
9702            throw new SecurityException("dumpProfiles");
9703        }
9704
9705        synchronized (mInstallLock) {
9706            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9707            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
9708            try {
9709                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
9710                String codePaths = TextUtils.join(";", allCodePaths);
9711                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
9712            } catch (InstallerException e) {
9713                Slog.w(TAG, "Failed to dump profiles", e);
9714            }
9715            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9716        }
9717    }
9718
9719    @Override
9720    public void forceDexOpt(String packageName) {
9721        enforceSystemOrRoot("forceDexOpt");
9722
9723        PackageParser.Package pkg;
9724        synchronized (mPackages) {
9725            pkg = mPackages.get(packageName);
9726            if (pkg == null) {
9727                throw new IllegalArgumentException("Unknown package: " + packageName);
9728            }
9729        }
9730
9731        synchronized (mInstallLock) {
9732            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9733
9734            // Whoever is calling forceDexOpt wants a compiled package.
9735            // Don't use profiles since that may cause compilation to be skipped.
9736            final int res = performDexOptInternalWithDependenciesLI(pkg,
9737                    false /* checkProfiles */, getDefaultCompilerFilter(),
9738                    true /* force */,
9739                    true /* bootComplete */);
9740
9741            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9742            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9743                throw new IllegalStateException("Failed to dexopt: " + res);
9744            }
9745        }
9746    }
9747
9748    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9749        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9750            Slog.w(TAG, "Unable to update from " + oldPkg.name
9751                    + " to " + newPkg.packageName
9752                    + ": old package not in system partition");
9753            return false;
9754        } else if (mPackages.get(oldPkg.name) != null) {
9755            Slog.w(TAG, "Unable to update from " + oldPkg.name
9756                    + " to " + newPkg.packageName
9757                    + ": old package still exists");
9758            return false;
9759        }
9760        return true;
9761    }
9762
9763    void removeCodePathLI(File codePath) {
9764        if (codePath.isDirectory()) {
9765            try {
9766                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9767            } catch (InstallerException e) {
9768                Slog.w(TAG, "Failed to remove code path", e);
9769            }
9770        } else {
9771            codePath.delete();
9772        }
9773    }
9774
9775    private int[] resolveUserIds(int userId) {
9776        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9777    }
9778
9779    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9780        if (pkg == null) {
9781            Slog.wtf(TAG, "Package was null!", new Throwable());
9782            return;
9783        }
9784        clearAppDataLeafLIF(pkg, userId, flags);
9785        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9786        for (int i = 0; i < childCount; i++) {
9787            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9788        }
9789    }
9790
9791    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9792        final PackageSetting ps;
9793        synchronized (mPackages) {
9794            ps = mSettings.mPackages.get(pkg.packageName);
9795        }
9796        for (int realUserId : resolveUserIds(userId)) {
9797            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9798            try {
9799                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9800                        ceDataInode);
9801            } catch (InstallerException e) {
9802                Slog.w(TAG, String.valueOf(e));
9803            }
9804        }
9805    }
9806
9807    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9808        if (pkg == null) {
9809            Slog.wtf(TAG, "Package was null!", new Throwable());
9810            return;
9811        }
9812        destroyAppDataLeafLIF(pkg, userId, flags);
9813        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9814        for (int i = 0; i < childCount; i++) {
9815            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9816        }
9817    }
9818
9819    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9820        final PackageSetting ps;
9821        synchronized (mPackages) {
9822            ps = mSettings.mPackages.get(pkg.packageName);
9823        }
9824        for (int realUserId : resolveUserIds(userId)) {
9825            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9826            try {
9827                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9828                        ceDataInode);
9829            } catch (InstallerException e) {
9830                Slog.w(TAG, String.valueOf(e));
9831            }
9832            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9833        }
9834    }
9835
9836    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9837        if (pkg == null) {
9838            Slog.wtf(TAG, "Package was null!", new Throwable());
9839            return;
9840        }
9841        destroyAppProfilesLeafLIF(pkg);
9842        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9843        for (int i = 0; i < childCount; i++) {
9844            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9845        }
9846    }
9847
9848    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9849        try {
9850            mInstaller.destroyAppProfiles(pkg.packageName);
9851        } catch (InstallerException e) {
9852            Slog.w(TAG, String.valueOf(e));
9853        }
9854    }
9855
9856    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9857        if (pkg == null) {
9858            Slog.wtf(TAG, "Package was null!", new Throwable());
9859            return;
9860        }
9861        clearAppProfilesLeafLIF(pkg);
9862        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9863        for (int i = 0; i < childCount; i++) {
9864            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
9865        }
9866    }
9867
9868    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
9869        try {
9870            mInstaller.clearAppProfiles(pkg.packageName);
9871        } catch (InstallerException e) {
9872            Slog.w(TAG, String.valueOf(e));
9873        }
9874    }
9875
9876    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9877            long lastUpdateTime) {
9878        // Set parent install/update time
9879        PackageSetting ps = (PackageSetting) pkg.mExtras;
9880        if (ps != null) {
9881            ps.firstInstallTime = firstInstallTime;
9882            ps.lastUpdateTime = lastUpdateTime;
9883        }
9884        // Set children install/update time
9885        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9886        for (int i = 0; i < childCount; i++) {
9887            PackageParser.Package childPkg = pkg.childPackages.get(i);
9888            ps = (PackageSetting) childPkg.mExtras;
9889            if (ps != null) {
9890                ps.firstInstallTime = firstInstallTime;
9891                ps.lastUpdateTime = lastUpdateTime;
9892            }
9893        }
9894    }
9895
9896    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
9897            PackageParser.Package changingLib) {
9898        if (file.path != null) {
9899            usesLibraryFiles.add(file.path);
9900            return;
9901        }
9902        PackageParser.Package p = mPackages.get(file.apk);
9903        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9904            // If we are doing this while in the middle of updating a library apk,
9905            // then we need to make sure to use that new apk for determining the
9906            // dependencies here.  (We haven't yet finished committing the new apk
9907            // to the package manager state.)
9908            if (p == null || p.packageName.equals(changingLib.packageName)) {
9909                p = changingLib;
9910            }
9911        }
9912        if (p != null) {
9913            usesLibraryFiles.addAll(p.getAllCodePaths());
9914            if (p.usesLibraryFiles != null) {
9915                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9916            }
9917        }
9918    }
9919
9920    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9921            PackageParser.Package changingLib) throws PackageManagerException {
9922        if (pkg == null) {
9923            return;
9924        }
9925        ArraySet<String> usesLibraryFiles = null;
9926        if (pkg.usesLibraries != null) {
9927            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9928                    null, null, pkg.packageName, changingLib, true, null);
9929        }
9930        if (pkg.usesStaticLibraries != null) {
9931            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9932                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9933                    pkg.packageName, changingLib, true, usesLibraryFiles);
9934        }
9935        if (pkg.usesOptionalLibraries != null) {
9936            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9937                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
9938        }
9939        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9940            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9941        } else {
9942            pkg.usesLibraryFiles = null;
9943        }
9944    }
9945
9946    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9947            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
9948            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9949            boolean required, @Nullable ArraySet<String> outUsedLibraries)
9950            throws PackageManagerException {
9951        final int libCount = requestedLibraries.size();
9952        for (int i = 0; i < libCount; i++) {
9953            final String libName = requestedLibraries.get(i);
9954            final int libVersion = requiredVersions != null ? requiredVersions[i]
9955                    : SharedLibraryInfo.VERSION_UNDEFINED;
9956            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9957            if (libEntry == null) {
9958                if (required) {
9959                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9960                            "Package " + packageName + " requires unavailable shared library "
9961                                    + libName + "; failing!");
9962                } else if (DEBUG_SHARED_LIBRARIES) {
9963                    Slog.i(TAG, "Package " + packageName
9964                            + " desires unavailable shared library "
9965                            + libName + "; ignoring!");
9966                }
9967            } else {
9968                if (requiredVersions != null && requiredCertDigests != null) {
9969                    if (libEntry.info.getVersion() != requiredVersions[i]) {
9970                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9971                            "Package " + packageName + " requires unavailable static shared"
9972                                    + " library " + libName + " version "
9973                                    + libEntry.info.getVersion() + "; failing!");
9974                    }
9975
9976                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9977                    if (libPkg == null) {
9978                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9979                                "Package " + packageName + " requires unavailable static shared"
9980                                        + " library; failing!");
9981                    }
9982
9983                    String expectedCertDigest = requiredCertDigests[i];
9984                    String libCertDigest = PackageUtils.computeCertSha256Digest(
9985                                libPkg.mSignatures[0]);
9986                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
9987                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9988                                "Package " + packageName + " requires differently signed" +
9989                                        " static shared library; failing!");
9990                    }
9991                }
9992
9993                if (outUsedLibraries == null) {
9994                    outUsedLibraries = new ArraySet<>();
9995                }
9996                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9997            }
9998        }
9999        return outUsedLibraries;
10000    }
10001
10002    private static boolean hasString(List<String> list, List<String> which) {
10003        if (list == null) {
10004            return false;
10005        }
10006        for (int i=list.size()-1; i>=0; i--) {
10007            for (int j=which.size()-1; j>=0; j--) {
10008                if (which.get(j).equals(list.get(i))) {
10009                    return true;
10010                }
10011            }
10012        }
10013        return false;
10014    }
10015
10016    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
10017            PackageParser.Package changingPkg) {
10018        ArrayList<PackageParser.Package> res = null;
10019        for (PackageParser.Package pkg : mPackages.values()) {
10020            if (changingPkg != null
10021                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
10022                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
10023                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
10024                            changingPkg.staticSharedLibName)) {
10025                return null;
10026            }
10027            if (res == null) {
10028                res = new ArrayList<>();
10029            }
10030            res.add(pkg);
10031            try {
10032                updateSharedLibrariesLPr(pkg, changingPkg);
10033            } catch (PackageManagerException e) {
10034                // If a system app update or an app and a required lib missing we
10035                // delete the package and for updated system apps keep the data as
10036                // it is better for the user to reinstall than to be in an limbo
10037                // state. Also libs disappearing under an app should never happen
10038                // - just in case.
10039                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
10040                    final int flags = pkg.isUpdatedSystemApp()
10041                            ? PackageManager.DELETE_KEEP_DATA : 0;
10042                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
10043                            flags , null, true, null);
10044                }
10045                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
10046            }
10047        }
10048        return res;
10049    }
10050
10051    /**
10052     * Derive the value of the {@code cpuAbiOverride} based on the provided
10053     * value and an optional stored value from the package settings.
10054     */
10055    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
10056        String cpuAbiOverride = null;
10057
10058        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10059            cpuAbiOverride = null;
10060        } else if (abiOverride != null) {
10061            cpuAbiOverride = abiOverride;
10062        } else if (settings != null) {
10063            cpuAbiOverride = settings.cpuAbiOverrideString;
10064        }
10065
10066        return cpuAbiOverride;
10067    }
10068
10069    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10070            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10071                    throws PackageManagerException {
10072        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10073        // If the package has children and this is the first dive in the function
10074        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10075        // whether all packages (parent and children) would be successfully scanned
10076        // before the actual scan since scanning mutates internal state and we want
10077        // to atomically install the package and its children.
10078        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10079            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10080                scanFlags |= SCAN_CHECK_ONLY;
10081            }
10082        } else {
10083            scanFlags &= ~SCAN_CHECK_ONLY;
10084        }
10085
10086        final PackageParser.Package scannedPkg;
10087        try {
10088            // Scan the parent
10089            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10090            // Scan the children
10091            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10092            for (int i = 0; i < childCount; i++) {
10093                PackageParser.Package childPkg = pkg.childPackages.get(i);
10094                scanPackageLI(childPkg, policyFlags,
10095                        scanFlags, currentTime, user);
10096            }
10097        } finally {
10098            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10099        }
10100
10101        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10102            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10103        }
10104
10105        return scannedPkg;
10106    }
10107
10108    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10109            int scanFlags, long currentTime, @Nullable UserHandle user)
10110                    throws PackageManagerException {
10111        boolean success = false;
10112        try {
10113            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10114                    currentTime, user);
10115            success = true;
10116            return res;
10117        } finally {
10118            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10119                // DELETE_DATA_ON_FAILURES is only used by frozen paths
10120                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10121                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10122                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10123            }
10124        }
10125    }
10126
10127    /**
10128     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10129     */
10130    private static boolean apkHasCode(String fileName) {
10131        StrictJarFile jarFile = null;
10132        try {
10133            jarFile = new StrictJarFile(fileName,
10134                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10135            return jarFile.findEntry("classes.dex") != null;
10136        } catch (IOException ignore) {
10137        } finally {
10138            try {
10139                if (jarFile != null) {
10140                    jarFile.close();
10141                }
10142            } catch (IOException ignore) {}
10143        }
10144        return false;
10145    }
10146
10147    /**
10148     * Enforces code policy for the package. This ensures that if an APK has
10149     * declared hasCode="true" in its manifest that the APK actually contains
10150     * code.
10151     *
10152     * @throws PackageManagerException If bytecode could not be found when it should exist
10153     */
10154    private static void assertCodePolicy(PackageParser.Package pkg)
10155            throws PackageManagerException {
10156        final boolean shouldHaveCode =
10157                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10158        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10159            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10160                    "Package " + pkg.baseCodePath + " code is missing");
10161        }
10162
10163        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10164            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10165                final boolean splitShouldHaveCode =
10166                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10167                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10168                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10169                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10170                }
10171            }
10172        }
10173    }
10174
10175    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10176            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10177                    throws PackageManagerException {
10178        if (DEBUG_PACKAGE_SCANNING) {
10179            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10180                Log.d(TAG, "Scanning package " + pkg.packageName);
10181        }
10182
10183        applyPolicy(pkg, policyFlags);
10184
10185        assertPackageIsValid(pkg, policyFlags, scanFlags);
10186
10187        // Initialize package source and resource directories
10188        final File scanFile = new File(pkg.codePath);
10189        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10190        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10191
10192        SharedUserSetting suid = null;
10193        PackageSetting pkgSetting = null;
10194
10195        // Getting the package setting may have a side-effect, so if we
10196        // are only checking if scan would succeed, stash a copy of the
10197        // old setting to restore at the end.
10198        PackageSetting nonMutatedPs = null;
10199
10200        // We keep references to the derived CPU Abis from settings in oder to reuse
10201        // them in the case where we're not upgrading or booting for the first time.
10202        String primaryCpuAbiFromSettings = null;
10203        String secondaryCpuAbiFromSettings = null;
10204
10205        // writer
10206        synchronized (mPackages) {
10207            if (pkg.mSharedUserId != null) {
10208                // SIDE EFFECTS; may potentially allocate a new shared user
10209                suid = mSettings.getSharedUserLPw(
10210                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10211                if (DEBUG_PACKAGE_SCANNING) {
10212                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10213                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10214                                + "): packages=" + suid.packages);
10215                }
10216            }
10217
10218            // Check if we are renaming from an original package name.
10219            PackageSetting origPackage = null;
10220            String realName = null;
10221            if (pkg.mOriginalPackages != null) {
10222                // This package may need to be renamed to a previously
10223                // installed name.  Let's check on that...
10224                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10225                if (pkg.mOriginalPackages.contains(renamed)) {
10226                    // This package had originally been installed as the
10227                    // original name, and we have already taken care of
10228                    // transitioning to the new one.  Just update the new
10229                    // one to continue using the old name.
10230                    realName = pkg.mRealPackage;
10231                    if (!pkg.packageName.equals(renamed)) {
10232                        // Callers into this function may have already taken
10233                        // care of renaming the package; only do it here if
10234                        // it is not already done.
10235                        pkg.setPackageName(renamed);
10236                    }
10237                } else {
10238                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10239                        if ((origPackage = mSettings.getPackageLPr(
10240                                pkg.mOriginalPackages.get(i))) != null) {
10241                            // We do have the package already installed under its
10242                            // original name...  should we use it?
10243                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10244                                // New package is not compatible with original.
10245                                origPackage = null;
10246                                continue;
10247                            } else if (origPackage.sharedUser != null) {
10248                                // Make sure uid is compatible between packages.
10249                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10250                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10251                                            + " to " + pkg.packageName + ": old uid "
10252                                            + origPackage.sharedUser.name
10253                                            + " differs from " + pkg.mSharedUserId);
10254                                    origPackage = null;
10255                                    continue;
10256                                }
10257                                // TODO: Add case when shared user id is added [b/28144775]
10258                            } else {
10259                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10260                                        + pkg.packageName + " to old name " + origPackage.name);
10261                            }
10262                            break;
10263                        }
10264                    }
10265                }
10266            }
10267
10268            if (mTransferedPackages.contains(pkg.packageName)) {
10269                Slog.w(TAG, "Package " + pkg.packageName
10270                        + " was transferred to another, but its .apk remains");
10271            }
10272
10273            // See comments in nonMutatedPs declaration
10274            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10275                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10276                if (foundPs != null) {
10277                    nonMutatedPs = new PackageSetting(foundPs);
10278                }
10279            }
10280
10281            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10282                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10283                if (foundPs != null) {
10284                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10285                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10286                }
10287            }
10288
10289            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10290            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10291                PackageManagerService.reportSettingsProblem(Log.WARN,
10292                        "Package " + pkg.packageName + " shared user changed from "
10293                                + (pkgSetting.sharedUser != null
10294                                        ? pkgSetting.sharedUser.name : "<nothing>")
10295                                + " to "
10296                                + (suid != null ? suid.name : "<nothing>")
10297                                + "; replacing with new");
10298                pkgSetting = null;
10299            }
10300            final PackageSetting oldPkgSetting =
10301                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10302            final PackageSetting disabledPkgSetting =
10303                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10304
10305            String[] usesStaticLibraries = null;
10306            if (pkg.usesStaticLibraries != null) {
10307                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10308                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10309            }
10310
10311            if (pkgSetting == null) {
10312                final String parentPackageName = (pkg.parentPackage != null)
10313                        ? pkg.parentPackage.packageName : null;
10314                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10315                // REMOVE SharedUserSetting from method; update in a separate call
10316                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10317                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10318                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10319                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10320                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10321                        true /*allowInstall*/, instantApp, parentPackageName,
10322                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
10323                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10324                // SIDE EFFECTS; updates system state; move elsewhere
10325                if (origPackage != null) {
10326                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10327                }
10328                mSettings.addUserToSettingLPw(pkgSetting);
10329            } else {
10330                // REMOVE SharedUserSetting from method; update in a separate call.
10331                //
10332                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10333                // secondaryCpuAbi are not known at this point so we always update them
10334                // to null here, only to reset them at a later point.
10335                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10336                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10337                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10338                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10339                        UserManagerService.getInstance(), usesStaticLibraries,
10340                        pkg.usesStaticLibrariesVersions);
10341            }
10342            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10343            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10344
10345            // SIDE EFFECTS; modifies system state; move elsewhere
10346            if (pkgSetting.origPackage != null) {
10347                // If we are first transitioning from an original package,
10348                // fix up the new package's name now.  We need to do this after
10349                // looking up the package under its new name, so getPackageLP
10350                // can take care of fiddling things correctly.
10351                pkg.setPackageName(origPackage.name);
10352
10353                // File a report about this.
10354                String msg = "New package " + pkgSetting.realName
10355                        + " renamed to replace old package " + pkgSetting.name;
10356                reportSettingsProblem(Log.WARN, msg);
10357
10358                // Make a note of it.
10359                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10360                    mTransferedPackages.add(origPackage.name);
10361                }
10362
10363                // No longer need to retain this.
10364                pkgSetting.origPackage = null;
10365            }
10366
10367            // SIDE EFFECTS; modifies system state; move elsewhere
10368            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10369                // Make a note of it.
10370                mTransferedPackages.add(pkg.packageName);
10371            }
10372
10373            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10374                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10375            }
10376
10377            if ((scanFlags & SCAN_BOOTING) == 0
10378                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10379                // Check all shared libraries and map to their actual file path.
10380                // We only do this here for apps not on a system dir, because those
10381                // are the only ones that can fail an install due to this.  We
10382                // will take care of the system apps by updating all of their
10383                // library paths after the scan is done. Also during the initial
10384                // scan don't update any libs as we do this wholesale after all
10385                // apps are scanned to avoid dependency based scanning.
10386                updateSharedLibrariesLPr(pkg, null);
10387            }
10388
10389            if (mFoundPolicyFile) {
10390                SELinuxMMAC.assignSeInfoValue(pkg);
10391            }
10392            pkg.applicationInfo.uid = pkgSetting.appId;
10393            pkg.mExtras = pkgSetting;
10394
10395
10396            // Static shared libs have same package with different versions where
10397            // we internally use a synthetic package name to allow multiple versions
10398            // of the same package, therefore we need to compare signatures against
10399            // the package setting for the latest library version.
10400            PackageSetting signatureCheckPs = pkgSetting;
10401            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10402                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10403                if (libraryEntry != null) {
10404                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10405                }
10406            }
10407
10408            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10409                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10410                    // We just determined the app is signed correctly, so bring
10411                    // over the latest parsed certs.
10412                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10413                } else {
10414                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10415                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10416                                "Package " + pkg.packageName + " upgrade keys do not match the "
10417                                + "previously installed version");
10418                    } else {
10419                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10420                        String msg = "System package " + pkg.packageName
10421                                + " signature changed; retaining data.";
10422                        reportSettingsProblem(Log.WARN, msg);
10423                    }
10424                }
10425            } else {
10426                try {
10427                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10428                    verifySignaturesLP(signatureCheckPs, pkg);
10429                    // We just determined the app is signed correctly, so bring
10430                    // over the latest parsed certs.
10431                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10432                } catch (PackageManagerException e) {
10433                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10434                        throw e;
10435                    }
10436                    // The signature has changed, but this package is in the system
10437                    // image...  let's recover!
10438                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10439                    // However...  if this package is part of a shared user, but it
10440                    // doesn't match the signature of the shared user, let's fail.
10441                    // What this means is that you can't change the signatures
10442                    // associated with an overall shared user, which doesn't seem all
10443                    // that unreasonable.
10444                    if (signatureCheckPs.sharedUser != null) {
10445                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10446                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10447                            throw new PackageManagerException(
10448                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10449                                    "Signature mismatch for shared user: "
10450                                            + pkgSetting.sharedUser);
10451                        }
10452                    }
10453                    // File a report about this.
10454                    String msg = "System package " + pkg.packageName
10455                            + " signature changed; retaining data.";
10456                    reportSettingsProblem(Log.WARN, msg);
10457                }
10458            }
10459
10460            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10461                // This package wants to adopt ownership of permissions from
10462                // another package.
10463                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10464                    final String origName = pkg.mAdoptPermissions.get(i);
10465                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10466                    if (orig != null) {
10467                        if (verifyPackageUpdateLPr(orig, pkg)) {
10468                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10469                                    + pkg.packageName);
10470                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10471                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
10472                        }
10473                    }
10474                }
10475            }
10476        }
10477
10478        pkg.applicationInfo.processName = fixProcessName(
10479                pkg.applicationInfo.packageName,
10480                pkg.applicationInfo.processName);
10481
10482        if (pkg != mPlatformPackage) {
10483            // Get all of our default paths setup
10484            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10485        }
10486
10487        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10488
10489        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10490            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10491                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10492                derivePackageAbi(
10493                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
10494                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10495
10496                // Some system apps still use directory structure for native libraries
10497                // in which case we might end up not detecting abi solely based on apk
10498                // structure. Try to detect abi based on directory structure.
10499                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10500                        pkg.applicationInfo.primaryCpuAbi == null) {
10501                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10502                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10503                }
10504            } else {
10505                // This is not a first boot or an upgrade, don't bother deriving the
10506                // ABI during the scan. Instead, trust the value that was stored in the
10507                // package setting.
10508                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10509                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10510
10511                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10512
10513                if (DEBUG_ABI_SELECTION) {
10514                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10515                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10516                        pkg.applicationInfo.secondaryCpuAbi);
10517                }
10518            }
10519        } else {
10520            if ((scanFlags & SCAN_MOVE) != 0) {
10521                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10522                // but we already have this packages package info in the PackageSetting. We just
10523                // use that and derive the native library path based on the new codepath.
10524                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10525                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10526            }
10527
10528            // Set native library paths again. For moves, the path will be updated based on the
10529            // ABIs we've determined above. For non-moves, the path will be updated based on the
10530            // ABIs we determined during compilation, but the path will depend on the final
10531            // package path (after the rename away from the stage path).
10532            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10533        }
10534
10535        // This is a special case for the "system" package, where the ABI is
10536        // dictated by the zygote configuration (and init.rc). We should keep track
10537        // of this ABI so that we can deal with "normal" applications that run under
10538        // the same UID correctly.
10539        if (mPlatformPackage == pkg) {
10540            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10541                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10542        }
10543
10544        // If there's a mismatch between the abi-override in the package setting
10545        // and the abiOverride specified for the install. Warn about this because we
10546        // would've already compiled the app without taking the package setting into
10547        // account.
10548        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10549            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10550                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10551                        " for package " + pkg.packageName);
10552            }
10553        }
10554
10555        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10556        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10557        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10558
10559        // Copy the derived override back to the parsed package, so that we can
10560        // update the package settings accordingly.
10561        pkg.cpuAbiOverride = cpuAbiOverride;
10562
10563        if (DEBUG_ABI_SELECTION) {
10564            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10565                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10566                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10567        }
10568
10569        // Push the derived path down into PackageSettings so we know what to
10570        // clean up at uninstall time.
10571        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10572
10573        if (DEBUG_ABI_SELECTION) {
10574            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10575                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10576                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10577        }
10578
10579        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
10580        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10581            // We don't do this here during boot because we can do it all
10582            // at once after scanning all existing packages.
10583            //
10584            // We also do this *before* we perform dexopt on this package, so that
10585            // we can avoid redundant dexopts, and also to make sure we've got the
10586            // code and package path correct.
10587            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10588        }
10589
10590        if (mFactoryTest && pkg.requestedPermissions.contains(
10591                android.Manifest.permission.FACTORY_TEST)) {
10592            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10593        }
10594
10595        if (isSystemApp(pkg)) {
10596            pkgSetting.isOrphaned = true;
10597        }
10598
10599        // Take care of first install / last update times.
10600        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
10601        if (currentTime != 0) {
10602            if (pkgSetting.firstInstallTime == 0) {
10603                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10604            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10605                pkgSetting.lastUpdateTime = currentTime;
10606            }
10607        } else if (pkgSetting.firstInstallTime == 0) {
10608            // We need *something*.  Take time time stamp of the file.
10609            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10610        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10611            if (scanFileTime != pkgSetting.timeStamp) {
10612                // A package on the system image has changed; consider this
10613                // to be an update.
10614                pkgSetting.lastUpdateTime = scanFileTime;
10615            }
10616        }
10617        pkgSetting.setTimeStamp(scanFileTime);
10618
10619        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10620            if (nonMutatedPs != null) {
10621                synchronized (mPackages) {
10622                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
10623                }
10624            }
10625        } else {
10626            final int userId = user == null ? 0 : user.getIdentifier();
10627            // Modify state for the given package setting
10628            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10629                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10630            if (pkgSetting.getInstantApp(userId)) {
10631                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10632            }
10633        }
10634        return pkg;
10635    }
10636
10637    /**
10638     * Applies policy to the parsed package based upon the given policy flags.
10639     * Ensures the package is in a good state.
10640     * <p>
10641     * Implementation detail: This method must NOT have any side effect. It would
10642     * ideally be static, but, it requires locks to read system state.
10643     */
10644    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
10645        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
10646            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10647            if (pkg.applicationInfo.isDirectBootAware()) {
10648                // we're direct boot aware; set for all components
10649                for (PackageParser.Service s : pkg.services) {
10650                    s.info.encryptionAware = s.info.directBootAware = true;
10651                }
10652                for (PackageParser.Provider p : pkg.providers) {
10653                    p.info.encryptionAware = p.info.directBootAware = true;
10654                }
10655                for (PackageParser.Activity a : pkg.activities) {
10656                    a.info.encryptionAware = a.info.directBootAware = true;
10657                }
10658                for (PackageParser.Activity r : pkg.receivers) {
10659                    r.info.encryptionAware = r.info.directBootAware = true;
10660                }
10661            }
10662        } else {
10663            // Only allow system apps to be flagged as core apps.
10664            pkg.coreApp = false;
10665            // clear flags not applicable to regular apps
10666            pkg.applicationInfo.privateFlags &=
10667                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10668            pkg.applicationInfo.privateFlags &=
10669                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10670        }
10671        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
10672
10673        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
10674            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10675        }
10676
10677        if (!isSystemApp(pkg)) {
10678            // Only system apps can use these features.
10679            pkg.mOriginalPackages = null;
10680            pkg.mRealPackage = null;
10681            pkg.mAdoptPermissions = null;
10682        }
10683    }
10684
10685    /**
10686     * Asserts the parsed package is valid according to the given policy. If the
10687     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10688     * <p>
10689     * Implementation detail: This method must NOT have any side effects. It would
10690     * ideally be static, but, it requires locks to read system state.
10691     *
10692     * @throws PackageManagerException If the package fails any of the validation checks
10693     */
10694    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
10695            throws PackageManagerException {
10696        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10697            assertCodePolicy(pkg);
10698        }
10699
10700        if (pkg.applicationInfo.getCodePath() == null ||
10701                pkg.applicationInfo.getResourcePath() == null) {
10702            // Bail out. The resource and code paths haven't been set.
10703            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10704                    "Code and resource paths haven't been set correctly");
10705        }
10706
10707        // Make sure we're not adding any bogus keyset info
10708        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10709        ksms.assertScannedPackageValid(pkg);
10710
10711        synchronized (mPackages) {
10712            // The special "android" package can only be defined once
10713            if (pkg.packageName.equals("android")) {
10714                if (mAndroidApplication != null) {
10715                    Slog.w(TAG, "*************************************************");
10716                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10717                    Slog.w(TAG, " codePath=" + pkg.codePath);
10718                    Slog.w(TAG, "*************************************************");
10719                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10720                            "Core android package being redefined.  Skipping.");
10721                }
10722            }
10723
10724            // A package name must be unique; don't allow duplicates
10725            if (mPackages.containsKey(pkg.packageName)) {
10726                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10727                        "Application package " + pkg.packageName
10728                        + " already installed.  Skipping duplicate.");
10729            }
10730
10731            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10732                // Static libs have a synthetic package name containing the version
10733                // but we still want the base name to be unique.
10734                if (mPackages.containsKey(pkg.manifestPackageName)) {
10735                    throw new PackageManagerException(
10736                            "Duplicate static shared lib provider package");
10737                }
10738
10739                // Static shared libraries should have at least O target SDK
10740                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10741                    throw new PackageManagerException(
10742                            "Packages declaring static-shared libs must target O SDK or higher");
10743                }
10744
10745                // Package declaring static a shared lib cannot be instant apps
10746                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10747                    throw new PackageManagerException(
10748                            "Packages declaring static-shared libs cannot be instant apps");
10749                }
10750
10751                // Package declaring static a shared lib cannot be renamed since the package
10752                // name is synthetic and apps can't code around package manager internals.
10753                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10754                    throw new PackageManagerException(
10755                            "Packages declaring static-shared libs cannot be renamed");
10756                }
10757
10758                // Package declaring static a shared lib cannot declare child packages
10759                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10760                    throw new PackageManagerException(
10761                            "Packages declaring static-shared libs cannot have child packages");
10762                }
10763
10764                // Package declaring static a shared lib cannot declare dynamic libs
10765                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10766                    throw new PackageManagerException(
10767                            "Packages declaring static-shared libs cannot declare dynamic libs");
10768                }
10769
10770                // Package declaring static a shared lib cannot declare shared users
10771                if (pkg.mSharedUserId != null) {
10772                    throw new PackageManagerException(
10773                            "Packages declaring static-shared libs cannot declare shared users");
10774                }
10775
10776                // Static shared libs cannot declare activities
10777                if (!pkg.activities.isEmpty()) {
10778                    throw new PackageManagerException(
10779                            "Static shared libs cannot declare activities");
10780                }
10781
10782                // Static shared libs cannot declare services
10783                if (!pkg.services.isEmpty()) {
10784                    throw new PackageManagerException(
10785                            "Static shared libs cannot declare services");
10786                }
10787
10788                // Static shared libs cannot declare providers
10789                if (!pkg.providers.isEmpty()) {
10790                    throw new PackageManagerException(
10791                            "Static shared libs cannot declare content providers");
10792                }
10793
10794                // Static shared libs cannot declare receivers
10795                if (!pkg.receivers.isEmpty()) {
10796                    throw new PackageManagerException(
10797                            "Static shared libs cannot declare broadcast receivers");
10798                }
10799
10800                // Static shared libs cannot declare permission groups
10801                if (!pkg.permissionGroups.isEmpty()) {
10802                    throw new PackageManagerException(
10803                            "Static shared libs cannot declare permission groups");
10804                }
10805
10806                // Static shared libs cannot declare permissions
10807                if (!pkg.permissions.isEmpty()) {
10808                    throw new PackageManagerException(
10809                            "Static shared libs cannot declare permissions");
10810                }
10811
10812                // Static shared libs cannot declare protected broadcasts
10813                if (pkg.protectedBroadcasts != null) {
10814                    throw new PackageManagerException(
10815                            "Static shared libs cannot declare protected broadcasts");
10816                }
10817
10818                // Static shared libs cannot be overlay targets
10819                if (pkg.mOverlayTarget != null) {
10820                    throw new PackageManagerException(
10821                            "Static shared libs cannot be overlay targets");
10822                }
10823
10824                // The version codes must be ordered as lib versions
10825                int minVersionCode = Integer.MIN_VALUE;
10826                int maxVersionCode = Integer.MAX_VALUE;
10827
10828                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10829                        pkg.staticSharedLibName);
10830                if (versionedLib != null) {
10831                    final int versionCount = versionedLib.size();
10832                    for (int i = 0; i < versionCount; i++) {
10833                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10834                        final int libVersionCode = libInfo.getDeclaringPackage()
10835                                .getVersionCode();
10836                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
10837                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10838                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
10839                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10840                        } else {
10841                            minVersionCode = maxVersionCode = libVersionCode;
10842                            break;
10843                        }
10844                    }
10845                }
10846                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
10847                    throw new PackageManagerException("Static shared"
10848                            + " lib version codes must be ordered as lib versions");
10849                }
10850            }
10851
10852            // Only privileged apps and updated privileged apps can add child packages.
10853            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10854                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
10855                    throw new PackageManagerException("Only privileged apps can add child "
10856                            + "packages. Ignoring package " + pkg.packageName);
10857                }
10858                final int childCount = pkg.childPackages.size();
10859                for (int i = 0; i < childCount; i++) {
10860                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10861                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10862                            childPkg.packageName)) {
10863                        throw new PackageManagerException("Can't override child of "
10864                                + "another disabled app. Ignoring package " + pkg.packageName);
10865                    }
10866                }
10867            }
10868
10869            // If we're only installing presumed-existing packages, require that the
10870            // scanned APK is both already known and at the path previously established
10871            // for it.  Previously unknown packages we pick up normally, but if we have an
10872            // a priori expectation about this package's install presence, enforce it.
10873            // With a singular exception for new system packages. When an OTA contains
10874            // a new system package, we allow the codepath to change from a system location
10875            // to the user-installed location. If we don't allow this change, any newer,
10876            // user-installed version of the application will be ignored.
10877            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10878                if (mExpectingBetter.containsKey(pkg.packageName)) {
10879                    logCriticalInfo(Log.WARN,
10880                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10881                } else {
10882                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10883                    if (known != null) {
10884                        if (DEBUG_PACKAGE_SCANNING) {
10885                            Log.d(TAG, "Examining " + pkg.codePath
10886                                    + " and requiring known paths " + known.codePathString
10887                                    + " & " + known.resourcePathString);
10888                        }
10889                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10890                                || !pkg.applicationInfo.getResourcePath().equals(
10891                                        known.resourcePathString)) {
10892                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10893                                    "Application package " + pkg.packageName
10894                                    + " found at " + pkg.applicationInfo.getCodePath()
10895                                    + " but expected at " + known.codePathString
10896                                    + "; ignoring.");
10897                        }
10898                    }
10899                }
10900            }
10901
10902            // Verify that this new package doesn't have any content providers
10903            // that conflict with existing packages.  Only do this if the
10904            // package isn't already installed, since we don't want to break
10905            // things that are installed.
10906            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10907                final int N = pkg.providers.size();
10908                int i;
10909                for (i=0; i<N; i++) {
10910                    PackageParser.Provider p = pkg.providers.get(i);
10911                    if (p.info.authority != null) {
10912                        String names[] = p.info.authority.split(";");
10913                        for (int j = 0; j < names.length; j++) {
10914                            if (mProvidersByAuthority.containsKey(names[j])) {
10915                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10916                                final String otherPackageName =
10917                                        ((other != null && other.getComponentName() != null) ?
10918                                                other.getComponentName().getPackageName() : "?");
10919                                throw new PackageManagerException(
10920                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10921                                        "Can't install because provider name " + names[j]
10922                                                + " (in package " + pkg.applicationInfo.packageName
10923                                                + ") is already used by " + otherPackageName);
10924                            }
10925                        }
10926                    }
10927                }
10928            }
10929        }
10930    }
10931
10932    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
10933            int type, String declaringPackageName, int declaringVersionCode) {
10934        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10935        if (versionedLib == null) {
10936            versionedLib = new SparseArray<>();
10937            mSharedLibraries.put(name, versionedLib);
10938            if (type == SharedLibraryInfo.TYPE_STATIC) {
10939                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
10940            }
10941        } else if (versionedLib.indexOfKey(version) >= 0) {
10942            return false;
10943        }
10944        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
10945                version, type, declaringPackageName, declaringVersionCode);
10946        versionedLib.put(version, libEntry);
10947        return true;
10948    }
10949
10950    private boolean removeSharedLibraryLPw(String name, int version) {
10951        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10952        if (versionedLib == null) {
10953            return false;
10954        }
10955        final int libIdx = versionedLib.indexOfKey(version);
10956        if (libIdx < 0) {
10957            return false;
10958        }
10959        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
10960        versionedLib.remove(version);
10961        if (versionedLib.size() <= 0) {
10962            mSharedLibraries.remove(name);
10963            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
10964                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
10965                        .getPackageName());
10966            }
10967        }
10968        return true;
10969    }
10970
10971    /**
10972     * Adds a scanned package to the system. When this method is finished, the package will
10973     * be available for query, resolution, etc...
10974     */
10975    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
10976            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
10977        final String pkgName = pkg.packageName;
10978        if (mCustomResolverComponentName != null &&
10979                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
10980            setUpCustomResolverActivity(pkg);
10981        }
10982
10983        if (pkg.packageName.equals("android")) {
10984            synchronized (mPackages) {
10985                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10986                    // Set up information for our fall-back user intent resolution activity.
10987                    mPlatformPackage = pkg;
10988                    pkg.mVersionCode = mSdkVersion;
10989                    mAndroidApplication = pkg.applicationInfo;
10990                    if (!mResolverReplaced) {
10991                        mResolveActivity.applicationInfo = mAndroidApplication;
10992                        mResolveActivity.name = ResolverActivity.class.getName();
10993                        mResolveActivity.packageName = mAndroidApplication.packageName;
10994                        mResolveActivity.processName = "system:ui";
10995                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10996                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
10997                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
10998                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
10999                        mResolveActivity.exported = true;
11000                        mResolveActivity.enabled = true;
11001                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11002                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11003                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11004                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11005                                | ActivityInfo.CONFIG_ORIENTATION
11006                                | ActivityInfo.CONFIG_KEYBOARD
11007                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11008                        mResolveInfo.activityInfo = mResolveActivity;
11009                        mResolveInfo.priority = 0;
11010                        mResolveInfo.preferredOrder = 0;
11011                        mResolveInfo.match = 0;
11012                        mResolveComponentName = new ComponentName(
11013                                mAndroidApplication.packageName, mResolveActivity.name);
11014                    }
11015                }
11016            }
11017        }
11018
11019        ArrayList<PackageParser.Package> clientLibPkgs = null;
11020        // writer
11021        synchronized (mPackages) {
11022            boolean hasStaticSharedLibs = false;
11023
11024            // Any app can add new static shared libraries
11025            if (pkg.staticSharedLibName != null) {
11026                // Static shared libs don't allow renaming as they have synthetic package
11027                // names to allow install of multiple versions, so use name from manifest.
11028                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11029                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11030                        pkg.manifestPackageName, pkg.mVersionCode)) {
11031                    hasStaticSharedLibs = true;
11032                } else {
11033                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11034                                + pkg.staticSharedLibName + " already exists; skipping");
11035                }
11036                // Static shared libs cannot be updated once installed since they
11037                // use synthetic package name which includes the version code, so
11038                // not need to update other packages's shared lib dependencies.
11039            }
11040
11041            if (!hasStaticSharedLibs
11042                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11043                // Only system apps can add new dynamic shared libraries.
11044                if (pkg.libraryNames != null) {
11045                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11046                        String name = pkg.libraryNames.get(i);
11047                        boolean allowed = false;
11048                        if (pkg.isUpdatedSystemApp()) {
11049                            // New library entries can only be added through the
11050                            // system image.  This is important to get rid of a lot
11051                            // of nasty edge cases: for example if we allowed a non-
11052                            // system update of the app to add a library, then uninstalling
11053                            // the update would make the library go away, and assumptions
11054                            // we made such as through app install filtering would now
11055                            // have allowed apps on the device which aren't compatible
11056                            // with it.  Better to just have the restriction here, be
11057                            // conservative, and create many fewer cases that can negatively
11058                            // impact the user experience.
11059                            final PackageSetting sysPs = mSettings
11060                                    .getDisabledSystemPkgLPr(pkg.packageName);
11061                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11062                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11063                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11064                                        allowed = true;
11065                                        break;
11066                                    }
11067                                }
11068                            }
11069                        } else {
11070                            allowed = true;
11071                        }
11072                        if (allowed) {
11073                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11074                                    SharedLibraryInfo.VERSION_UNDEFINED,
11075                                    SharedLibraryInfo.TYPE_DYNAMIC,
11076                                    pkg.packageName, pkg.mVersionCode)) {
11077                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11078                                        + name + " already exists; skipping");
11079                            }
11080                        } else {
11081                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11082                                    + name + " that is not declared on system image; skipping");
11083                        }
11084                    }
11085
11086                    if ((scanFlags & SCAN_BOOTING) == 0) {
11087                        // If we are not booting, we need to update any applications
11088                        // that are clients of our shared library.  If we are booting,
11089                        // this will all be done once the scan is complete.
11090                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11091                    }
11092                }
11093            }
11094        }
11095
11096        if ((scanFlags & SCAN_BOOTING) != 0) {
11097            // No apps can run during boot scan, so they don't need to be frozen
11098        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11099            // Caller asked to not kill app, so it's probably not frozen
11100        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11101            // Caller asked us to ignore frozen check for some reason; they
11102            // probably didn't know the package name
11103        } else {
11104            // We're doing major surgery on this package, so it better be frozen
11105            // right now to keep it from launching
11106            checkPackageFrozen(pkgName);
11107        }
11108
11109        // Also need to kill any apps that are dependent on the library.
11110        if (clientLibPkgs != null) {
11111            for (int i=0; i<clientLibPkgs.size(); i++) {
11112                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11113                killApplication(clientPkg.applicationInfo.packageName,
11114                        clientPkg.applicationInfo.uid, "update lib");
11115            }
11116        }
11117
11118        // writer
11119        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11120
11121        synchronized (mPackages) {
11122            // We don't expect installation to fail beyond this point
11123
11124            // Add the new setting to mSettings
11125            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11126            // Add the new setting to mPackages
11127            mPackages.put(pkg.applicationInfo.packageName, pkg);
11128            // Make sure we don't accidentally delete its data.
11129            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11130            while (iter.hasNext()) {
11131                PackageCleanItem item = iter.next();
11132                if (pkgName.equals(item.packageName)) {
11133                    iter.remove();
11134                }
11135            }
11136
11137            // Add the package's KeySets to the global KeySetManagerService
11138            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11139            ksms.addScannedPackageLPw(pkg);
11140
11141            int N = pkg.providers.size();
11142            StringBuilder r = null;
11143            int i;
11144            for (i=0; i<N; i++) {
11145                PackageParser.Provider p = pkg.providers.get(i);
11146                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11147                        p.info.processName);
11148                mProviders.addProvider(p);
11149                p.syncable = p.info.isSyncable;
11150                if (p.info.authority != null) {
11151                    String names[] = p.info.authority.split(";");
11152                    p.info.authority = null;
11153                    for (int j = 0; j < names.length; j++) {
11154                        if (j == 1 && p.syncable) {
11155                            // We only want the first authority for a provider to possibly be
11156                            // syncable, so if we already added this provider using a different
11157                            // authority clear the syncable flag. We copy the provider before
11158                            // changing it because the mProviders object contains a reference
11159                            // to a provider that we don't want to change.
11160                            // Only do this for the second authority since the resulting provider
11161                            // object can be the same for all future authorities for this provider.
11162                            p = new PackageParser.Provider(p);
11163                            p.syncable = false;
11164                        }
11165                        if (!mProvidersByAuthority.containsKey(names[j])) {
11166                            mProvidersByAuthority.put(names[j], p);
11167                            if (p.info.authority == null) {
11168                                p.info.authority = names[j];
11169                            } else {
11170                                p.info.authority = p.info.authority + ";" + names[j];
11171                            }
11172                            if (DEBUG_PACKAGE_SCANNING) {
11173                                if (chatty)
11174                                    Log.d(TAG, "Registered content provider: " + names[j]
11175                                            + ", className = " + p.info.name + ", isSyncable = "
11176                                            + p.info.isSyncable);
11177                            }
11178                        } else {
11179                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11180                            Slog.w(TAG, "Skipping provider name " + names[j] +
11181                                    " (in package " + pkg.applicationInfo.packageName +
11182                                    "): name already used by "
11183                                    + ((other != null && other.getComponentName() != null)
11184                                            ? other.getComponentName().getPackageName() : "?"));
11185                        }
11186                    }
11187                }
11188                if (chatty) {
11189                    if (r == null) {
11190                        r = new StringBuilder(256);
11191                    } else {
11192                        r.append(' ');
11193                    }
11194                    r.append(p.info.name);
11195                }
11196            }
11197            if (r != null) {
11198                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11199            }
11200
11201            N = pkg.services.size();
11202            r = null;
11203            for (i=0; i<N; i++) {
11204                PackageParser.Service s = pkg.services.get(i);
11205                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11206                        s.info.processName);
11207                mServices.addService(s);
11208                if (chatty) {
11209                    if (r == null) {
11210                        r = new StringBuilder(256);
11211                    } else {
11212                        r.append(' ');
11213                    }
11214                    r.append(s.info.name);
11215                }
11216            }
11217            if (r != null) {
11218                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11219            }
11220
11221            N = pkg.receivers.size();
11222            r = null;
11223            for (i=0; i<N; i++) {
11224                PackageParser.Activity a = pkg.receivers.get(i);
11225                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11226                        a.info.processName);
11227                mReceivers.addActivity(a, "receiver");
11228                if (chatty) {
11229                    if (r == null) {
11230                        r = new StringBuilder(256);
11231                    } else {
11232                        r.append(' ');
11233                    }
11234                    r.append(a.info.name);
11235                }
11236            }
11237            if (r != null) {
11238                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11239            }
11240
11241            N = pkg.activities.size();
11242            r = null;
11243            for (i=0; i<N; i++) {
11244                PackageParser.Activity a = pkg.activities.get(i);
11245                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11246                        a.info.processName);
11247                mActivities.addActivity(a, "activity");
11248                if (chatty) {
11249                    if (r == null) {
11250                        r = new StringBuilder(256);
11251                    } else {
11252                        r.append(' ');
11253                    }
11254                    r.append(a.info.name);
11255                }
11256            }
11257            if (r != null) {
11258                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11259            }
11260
11261            N = pkg.permissionGroups.size();
11262            r = null;
11263            for (i=0; i<N; i++) {
11264                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11265                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11266                final String curPackageName = cur == null ? null : cur.info.packageName;
11267                // Dont allow ephemeral apps to define new permission groups.
11268                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11269                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11270                            + pg.info.packageName
11271                            + " ignored: instant apps cannot define new permission groups.");
11272                    continue;
11273                }
11274                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11275                if (cur == null || isPackageUpdate) {
11276                    mPermissionGroups.put(pg.info.name, pg);
11277                    if (chatty) {
11278                        if (r == null) {
11279                            r = new StringBuilder(256);
11280                        } else {
11281                            r.append(' ');
11282                        }
11283                        if (isPackageUpdate) {
11284                            r.append("UPD:");
11285                        }
11286                        r.append(pg.info.name);
11287                    }
11288                } else {
11289                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11290                            + pg.info.packageName + " ignored: original from "
11291                            + cur.info.packageName);
11292                    if (chatty) {
11293                        if (r == null) {
11294                            r = new StringBuilder(256);
11295                        } else {
11296                            r.append(' ');
11297                        }
11298                        r.append("DUP:");
11299                        r.append(pg.info.name);
11300                    }
11301                }
11302            }
11303            if (r != null) {
11304                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11305            }
11306
11307            N = pkg.permissions.size();
11308            r = null;
11309            for (i=0; i<N; i++) {
11310                PackageParser.Permission p = pkg.permissions.get(i);
11311
11312                // Dont allow ephemeral apps to define new permissions.
11313                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11314                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11315                            + p.info.packageName
11316                            + " ignored: instant apps cannot define new permissions.");
11317                    continue;
11318                }
11319
11320                // Assume by default that we did not install this permission into the system.
11321                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11322
11323                // Now that permission groups have a special meaning, we ignore permission
11324                // groups for legacy apps to prevent unexpected behavior. In particular,
11325                // permissions for one app being granted to someone just because they happen
11326                // to be in a group defined by another app (before this had no implications).
11327                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11328                    p.group = mPermissionGroups.get(p.info.group);
11329                    // Warn for a permission in an unknown group.
11330                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11331                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11332                                + p.info.packageName + " in an unknown group " + p.info.group);
11333                    }
11334                }
11335
11336                ArrayMap<String, BasePermission> permissionMap =
11337                        p.tree ? mSettings.mPermissionTrees
11338                                : mSettings.mPermissions;
11339                BasePermission bp = permissionMap.get(p.info.name);
11340
11341                // Allow system apps to redefine non-system permissions
11342                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11343                    final boolean currentOwnerIsSystem = (bp.perm != null
11344                            && isSystemApp(bp.perm.owner));
11345                    if (isSystemApp(p.owner)) {
11346                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11347                            // It's a built-in permission and no owner, take ownership now
11348                            bp.packageSetting = pkgSetting;
11349                            bp.perm = p;
11350                            bp.uid = pkg.applicationInfo.uid;
11351                            bp.sourcePackage = p.info.packageName;
11352                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11353                        } else if (!currentOwnerIsSystem) {
11354                            String msg = "New decl " + p.owner + " of permission  "
11355                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
11356                            reportSettingsProblem(Log.WARN, msg);
11357                            bp = null;
11358                        }
11359                    }
11360                }
11361
11362                if (bp == null) {
11363                    bp = new BasePermission(p.info.name, p.info.packageName,
11364                            BasePermission.TYPE_NORMAL);
11365                    permissionMap.put(p.info.name, bp);
11366                }
11367
11368                if (bp.perm == null) {
11369                    if (bp.sourcePackage == null
11370                            || bp.sourcePackage.equals(p.info.packageName)) {
11371                        BasePermission tree = findPermissionTreeLP(p.info.name);
11372                        if (tree == null
11373                                || tree.sourcePackage.equals(p.info.packageName)) {
11374                            bp.packageSetting = pkgSetting;
11375                            bp.perm = p;
11376                            bp.uid = pkg.applicationInfo.uid;
11377                            bp.sourcePackage = p.info.packageName;
11378                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11379                            if (chatty) {
11380                                if (r == null) {
11381                                    r = new StringBuilder(256);
11382                                } else {
11383                                    r.append(' ');
11384                                }
11385                                r.append(p.info.name);
11386                            }
11387                        } else {
11388                            Slog.w(TAG, "Permission " + p.info.name + " from package "
11389                                    + p.info.packageName + " ignored: base tree "
11390                                    + tree.name + " is from package "
11391                                    + tree.sourcePackage);
11392                        }
11393                    } else {
11394                        Slog.w(TAG, "Permission " + p.info.name + " from package "
11395                                + p.info.packageName + " ignored: original from "
11396                                + bp.sourcePackage);
11397                    }
11398                } else if (chatty) {
11399                    if (r == null) {
11400                        r = new StringBuilder(256);
11401                    } else {
11402                        r.append(' ');
11403                    }
11404                    r.append("DUP:");
11405                    r.append(p.info.name);
11406                }
11407                if (bp.perm == p) {
11408                    bp.protectionLevel = p.info.protectionLevel;
11409                }
11410            }
11411
11412            if (r != null) {
11413                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
11414            }
11415
11416            N = pkg.instrumentation.size();
11417            r = null;
11418            for (i=0; i<N; i++) {
11419                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11420                a.info.packageName = pkg.applicationInfo.packageName;
11421                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11422                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11423                a.info.splitNames = pkg.splitNames;
11424                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11425                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11426                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11427                a.info.dataDir = pkg.applicationInfo.dataDir;
11428                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11429                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11430                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11431                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11432                mInstrumentation.put(a.getComponentName(), a);
11433                if (chatty) {
11434                    if (r == null) {
11435                        r = new StringBuilder(256);
11436                    } else {
11437                        r.append(' ');
11438                    }
11439                    r.append(a.info.name);
11440                }
11441            }
11442            if (r != null) {
11443                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11444            }
11445
11446            if (pkg.protectedBroadcasts != null) {
11447                N = pkg.protectedBroadcasts.size();
11448                synchronized (mProtectedBroadcasts) {
11449                    for (i = 0; i < N; i++) {
11450                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11451                    }
11452                }
11453            }
11454        }
11455
11456        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11457    }
11458
11459    /**
11460     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11461     * is derived purely on the basis of the contents of {@code scanFile} and
11462     * {@code cpuAbiOverride}.
11463     *
11464     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11465     */
11466    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11467                                 String cpuAbiOverride, boolean extractLibs,
11468                                 File appLib32InstallDir)
11469            throws PackageManagerException {
11470        // Give ourselves some initial paths; we'll come back for another
11471        // pass once we've determined ABI below.
11472        setNativeLibraryPaths(pkg, appLib32InstallDir);
11473
11474        // We would never need to extract libs for forward-locked and external packages,
11475        // since the container service will do it for us. We shouldn't attempt to
11476        // extract libs from system app when it was not updated.
11477        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11478                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11479            extractLibs = false;
11480        }
11481
11482        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11483        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11484
11485        NativeLibraryHelper.Handle handle = null;
11486        try {
11487            handle = NativeLibraryHelper.Handle.create(pkg);
11488            // TODO(multiArch): This can be null for apps that didn't go through the
11489            // usual installation process. We can calculate it again, like we
11490            // do during install time.
11491            //
11492            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11493            // unnecessary.
11494            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11495
11496            // Null out the abis so that they can be recalculated.
11497            pkg.applicationInfo.primaryCpuAbi = null;
11498            pkg.applicationInfo.secondaryCpuAbi = null;
11499            if (isMultiArch(pkg.applicationInfo)) {
11500                // Warn if we've set an abiOverride for multi-lib packages..
11501                // By definition, we need to copy both 32 and 64 bit libraries for
11502                // such packages.
11503                if (pkg.cpuAbiOverride != null
11504                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11505                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11506                }
11507
11508                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11509                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11510                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11511                    if (extractLibs) {
11512                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11513                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11514                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11515                                useIsaSpecificSubdirs);
11516                    } else {
11517                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11518                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11519                    }
11520                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11521                }
11522
11523                maybeThrowExceptionForMultiArchCopy(
11524                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11525
11526                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11527                    if (extractLibs) {
11528                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11529                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11530                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11531                                useIsaSpecificSubdirs);
11532                    } else {
11533                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11534                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11535                    }
11536                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11537                }
11538
11539                maybeThrowExceptionForMultiArchCopy(
11540                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11541
11542                if (abi64 >= 0) {
11543                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11544                }
11545
11546                if (abi32 >= 0) {
11547                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11548                    if (abi64 >= 0) {
11549                        if (pkg.use32bitAbi) {
11550                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11551                            pkg.applicationInfo.primaryCpuAbi = abi;
11552                        } else {
11553                            pkg.applicationInfo.secondaryCpuAbi = abi;
11554                        }
11555                    } else {
11556                        pkg.applicationInfo.primaryCpuAbi = abi;
11557                    }
11558                }
11559
11560            } else {
11561                String[] abiList = (cpuAbiOverride != null) ?
11562                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11563
11564                // Enable gross and lame hacks for apps that are built with old
11565                // SDK tools. We must scan their APKs for renderscript bitcode and
11566                // not launch them if it's present. Don't bother checking on devices
11567                // that don't have 64 bit support.
11568                boolean needsRenderScriptOverride = false;
11569                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11570                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11571                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11572                    needsRenderScriptOverride = true;
11573                }
11574
11575                final int copyRet;
11576                if (extractLibs) {
11577                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11578                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11579                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11580                } else {
11581                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11582                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11583                }
11584                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11585
11586                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11587                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11588                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11589                }
11590
11591                if (copyRet >= 0) {
11592                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11593                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11594                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11595                } else if (needsRenderScriptOverride) {
11596                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11597                }
11598            }
11599        } catch (IOException ioe) {
11600            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11601        } finally {
11602            IoUtils.closeQuietly(handle);
11603        }
11604
11605        // Now that we've calculated the ABIs and determined if it's an internal app,
11606        // we will go ahead and populate the nativeLibraryPath.
11607        setNativeLibraryPaths(pkg, appLib32InstallDir);
11608    }
11609
11610    /**
11611     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11612     * i.e, so that all packages can be run inside a single process if required.
11613     *
11614     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11615     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11616     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11617     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11618     * updating a package that belongs to a shared user.
11619     *
11620     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11621     * adds unnecessary complexity.
11622     */
11623    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
11624            PackageParser.Package scannedPackage) {
11625        String requiredInstructionSet = null;
11626        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11627            requiredInstructionSet = VMRuntime.getInstructionSet(
11628                     scannedPackage.applicationInfo.primaryCpuAbi);
11629        }
11630
11631        PackageSetting requirer = null;
11632        for (PackageSetting ps : packagesForUser) {
11633            // If packagesForUser contains scannedPackage, we skip it. This will happen
11634            // when scannedPackage is an update of an existing package. Without this check,
11635            // we will never be able to change the ABI of any package belonging to a shared
11636            // user, even if it's compatible with other packages.
11637            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11638                if (ps.primaryCpuAbiString == null) {
11639                    continue;
11640                }
11641
11642                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11643                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11644                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11645                    // this but there's not much we can do.
11646                    String errorMessage = "Instruction set mismatch, "
11647                            + ((requirer == null) ? "[caller]" : requirer)
11648                            + " requires " + requiredInstructionSet + " whereas " + ps
11649                            + " requires " + instructionSet;
11650                    Slog.w(TAG, errorMessage);
11651                }
11652
11653                if (requiredInstructionSet == null) {
11654                    requiredInstructionSet = instructionSet;
11655                    requirer = ps;
11656                }
11657            }
11658        }
11659
11660        if (requiredInstructionSet != null) {
11661            String adjustedAbi;
11662            if (requirer != null) {
11663                // requirer != null implies that either scannedPackage was null or that scannedPackage
11664                // did not require an ABI, in which case we have to adjust scannedPackage to match
11665                // the ABI of the set (which is the same as requirer's ABI)
11666                adjustedAbi = requirer.primaryCpuAbiString;
11667                if (scannedPackage != null) {
11668                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11669                }
11670            } else {
11671                // requirer == null implies that we're updating all ABIs in the set to
11672                // match scannedPackage.
11673                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11674            }
11675
11676            for (PackageSetting ps : packagesForUser) {
11677                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11678                    if (ps.primaryCpuAbiString != null) {
11679                        continue;
11680                    }
11681
11682                    ps.primaryCpuAbiString = adjustedAbi;
11683                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11684                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11685                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11686                        if (DEBUG_ABI_SELECTION) {
11687                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11688                                    + " (requirer="
11689                                    + (requirer != null ? requirer.pkg : "null")
11690                                    + ", scannedPackage="
11691                                    + (scannedPackage != null ? scannedPackage : "null")
11692                                    + ")");
11693                        }
11694                        try {
11695                            mInstaller.rmdex(ps.codePathString,
11696                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
11697                        } catch (InstallerException ignored) {
11698                        }
11699                    }
11700                }
11701            }
11702        }
11703    }
11704
11705    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11706        synchronized (mPackages) {
11707            mResolverReplaced = true;
11708            // Set up information for custom user intent resolution activity.
11709            mResolveActivity.applicationInfo = pkg.applicationInfo;
11710            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11711            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11712            mResolveActivity.processName = pkg.applicationInfo.packageName;
11713            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11714            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11715                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11716            mResolveActivity.theme = 0;
11717            mResolveActivity.exported = true;
11718            mResolveActivity.enabled = true;
11719            mResolveInfo.activityInfo = mResolveActivity;
11720            mResolveInfo.priority = 0;
11721            mResolveInfo.preferredOrder = 0;
11722            mResolveInfo.match = 0;
11723            mResolveComponentName = mCustomResolverComponentName;
11724            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11725                    mResolveComponentName);
11726        }
11727    }
11728
11729    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11730        if (installerActivity == null) {
11731            if (DEBUG_EPHEMERAL) {
11732                Slog.d(TAG, "Clear ephemeral installer activity");
11733            }
11734            mInstantAppInstallerActivity = null;
11735            return;
11736        }
11737
11738        if (DEBUG_EPHEMERAL) {
11739            Slog.d(TAG, "Set ephemeral installer activity: "
11740                    + installerActivity.getComponentName());
11741        }
11742        // Set up information for ephemeral installer activity
11743        mInstantAppInstallerActivity = installerActivity;
11744        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11745                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11746        mInstantAppInstallerActivity.exported = true;
11747        mInstantAppInstallerActivity.enabled = true;
11748        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11749        mInstantAppInstallerInfo.priority = 0;
11750        mInstantAppInstallerInfo.preferredOrder = 1;
11751        mInstantAppInstallerInfo.isDefault = true;
11752        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11753                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11754    }
11755
11756    private static String calculateBundledApkRoot(final String codePathString) {
11757        final File codePath = new File(codePathString);
11758        final File codeRoot;
11759        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11760            codeRoot = Environment.getRootDirectory();
11761        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11762            codeRoot = Environment.getOemDirectory();
11763        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11764            codeRoot = Environment.getVendorDirectory();
11765        } else {
11766            // Unrecognized code path; take its top real segment as the apk root:
11767            // e.g. /something/app/blah.apk => /something
11768            try {
11769                File f = codePath.getCanonicalFile();
11770                File parent = f.getParentFile();    // non-null because codePath is a file
11771                File tmp;
11772                while ((tmp = parent.getParentFile()) != null) {
11773                    f = parent;
11774                    parent = tmp;
11775                }
11776                codeRoot = f;
11777                Slog.w(TAG, "Unrecognized code path "
11778                        + codePath + " - using " + codeRoot);
11779            } catch (IOException e) {
11780                // Can't canonicalize the code path -- shenanigans?
11781                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11782                return Environment.getRootDirectory().getPath();
11783            }
11784        }
11785        return codeRoot.getPath();
11786    }
11787
11788    /**
11789     * Derive and set the location of native libraries for the given package,
11790     * which varies depending on where and how the package was installed.
11791     */
11792    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11793        final ApplicationInfo info = pkg.applicationInfo;
11794        final String codePath = pkg.codePath;
11795        final File codeFile = new File(codePath);
11796        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11797        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11798
11799        info.nativeLibraryRootDir = null;
11800        info.nativeLibraryRootRequiresIsa = false;
11801        info.nativeLibraryDir = null;
11802        info.secondaryNativeLibraryDir = null;
11803
11804        if (isApkFile(codeFile)) {
11805            // Monolithic install
11806            if (bundledApp) {
11807                // If "/system/lib64/apkname" exists, assume that is the per-package
11808                // native library directory to use; otherwise use "/system/lib/apkname".
11809                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11810                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11811                        getPrimaryInstructionSet(info));
11812
11813                // This is a bundled system app so choose the path based on the ABI.
11814                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11815                // is just the default path.
11816                final String apkName = deriveCodePathName(codePath);
11817                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11818                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11819                        apkName).getAbsolutePath();
11820
11821                if (info.secondaryCpuAbi != null) {
11822                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11823                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11824                            secondaryLibDir, apkName).getAbsolutePath();
11825                }
11826            } else if (asecApp) {
11827                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11828                        .getAbsolutePath();
11829            } else {
11830                final String apkName = deriveCodePathName(codePath);
11831                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11832                        .getAbsolutePath();
11833            }
11834
11835            info.nativeLibraryRootRequiresIsa = false;
11836            info.nativeLibraryDir = info.nativeLibraryRootDir;
11837        } else {
11838            // Cluster install
11839            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11840            info.nativeLibraryRootRequiresIsa = true;
11841
11842            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11843                    getPrimaryInstructionSet(info)).getAbsolutePath();
11844
11845            if (info.secondaryCpuAbi != null) {
11846                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11847                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11848            }
11849        }
11850    }
11851
11852    /**
11853     * Calculate the abis and roots for a bundled app. These can uniquely
11854     * be determined from the contents of the system partition, i.e whether
11855     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11856     * of this information, and instead assume that the system was built
11857     * sensibly.
11858     */
11859    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11860                                           PackageSetting pkgSetting) {
11861        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11862
11863        // If "/system/lib64/apkname" exists, assume that is the per-package
11864        // native library directory to use; otherwise use "/system/lib/apkname".
11865        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11866        setBundledAppAbi(pkg, apkRoot, apkName);
11867        // pkgSetting might be null during rescan following uninstall of updates
11868        // to a bundled app, so accommodate that possibility.  The settings in
11869        // that case will be established later from the parsed package.
11870        //
11871        // If the settings aren't null, sync them up with what we've just derived.
11872        // note that apkRoot isn't stored in the package settings.
11873        if (pkgSetting != null) {
11874            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11875            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11876        }
11877    }
11878
11879    /**
11880     * Deduces the ABI of a bundled app and sets the relevant fields on the
11881     * parsed pkg object.
11882     *
11883     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11884     *        under which system libraries are installed.
11885     * @param apkName the name of the installed package.
11886     */
11887    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11888        final File codeFile = new File(pkg.codePath);
11889
11890        final boolean has64BitLibs;
11891        final boolean has32BitLibs;
11892        if (isApkFile(codeFile)) {
11893            // Monolithic install
11894            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11895            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11896        } else {
11897            // Cluster install
11898            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11899            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11900                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11901                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11902                has64BitLibs = (new File(rootDir, isa)).exists();
11903            } else {
11904                has64BitLibs = false;
11905            }
11906            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11907                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11908                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11909                has32BitLibs = (new File(rootDir, isa)).exists();
11910            } else {
11911                has32BitLibs = false;
11912            }
11913        }
11914
11915        if (has64BitLibs && !has32BitLibs) {
11916            // The package has 64 bit libs, but not 32 bit libs. Its primary
11917            // ABI should be 64 bit. We can safely assume here that the bundled
11918            // native libraries correspond to the most preferred ABI in the list.
11919
11920            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11921            pkg.applicationInfo.secondaryCpuAbi = null;
11922        } else if (has32BitLibs && !has64BitLibs) {
11923            // The package has 32 bit libs but not 64 bit libs. Its primary
11924            // ABI should be 32 bit.
11925
11926            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11927            pkg.applicationInfo.secondaryCpuAbi = null;
11928        } else if (has32BitLibs && has64BitLibs) {
11929            // The application has both 64 and 32 bit bundled libraries. We check
11930            // here that the app declares multiArch support, and warn if it doesn't.
11931            //
11932            // We will be lenient here and record both ABIs. The primary will be the
11933            // ABI that's higher on the list, i.e, a device that's configured to prefer
11934            // 64 bit apps will see a 64 bit primary ABI,
11935
11936            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11937                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11938            }
11939
11940            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11941                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11942                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11943            } else {
11944                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11945                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11946            }
11947        } else {
11948            pkg.applicationInfo.primaryCpuAbi = null;
11949            pkg.applicationInfo.secondaryCpuAbi = null;
11950        }
11951    }
11952
11953    private void killApplication(String pkgName, int appId, String reason) {
11954        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11955    }
11956
11957    private void killApplication(String pkgName, int appId, int userId, String reason) {
11958        // Request the ActivityManager to kill the process(only for existing packages)
11959        // so that we do not end up in a confused state while the user is still using the older
11960        // version of the application while the new one gets installed.
11961        final long token = Binder.clearCallingIdentity();
11962        try {
11963            IActivityManager am = ActivityManager.getService();
11964            if (am != null) {
11965                try {
11966                    am.killApplication(pkgName, appId, userId, reason);
11967                } catch (RemoteException e) {
11968                }
11969            }
11970        } finally {
11971            Binder.restoreCallingIdentity(token);
11972        }
11973    }
11974
11975    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
11976        // Remove the parent package setting
11977        PackageSetting ps = (PackageSetting) pkg.mExtras;
11978        if (ps != null) {
11979            removePackageLI(ps, chatty);
11980        }
11981        // Remove the child package setting
11982        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11983        for (int i = 0; i < childCount; i++) {
11984            PackageParser.Package childPkg = pkg.childPackages.get(i);
11985            ps = (PackageSetting) childPkg.mExtras;
11986            if (ps != null) {
11987                removePackageLI(ps, chatty);
11988            }
11989        }
11990    }
11991
11992    void removePackageLI(PackageSetting ps, boolean chatty) {
11993        if (DEBUG_INSTALL) {
11994            if (chatty)
11995                Log.d(TAG, "Removing package " + ps.name);
11996        }
11997
11998        // writer
11999        synchronized (mPackages) {
12000            mPackages.remove(ps.name);
12001            final PackageParser.Package pkg = ps.pkg;
12002            if (pkg != null) {
12003                cleanPackageDataStructuresLILPw(pkg, chatty);
12004            }
12005        }
12006    }
12007
12008    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12009        if (DEBUG_INSTALL) {
12010            if (chatty)
12011                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12012        }
12013
12014        // writer
12015        synchronized (mPackages) {
12016            // Remove the parent package
12017            mPackages.remove(pkg.applicationInfo.packageName);
12018            cleanPackageDataStructuresLILPw(pkg, chatty);
12019
12020            // Remove the child packages
12021            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12022            for (int i = 0; i < childCount; i++) {
12023                PackageParser.Package childPkg = pkg.childPackages.get(i);
12024                mPackages.remove(childPkg.applicationInfo.packageName);
12025                cleanPackageDataStructuresLILPw(childPkg, chatty);
12026            }
12027        }
12028    }
12029
12030    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12031        int N = pkg.providers.size();
12032        StringBuilder r = null;
12033        int i;
12034        for (i=0; i<N; i++) {
12035            PackageParser.Provider p = pkg.providers.get(i);
12036            mProviders.removeProvider(p);
12037            if (p.info.authority == null) {
12038
12039                /* There was another ContentProvider with this authority when
12040                 * this app was installed so this authority is null,
12041                 * Ignore it as we don't have to unregister the provider.
12042                 */
12043                continue;
12044            }
12045            String names[] = p.info.authority.split(";");
12046            for (int j = 0; j < names.length; j++) {
12047                if (mProvidersByAuthority.get(names[j]) == p) {
12048                    mProvidersByAuthority.remove(names[j]);
12049                    if (DEBUG_REMOVE) {
12050                        if (chatty)
12051                            Log.d(TAG, "Unregistered content provider: " + names[j]
12052                                    + ", className = " + p.info.name + ", isSyncable = "
12053                                    + p.info.isSyncable);
12054                    }
12055                }
12056            }
12057            if (DEBUG_REMOVE && chatty) {
12058                if (r == null) {
12059                    r = new StringBuilder(256);
12060                } else {
12061                    r.append(' ');
12062                }
12063                r.append(p.info.name);
12064            }
12065        }
12066        if (r != null) {
12067            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12068        }
12069
12070        N = pkg.services.size();
12071        r = null;
12072        for (i=0; i<N; i++) {
12073            PackageParser.Service s = pkg.services.get(i);
12074            mServices.removeService(s);
12075            if (chatty) {
12076                if (r == null) {
12077                    r = new StringBuilder(256);
12078                } else {
12079                    r.append(' ');
12080                }
12081                r.append(s.info.name);
12082            }
12083        }
12084        if (r != null) {
12085            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12086        }
12087
12088        N = pkg.receivers.size();
12089        r = null;
12090        for (i=0; i<N; i++) {
12091            PackageParser.Activity a = pkg.receivers.get(i);
12092            mReceivers.removeActivity(a, "receiver");
12093            if (DEBUG_REMOVE && chatty) {
12094                if (r == null) {
12095                    r = new StringBuilder(256);
12096                } else {
12097                    r.append(' ');
12098                }
12099                r.append(a.info.name);
12100            }
12101        }
12102        if (r != null) {
12103            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12104        }
12105
12106        N = pkg.activities.size();
12107        r = null;
12108        for (i=0; i<N; i++) {
12109            PackageParser.Activity a = pkg.activities.get(i);
12110            mActivities.removeActivity(a, "activity");
12111            if (DEBUG_REMOVE && chatty) {
12112                if (r == null) {
12113                    r = new StringBuilder(256);
12114                } else {
12115                    r.append(' ');
12116                }
12117                r.append(a.info.name);
12118            }
12119        }
12120        if (r != null) {
12121            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12122        }
12123
12124        N = pkg.permissions.size();
12125        r = null;
12126        for (i=0; i<N; i++) {
12127            PackageParser.Permission p = pkg.permissions.get(i);
12128            BasePermission bp = mSettings.mPermissions.get(p.info.name);
12129            if (bp == null) {
12130                bp = mSettings.mPermissionTrees.get(p.info.name);
12131            }
12132            if (bp != null && bp.perm == p) {
12133                bp.perm = null;
12134                if (DEBUG_REMOVE && chatty) {
12135                    if (r == null) {
12136                        r = new StringBuilder(256);
12137                    } else {
12138                        r.append(' ');
12139                    }
12140                    r.append(p.info.name);
12141                }
12142            }
12143            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12144                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12145                if (appOpPkgs != null) {
12146                    appOpPkgs.remove(pkg.packageName);
12147                }
12148            }
12149        }
12150        if (r != null) {
12151            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12152        }
12153
12154        N = pkg.requestedPermissions.size();
12155        r = null;
12156        for (i=0; i<N; i++) {
12157            String perm = pkg.requestedPermissions.get(i);
12158            BasePermission bp = mSettings.mPermissions.get(perm);
12159            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12160                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12161                if (appOpPkgs != null) {
12162                    appOpPkgs.remove(pkg.packageName);
12163                    if (appOpPkgs.isEmpty()) {
12164                        mAppOpPermissionPackages.remove(perm);
12165                    }
12166                }
12167            }
12168        }
12169        if (r != null) {
12170            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12171        }
12172
12173        N = pkg.instrumentation.size();
12174        r = null;
12175        for (i=0; i<N; i++) {
12176            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12177            mInstrumentation.remove(a.getComponentName());
12178            if (DEBUG_REMOVE && chatty) {
12179                if (r == null) {
12180                    r = new StringBuilder(256);
12181                } else {
12182                    r.append(' ');
12183                }
12184                r.append(a.info.name);
12185            }
12186        }
12187        if (r != null) {
12188            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12189        }
12190
12191        r = null;
12192        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12193            // Only system apps can hold shared libraries.
12194            if (pkg.libraryNames != null) {
12195                for (i = 0; i < pkg.libraryNames.size(); i++) {
12196                    String name = pkg.libraryNames.get(i);
12197                    if (removeSharedLibraryLPw(name, 0)) {
12198                        if (DEBUG_REMOVE && chatty) {
12199                            if (r == null) {
12200                                r = new StringBuilder(256);
12201                            } else {
12202                                r.append(' ');
12203                            }
12204                            r.append(name);
12205                        }
12206                    }
12207                }
12208            }
12209        }
12210
12211        r = null;
12212
12213        // Any package can hold static shared libraries.
12214        if (pkg.staticSharedLibName != null) {
12215            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12216                if (DEBUG_REMOVE && chatty) {
12217                    if (r == null) {
12218                        r = new StringBuilder(256);
12219                    } else {
12220                        r.append(' ');
12221                    }
12222                    r.append(pkg.staticSharedLibName);
12223                }
12224            }
12225        }
12226
12227        if (r != null) {
12228            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12229        }
12230    }
12231
12232    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12233        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12234            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12235                return true;
12236            }
12237        }
12238        return false;
12239    }
12240
12241    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12242    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12243    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12244
12245    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12246        // Update the parent permissions
12247        updatePermissionsLPw(pkg.packageName, pkg, flags);
12248        // Update the child permissions
12249        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12250        for (int i = 0; i < childCount; i++) {
12251            PackageParser.Package childPkg = pkg.childPackages.get(i);
12252            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12253        }
12254    }
12255
12256    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12257            int flags) {
12258        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12259        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12260    }
12261
12262    private void updatePermissionsLPw(String changingPkg,
12263            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12264        // Make sure there are no dangling permission trees.
12265        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12266        while (it.hasNext()) {
12267            final BasePermission bp = it.next();
12268            if (bp.packageSetting == null) {
12269                // We may not yet have parsed the package, so just see if
12270                // we still know about its settings.
12271                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12272            }
12273            if (bp.packageSetting == null) {
12274                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12275                        + " from package " + bp.sourcePackage);
12276                it.remove();
12277            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12278                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12279                    Slog.i(TAG, "Removing old permission tree: " + bp.name
12280                            + " from package " + bp.sourcePackage);
12281                    flags |= UPDATE_PERMISSIONS_ALL;
12282                    it.remove();
12283                }
12284            }
12285        }
12286
12287        // Make sure all dynamic permissions have been assigned to a package,
12288        // and make sure there are no dangling permissions.
12289        it = mSettings.mPermissions.values().iterator();
12290        while (it.hasNext()) {
12291            final BasePermission bp = it.next();
12292            if (bp.type == BasePermission.TYPE_DYNAMIC) {
12293                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12294                        + bp.name + " pkg=" + bp.sourcePackage
12295                        + " info=" + bp.pendingInfo);
12296                if (bp.packageSetting == null && bp.pendingInfo != null) {
12297                    final BasePermission tree = findPermissionTreeLP(bp.name);
12298                    if (tree != null && tree.perm != null) {
12299                        bp.packageSetting = tree.packageSetting;
12300                        bp.perm = new PackageParser.Permission(tree.perm.owner,
12301                                new PermissionInfo(bp.pendingInfo));
12302                        bp.perm.info.packageName = tree.perm.info.packageName;
12303                        bp.perm.info.name = bp.name;
12304                        bp.uid = tree.uid;
12305                    }
12306                }
12307            }
12308            if (bp.packageSetting == null) {
12309                // We may not yet have parsed the package, so just see if
12310                // we still know about its settings.
12311                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12312            }
12313            if (bp.packageSetting == null) {
12314                Slog.w(TAG, "Removing dangling permission: " + bp.name
12315                        + " from package " + bp.sourcePackage);
12316                it.remove();
12317            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12318                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12319                    Slog.i(TAG, "Removing old permission: " + bp.name
12320                            + " from package " + bp.sourcePackage);
12321                    flags |= UPDATE_PERMISSIONS_ALL;
12322                    it.remove();
12323                }
12324            }
12325        }
12326
12327        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12328        // Now update the permissions for all packages, in particular
12329        // replace the granted permissions of the system packages.
12330        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12331            for (PackageParser.Package pkg : mPackages.values()) {
12332                if (pkg != pkgInfo) {
12333                    // Only replace for packages on requested volume
12334                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12335                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12336                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12337                    grantPermissionsLPw(pkg, replace, changingPkg);
12338                }
12339            }
12340        }
12341
12342        if (pkgInfo != null) {
12343            // Only replace for packages on requested volume
12344            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12345            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12346                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12347            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12348        }
12349        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12350    }
12351
12352    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12353            String packageOfInterest) {
12354        // IMPORTANT: There are two types of permissions: install and runtime.
12355        // Install time permissions are granted when the app is installed to
12356        // all device users and users added in the future. Runtime permissions
12357        // are granted at runtime explicitly to specific users. Normal and signature
12358        // protected permissions are install time permissions. Dangerous permissions
12359        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12360        // otherwise they are runtime permissions. This function does not manage
12361        // runtime permissions except for the case an app targeting Lollipop MR1
12362        // being upgraded to target a newer SDK, in which case dangerous permissions
12363        // are transformed from install time to runtime ones.
12364
12365        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12366        if (ps == null) {
12367            return;
12368        }
12369
12370        PermissionsState permissionsState = ps.getPermissionsState();
12371        PermissionsState origPermissions = permissionsState;
12372
12373        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12374
12375        boolean runtimePermissionsRevoked = false;
12376        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12377
12378        boolean changedInstallPermission = false;
12379
12380        if (replace) {
12381            ps.installPermissionsFixed = false;
12382            if (!ps.isSharedUser()) {
12383                origPermissions = new PermissionsState(permissionsState);
12384                permissionsState.reset();
12385            } else {
12386                // We need to know only about runtime permission changes since the
12387                // calling code always writes the install permissions state but
12388                // the runtime ones are written only if changed. The only cases of
12389                // changed runtime permissions here are promotion of an install to
12390                // runtime and revocation of a runtime from a shared user.
12391                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12392                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
12393                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12394                    runtimePermissionsRevoked = true;
12395                }
12396            }
12397        }
12398
12399        permissionsState.setGlobalGids(mGlobalGids);
12400
12401        final int N = pkg.requestedPermissions.size();
12402        for (int i=0; i<N; i++) {
12403            final String name = pkg.requestedPermissions.get(i);
12404            final BasePermission bp = mSettings.mPermissions.get(name);
12405            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12406                    >= Build.VERSION_CODES.M;
12407
12408            if (DEBUG_INSTALL) {
12409                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12410            }
12411
12412            if (bp == null || bp.packageSetting == null) {
12413                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12414                    if (DEBUG_PERMISSIONS) {
12415                        Slog.i(TAG, "Unknown permission " + name
12416                                + " in package " + pkg.packageName);
12417                    }
12418                }
12419                continue;
12420            }
12421
12422
12423            // Limit ephemeral apps to ephemeral allowed permissions.
12424            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12425                if (DEBUG_PERMISSIONS) {
12426                    Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
12427                            + pkg.packageName);
12428                }
12429                continue;
12430            }
12431
12432            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12433                if (DEBUG_PERMISSIONS) {
12434                    Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
12435                            + pkg.packageName);
12436                }
12437                continue;
12438            }
12439
12440            final String perm = bp.name;
12441            boolean allowedSig = false;
12442            int grant = GRANT_DENIED;
12443
12444            // Keep track of app op permissions.
12445            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12446                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
12447                if (pkgs == null) {
12448                    pkgs = new ArraySet<>();
12449                    mAppOpPermissionPackages.put(bp.name, pkgs);
12450                }
12451                pkgs.add(pkg.packageName);
12452            }
12453
12454            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
12455            switch (level) {
12456                case PermissionInfo.PROTECTION_NORMAL: {
12457                    // For all apps normal permissions are install time ones.
12458                    grant = GRANT_INSTALL;
12459                } break;
12460
12461                case PermissionInfo.PROTECTION_DANGEROUS: {
12462                    // If a permission review is required for legacy apps we represent
12463                    // their permissions as always granted runtime ones since we need
12464                    // to keep the review required permission flag per user while an
12465                    // install permission's state is shared across all users.
12466                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12467                        // For legacy apps dangerous permissions are install time ones.
12468                        grant = GRANT_INSTALL;
12469                    } else if (origPermissions.hasInstallPermission(bp.name)) {
12470                        // For legacy apps that became modern, install becomes runtime.
12471                        grant = GRANT_UPGRADE;
12472                    } else if (mPromoteSystemApps
12473                            && isSystemApp(ps)
12474                            && mExistingSystemPackages.contains(ps.name)) {
12475                        // For legacy system apps, install becomes runtime.
12476                        // We cannot check hasInstallPermission() for system apps since those
12477                        // permissions were granted implicitly and not persisted pre-M.
12478                        grant = GRANT_UPGRADE;
12479                    } else {
12480                        // For modern apps keep runtime permissions unchanged.
12481                        grant = GRANT_RUNTIME;
12482                    }
12483                } break;
12484
12485                case PermissionInfo.PROTECTION_SIGNATURE: {
12486                    // For all apps signature permissions are install time ones.
12487                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
12488                    if (allowedSig) {
12489                        grant = GRANT_INSTALL;
12490                    }
12491                } break;
12492            }
12493
12494            if (DEBUG_PERMISSIONS) {
12495                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
12496            }
12497
12498            if (grant != GRANT_DENIED) {
12499                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
12500                    // If this is an existing, non-system package, then
12501                    // we can't add any new permissions to it.
12502                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
12503                        // Except...  if this is a permission that was added
12504                        // to the platform (note: need to only do this when
12505                        // updating the platform).
12506                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
12507                            grant = GRANT_DENIED;
12508                        }
12509                    }
12510                }
12511
12512                switch (grant) {
12513                    case GRANT_INSTALL: {
12514                        // Revoke this as runtime permission to handle the case of
12515                        // a runtime permission being downgraded to an install one.
12516                        // Also in permission review mode we keep dangerous permissions
12517                        // for legacy apps
12518                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12519                            if (origPermissions.getRuntimePermissionState(
12520                                    bp.name, userId) != null) {
12521                                // Revoke the runtime permission and clear the flags.
12522                                origPermissions.revokeRuntimePermission(bp, userId);
12523                                origPermissions.updatePermissionFlags(bp, userId,
12524                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
12525                                // If we revoked a permission permission, we have to write.
12526                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12527                                        changedRuntimePermissionUserIds, userId);
12528                            }
12529                        }
12530                        // Grant an install permission.
12531                        if (permissionsState.grantInstallPermission(bp) !=
12532                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
12533                            changedInstallPermission = true;
12534                        }
12535                    } break;
12536
12537                    case GRANT_RUNTIME: {
12538                        // Grant previously granted runtime permissions.
12539                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12540                            PermissionState permissionState = origPermissions
12541                                    .getRuntimePermissionState(bp.name, userId);
12542                            int flags = permissionState != null
12543                                    ? permissionState.getFlags() : 0;
12544                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
12545                                // Don't propagate the permission in a permission review mode if
12546                                // the former was revoked, i.e. marked to not propagate on upgrade.
12547                                // Note that in a permission review mode install permissions are
12548                                // represented as constantly granted runtime ones since we need to
12549                                // keep a per user state associated with the permission. Also the
12550                                // revoke on upgrade flag is no longer applicable and is reset.
12551                                final boolean revokeOnUpgrade = (flags & PackageManager
12552                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
12553                                if (revokeOnUpgrade) {
12554                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12555                                    // Since we changed the flags, we have to write.
12556                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12557                                            changedRuntimePermissionUserIds, userId);
12558                                }
12559                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
12560                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
12561                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
12562                                        // If we cannot put the permission as it was,
12563                                        // we have to write.
12564                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12565                                                changedRuntimePermissionUserIds, userId);
12566                                    }
12567                                }
12568
12569                                // If the app supports runtime permissions no need for a review.
12570                                if (mPermissionReviewRequired
12571                                        && appSupportsRuntimePermissions
12572                                        && (flags & PackageManager
12573                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
12574                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
12575                                    // Since we changed the flags, we have to write.
12576                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12577                                            changedRuntimePermissionUserIds, userId);
12578                                }
12579                            } else if (mPermissionReviewRequired
12580                                    && !appSupportsRuntimePermissions) {
12581                                // For legacy apps that need a permission review, every new
12582                                // runtime permission is granted but it is pending a review.
12583                                // We also need to review only platform defined runtime
12584                                // permissions as these are the only ones the platform knows
12585                                // how to disable the API to simulate revocation as legacy
12586                                // apps don't expect to run with revoked permissions.
12587                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
12588                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
12589                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
12590                                        // We changed the flags, hence have to write.
12591                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12592                                                changedRuntimePermissionUserIds, userId);
12593                                    }
12594                                }
12595                                if (permissionsState.grantRuntimePermission(bp, userId)
12596                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12597                                    // We changed the permission, hence have to write.
12598                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12599                                            changedRuntimePermissionUserIds, userId);
12600                                }
12601                            }
12602                            // Propagate the permission flags.
12603                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
12604                        }
12605                    } break;
12606
12607                    case GRANT_UPGRADE: {
12608                        // Grant runtime permissions for a previously held install permission.
12609                        PermissionState permissionState = origPermissions
12610                                .getInstallPermissionState(bp.name);
12611                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
12612
12613                        if (origPermissions.revokeInstallPermission(bp)
12614                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12615                            // We will be transferring the permission flags, so clear them.
12616                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
12617                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
12618                            changedInstallPermission = true;
12619                        }
12620
12621                        // If the permission is not to be promoted to runtime we ignore it and
12622                        // also its other flags as they are not applicable to install permissions.
12623                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
12624                            for (int userId : currentUserIds) {
12625                                if (permissionsState.grantRuntimePermission(bp, userId) !=
12626                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12627                                    // Transfer the permission flags.
12628                                    permissionsState.updatePermissionFlags(bp, userId,
12629                                            flags, flags);
12630                                    // If we granted the permission, we have to write.
12631                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12632                                            changedRuntimePermissionUserIds, userId);
12633                                }
12634                            }
12635                        }
12636                    } break;
12637
12638                    default: {
12639                        if (packageOfInterest == null
12640                                || packageOfInterest.equals(pkg.packageName)) {
12641                            if (DEBUG_PERMISSIONS) {
12642                                Slog.i(TAG, "Not granting permission " + perm
12643                                        + " to package " + pkg.packageName
12644                                        + " because it was previously installed without");
12645                            }
12646                        }
12647                    } break;
12648                }
12649            } else {
12650                if (permissionsState.revokeInstallPermission(bp) !=
12651                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12652                    // Also drop the permission flags.
12653                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12654                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12655                    changedInstallPermission = true;
12656                    Slog.i(TAG, "Un-granting permission " + perm
12657                            + " from package " + pkg.packageName
12658                            + " (protectionLevel=" + bp.protectionLevel
12659                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12660                            + ")");
12661                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
12662                    // Don't print warning for app op permissions, since it is fine for them
12663                    // not to be granted, there is a UI for the user to decide.
12664                    if (DEBUG_PERMISSIONS
12665                            && (packageOfInterest == null
12666                                    || packageOfInterest.equals(pkg.packageName))) {
12667                        Slog.i(TAG, "Not granting permission " + perm
12668                                + " to package " + pkg.packageName
12669                                + " (protectionLevel=" + bp.protectionLevel
12670                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12671                                + ")");
12672                    }
12673                }
12674            }
12675        }
12676
12677        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
12678                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
12679            // This is the first that we have heard about this package, so the
12680            // permissions we have now selected are fixed until explicitly
12681            // changed.
12682            ps.installPermissionsFixed = true;
12683        }
12684
12685        // Persist the runtime permissions state for users with changes. If permissions
12686        // were revoked because no app in the shared user declares them we have to
12687        // write synchronously to avoid losing runtime permissions state.
12688        for (int userId : changedRuntimePermissionUserIds) {
12689            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
12690        }
12691    }
12692
12693    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
12694        boolean allowed = false;
12695        final int NP = PackageParser.NEW_PERMISSIONS.length;
12696        for (int ip=0; ip<NP; ip++) {
12697            final PackageParser.NewPermissionInfo npi
12698                    = PackageParser.NEW_PERMISSIONS[ip];
12699            if (npi.name.equals(perm)
12700                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
12701                allowed = true;
12702                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
12703                        + pkg.packageName);
12704                break;
12705            }
12706        }
12707        return allowed;
12708    }
12709
12710    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
12711            BasePermission bp, PermissionsState origPermissions) {
12712        boolean privilegedPermission = (bp.protectionLevel
12713                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
12714        boolean privappPermissionsDisable =
12715                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
12716        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
12717        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
12718        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
12719                && !platformPackage && platformPermission) {
12720            ArraySet<String> wlPermissions = SystemConfig.getInstance()
12721                    .getPrivAppPermissions(pkg.packageName);
12722            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
12723            if (!whitelisted) {
12724                Slog.w(TAG, "Privileged permission " + perm + " for package "
12725                        + pkg.packageName + " - not in privapp-permissions whitelist");
12726                // Only report violations for apps on system image
12727                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
12728                    if (mPrivappPermissionsViolations == null) {
12729                        mPrivappPermissionsViolations = new ArraySet<>();
12730                    }
12731                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
12732                }
12733                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
12734                    return false;
12735                }
12736            }
12737        }
12738        boolean allowed = (compareSignatures(
12739                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
12740                        == PackageManager.SIGNATURE_MATCH)
12741                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
12742                        == PackageManager.SIGNATURE_MATCH);
12743        if (!allowed && privilegedPermission) {
12744            if (isSystemApp(pkg)) {
12745                // For updated system applications, a system permission
12746                // is granted only if it had been defined by the original application.
12747                if (pkg.isUpdatedSystemApp()) {
12748                    final PackageSetting sysPs = mSettings
12749                            .getDisabledSystemPkgLPr(pkg.packageName);
12750                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
12751                        // If the original was granted this permission, we take
12752                        // that grant decision as read and propagate it to the
12753                        // update.
12754                        if (sysPs.isPrivileged()) {
12755                            allowed = true;
12756                        }
12757                    } else {
12758                        // The system apk may have been updated with an older
12759                        // version of the one on the data partition, but which
12760                        // granted a new system permission that it didn't have
12761                        // before.  In this case we do want to allow the app to
12762                        // now get the new permission if the ancestral apk is
12763                        // privileged to get it.
12764                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
12765                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
12766                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
12767                                    allowed = true;
12768                                    break;
12769                                }
12770                            }
12771                        }
12772                        // Also if a privileged parent package on the system image or any of
12773                        // its children requested a privileged permission, the updated child
12774                        // packages can also get the permission.
12775                        if (pkg.parentPackage != null) {
12776                            final PackageSetting disabledSysParentPs = mSettings
12777                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
12778                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
12779                                    && disabledSysParentPs.isPrivileged()) {
12780                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
12781                                    allowed = true;
12782                                } else if (disabledSysParentPs.pkg.childPackages != null) {
12783                                    final int count = disabledSysParentPs.pkg.childPackages.size();
12784                                    for (int i = 0; i < count; i++) {
12785                                        PackageParser.Package disabledSysChildPkg =
12786                                                disabledSysParentPs.pkg.childPackages.get(i);
12787                                        if (isPackageRequestingPermission(disabledSysChildPkg,
12788                                                perm)) {
12789                                            allowed = true;
12790                                            break;
12791                                        }
12792                                    }
12793                                }
12794                            }
12795                        }
12796                    }
12797                } else {
12798                    allowed = isPrivilegedApp(pkg);
12799                }
12800            }
12801        }
12802        if (!allowed) {
12803            if (!allowed && (bp.protectionLevel
12804                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
12805                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
12806                // If this was a previously normal/dangerous permission that got moved
12807                // to a system permission as part of the runtime permission redesign, then
12808                // we still want to blindly grant it to old apps.
12809                allowed = true;
12810            }
12811            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
12812                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
12813                // If this permission is to be granted to the system installer and
12814                // this app is an installer, then it gets the permission.
12815                allowed = true;
12816            }
12817            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
12818                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
12819                // If this permission is to be granted to the system verifier and
12820                // this app is a verifier, then it gets the permission.
12821                allowed = true;
12822            }
12823            if (!allowed && (bp.protectionLevel
12824                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
12825                    && isSystemApp(pkg)) {
12826                // Any pre-installed system app is allowed to get this permission.
12827                allowed = true;
12828            }
12829            if (!allowed && (bp.protectionLevel
12830                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
12831                // For development permissions, a development permission
12832                // is granted only if it was already granted.
12833                allowed = origPermissions.hasInstallPermission(perm);
12834            }
12835            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
12836                    && pkg.packageName.equals(mSetupWizardPackage)) {
12837                // If this permission is to be granted to the system setup wizard and
12838                // this app is a setup wizard, then it gets the permission.
12839                allowed = true;
12840            }
12841        }
12842        return allowed;
12843    }
12844
12845    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
12846        final int permCount = pkg.requestedPermissions.size();
12847        for (int j = 0; j < permCount; j++) {
12848            String requestedPermission = pkg.requestedPermissions.get(j);
12849            if (permission.equals(requestedPermission)) {
12850                return true;
12851            }
12852        }
12853        return false;
12854    }
12855
12856    final class ActivityIntentResolver
12857            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12858        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12859                boolean defaultOnly, int userId) {
12860            if (!sUserManager.exists(userId)) return null;
12861            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12862            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12863        }
12864
12865        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12866                int userId) {
12867            if (!sUserManager.exists(userId)) return null;
12868            mFlags = flags;
12869            return super.queryIntent(intent, resolvedType,
12870                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12871                    userId);
12872        }
12873
12874        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12875                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12876            if (!sUserManager.exists(userId)) return null;
12877            if (packageActivities == null) {
12878                return null;
12879            }
12880            mFlags = flags;
12881            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12882            final int N = packageActivities.size();
12883            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12884                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12885
12886            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12887            for (int i = 0; i < N; ++i) {
12888                intentFilters = packageActivities.get(i).intents;
12889                if (intentFilters != null && intentFilters.size() > 0) {
12890                    PackageParser.ActivityIntentInfo[] array =
12891                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12892                    intentFilters.toArray(array);
12893                    listCut.add(array);
12894                }
12895            }
12896            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12897        }
12898
12899        /**
12900         * Finds a privileged activity that matches the specified activity names.
12901         */
12902        private PackageParser.Activity findMatchingActivity(
12903                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12904            for (PackageParser.Activity sysActivity : activityList) {
12905                if (sysActivity.info.name.equals(activityInfo.name)) {
12906                    return sysActivity;
12907                }
12908                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12909                    return sysActivity;
12910                }
12911                if (sysActivity.info.targetActivity != null) {
12912                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12913                        return sysActivity;
12914                    }
12915                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12916                        return sysActivity;
12917                    }
12918                }
12919            }
12920            return null;
12921        }
12922
12923        public class IterGenerator<E> {
12924            public Iterator<E> generate(ActivityIntentInfo info) {
12925                return null;
12926            }
12927        }
12928
12929        public class ActionIterGenerator extends IterGenerator<String> {
12930            @Override
12931            public Iterator<String> generate(ActivityIntentInfo info) {
12932                return info.actionsIterator();
12933            }
12934        }
12935
12936        public class CategoriesIterGenerator extends IterGenerator<String> {
12937            @Override
12938            public Iterator<String> generate(ActivityIntentInfo info) {
12939                return info.categoriesIterator();
12940            }
12941        }
12942
12943        public class SchemesIterGenerator extends IterGenerator<String> {
12944            @Override
12945            public Iterator<String> generate(ActivityIntentInfo info) {
12946                return info.schemesIterator();
12947            }
12948        }
12949
12950        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12951            @Override
12952            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12953                return info.authoritiesIterator();
12954            }
12955        }
12956
12957        /**
12958         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12959         * MODIFIED. Do not pass in a list that should not be changed.
12960         */
12961        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12962                IterGenerator<T> generator, Iterator<T> searchIterator) {
12963            // loop through the set of actions; every one must be found in the intent filter
12964            while (searchIterator.hasNext()) {
12965                // we must have at least one filter in the list to consider a match
12966                if (intentList.size() == 0) {
12967                    break;
12968                }
12969
12970                final T searchAction = searchIterator.next();
12971
12972                // loop through the set of intent filters
12973                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12974                while (intentIter.hasNext()) {
12975                    final ActivityIntentInfo intentInfo = intentIter.next();
12976                    boolean selectionFound = false;
12977
12978                    // loop through the intent filter's selection criteria; at least one
12979                    // of them must match the searched criteria
12980                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12981                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12982                        final T intentSelection = intentSelectionIter.next();
12983                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12984                            selectionFound = true;
12985                            break;
12986                        }
12987                    }
12988
12989                    // the selection criteria wasn't found in this filter's set; this filter
12990                    // is not a potential match
12991                    if (!selectionFound) {
12992                        intentIter.remove();
12993                    }
12994                }
12995            }
12996        }
12997
12998        private boolean isProtectedAction(ActivityIntentInfo filter) {
12999            final Iterator<String> actionsIter = filter.actionsIterator();
13000            while (actionsIter != null && actionsIter.hasNext()) {
13001                final String filterAction = actionsIter.next();
13002                if (PROTECTED_ACTIONS.contains(filterAction)) {
13003                    return true;
13004                }
13005            }
13006            return false;
13007        }
13008
13009        /**
13010         * Adjusts the priority of the given intent filter according to policy.
13011         * <p>
13012         * <ul>
13013         * <li>The priority for non privileged applications is capped to '0'</li>
13014         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
13015         * <li>The priority for unbundled updates to privileged applications is capped to the
13016         *      priority defined on the system partition</li>
13017         * </ul>
13018         * <p>
13019         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
13020         * allowed to obtain any priority on any action.
13021         */
13022        private void adjustPriority(
13023                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
13024            // nothing to do; priority is fine as-is
13025            if (intent.getPriority() <= 0) {
13026                return;
13027            }
13028
13029            final ActivityInfo activityInfo = intent.activity.info;
13030            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
13031
13032            final boolean privilegedApp =
13033                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
13034            if (!privilegedApp) {
13035                // non-privileged applications can never define a priority >0
13036                if (DEBUG_FILTERS) {
13037                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
13038                            + " package: " + applicationInfo.packageName
13039                            + " activity: " + intent.activity.className
13040                            + " origPrio: " + intent.getPriority());
13041                }
13042                intent.setPriority(0);
13043                return;
13044            }
13045
13046            if (systemActivities == null) {
13047                // the system package is not disabled; we're parsing the system partition
13048                if (isProtectedAction(intent)) {
13049                    if (mDeferProtectedFilters) {
13050                        // We can't deal with these just yet. No component should ever obtain a
13051                        // >0 priority for a protected actions, with ONE exception -- the setup
13052                        // wizard. The setup wizard, however, cannot be known until we're able to
13053                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
13054                        // until all intent filters have been processed. Chicken, meet egg.
13055                        // Let the filter temporarily have a high priority and rectify the
13056                        // priorities after all system packages have been scanned.
13057                        mProtectedFilters.add(intent);
13058                        if (DEBUG_FILTERS) {
13059                            Slog.i(TAG, "Protected action; save for later;"
13060                                    + " package: " + applicationInfo.packageName
13061                                    + " activity: " + intent.activity.className
13062                                    + " origPrio: " + intent.getPriority());
13063                        }
13064                        return;
13065                    } else {
13066                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13067                            Slog.i(TAG, "No setup wizard;"
13068                                + " All protected intents capped to priority 0");
13069                        }
13070                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13071                            if (DEBUG_FILTERS) {
13072                                Slog.i(TAG, "Found setup wizard;"
13073                                    + " allow priority " + intent.getPriority() + ";"
13074                                    + " package: " + intent.activity.info.packageName
13075                                    + " activity: " + intent.activity.className
13076                                    + " priority: " + intent.getPriority());
13077                            }
13078                            // setup wizard gets whatever it wants
13079                            return;
13080                        }
13081                        if (DEBUG_FILTERS) {
13082                            Slog.i(TAG, "Protected action; cap priority to 0;"
13083                                    + " package: " + intent.activity.info.packageName
13084                                    + " activity: " + intent.activity.className
13085                                    + " origPrio: " + intent.getPriority());
13086                        }
13087                        intent.setPriority(0);
13088                        return;
13089                    }
13090                }
13091                // privileged apps on the system image get whatever priority they request
13092                return;
13093            }
13094
13095            // privileged app unbundled update ... try to find the same activity
13096            final PackageParser.Activity foundActivity =
13097                    findMatchingActivity(systemActivities, activityInfo);
13098            if (foundActivity == null) {
13099                // this is a new activity; it cannot obtain >0 priority
13100                if (DEBUG_FILTERS) {
13101                    Slog.i(TAG, "New activity; cap priority to 0;"
13102                            + " package: " + applicationInfo.packageName
13103                            + " activity: " + intent.activity.className
13104                            + " origPrio: " + intent.getPriority());
13105                }
13106                intent.setPriority(0);
13107                return;
13108            }
13109
13110            // found activity, now check for filter equivalence
13111
13112            // a shallow copy is enough; we modify the list, not its contents
13113            final List<ActivityIntentInfo> intentListCopy =
13114                    new ArrayList<>(foundActivity.intents);
13115            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13116
13117            // find matching action subsets
13118            final Iterator<String> actionsIterator = intent.actionsIterator();
13119            if (actionsIterator != null) {
13120                getIntentListSubset(
13121                        intentListCopy, new ActionIterGenerator(), actionsIterator);
13122                if (intentListCopy.size() == 0) {
13123                    // no more intents to match; we're not equivalent
13124                    if (DEBUG_FILTERS) {
13125                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
13126                                + " package: " + applicationInfo.packageName
13127                                + " activity: " + intent.activity.className
13128                                + " origPrio: " + intent.getPriority());
13129                    }
13130                    intent.setPriority(0);
13131                    return;
13132                }
13133            }
13134
13135            // find matching category subsets
13136            final Iterator<String> categoriesIterator = intent.categoriesIterator();
13137            if (categoriesIterator != null) {
13138                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13139                        categoriesIterator);
13140                if (intentListCopy.size() == 0) {
13141                    // no more intents to match; we're not equivalent
13142                    if (DEBUG_FILTERS) {
13143                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
13144                                + " package: " + applicationInfo.packageName
13145                                + " activity: " + intent.activity.className
13146                                + " origPrio: " + intent.getPriority());
13147                    }
13148                    intent.setPriority(0);
13149                    return;
13150                }
13151            }
13152
13153            // find matching schemes subsets
13154            final Iterator<String> schemesIterator = intent.schemesIterator();
13155            if (schemesIterator != null) {
13156                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13157                        schemesIterator);
13158                if (intentListCopy.size() == 0) {
13159                    // no more intents to match; we're not equivalent
13160                    if (DEBUG_FILTERS) {
13161                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
13162                                + " package: " + applicationInfo.packageName
13163                                + " activity: " + intent.activity.className
13164                                + " origPrio: " + intent.getPriority());
13165                    }
13166                    intent.setPriority(0);
13167                    return;
13168                }
13169            }
13170
13171            // find matching authorities subsets
13172            final Iterator<IntentFilter.AuthorityEntry>
13173                    authoritiesIterator = intent.authoritiesIterator();
13174            if (authoritiesIterator != null) {
13175                getIntentListSubset(intentListCopy,
13176                        new AuthoritiesIterGenerator(),
13177                        authoritiesIterator);
13178                if (intentListCopy.size() == 0) {
13179                    // no more intents to match; we're not equivalent
13180                    if (DEBUG_FILTERS) {
13181                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13182                                + " package: " + applicationInfo.packageName
13183                                + " activity: " + intent.activity.className
13184                                + " origPrio: " + intent.getPriority());
13185                    }
13186                    intent.setPriority(0);
13187                    return;
13188                }
13189            }
13190
13191            // we found matching filter(s); app gets the max priority of all intents
13192            int cappedPriority = 0;
13193            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13194                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13195            }
13196            if (intent.getPriority() > cappedPriority) {
13197                if (DEBUG_FILTERS) {
13198                    Slog.i(TAG, "Found matching filter(s);"
13199                            + " cap priority to " + cappedPriority + ";"
13200                            + " package: " + applicationInfo.packageName
13201                            + " activity: " + intent.activity.className
13202                            + " origPrio: " + intent.getPriority());
13203                }
13204                intent.setPriority(cappedPriority);
13205                return;
13206            }
13207            // all this for nothing; the requested priority was <= what was on the system
13208        }
13209
13210        public final void addActivity(PackageParser.Activity a, String type) {
13211            mActivities.put(a.getComponentName(), a);
13212            if (DEBUG_SHOW_INFO)
13213                Log.v(
13214                TAG, "  " + type + " " +
13215                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13216            if (DEBUG_SHOW_INFO)
13217                Log.v(TAG, "    Class=" + a.info.name);
13218            final int NI = a.intents.size();
13219            for (int j=0; j<NI; j++) {
13220                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13221                if ("activity".equals(type)) {
13222                    final PackageSetting ps =
13223                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13224                    final List<PackageParser.Activity> systemActivities =
13225                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
13226                    adjustPriority(systemActivities, intent);
13227                }
13228                if (DEBUG_SHOW_INFO) {
13229                    Log.v(TAG, "    IntentFilter:");
13230                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13231                }
13232                if (!intent.debugCheck()) {
13233                    Log.w(TAG, "==> For Activity " + a.info.name);
13234                }
13235                addFilter(intent);
13236            }
13237        }
13238
13239        public final void removeActivity(PackageParser.Activity a, String type) {
13240            mActivities.remove(a.getComponentName());
13241            if (DEBUG_SHOW_INFO) {
13242                Log.v(TAG, "  " + type + " "
13243                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13244                                : a.info.name) + ":");
13245                Log.v(TAG, "    Class=" + a.info.name);
13246            }
13247            final int NI = a.intents.size();
13248            for (int j=0; j<NI; j++) {
13249                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13250                if (DEBUG_SHOW_INFO) {
13251                    Log.v(TAG, "    IntentFilter:");
13252                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13253                }
13254                removeFilter(intent);
13255            }
13256        }
13257
13258        @Override
13259        protected boolean allowFilterResult(
13260                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13261            ActivityInfo filterAi = filter.activity.info;
13262            for (int i=dest.size()-1; i>=0; i--) {
13263                ActivityInfo destAi = dest.get(i).activityInfo;
13264                if (destAi.name == filterAi.name
13265                        && destAi.packageName == filterAi.packageName) {
13266                    return false;
13267                }
13268            }
13269            return true;
13270        }
13271
13272        @Override
13273        protected ActivityIntentInfo[] newArray(int size) {
13274            return new ActivityIntentInfo[size];
13275        }
13276
13277        @Override
13278        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13279            if (!sUserManager.exists(userId)) return true;
13280            PackageParser.Package p = filter.activity.owner;
13281            if (p != null) {
13282                PackageSetting ps = (PackageSetting)p.mExtras;
13283                if (ps != null) {
13284                    // System apps are never considered stopped for purposes of
13285                    // filtering, because there may be no way for the user to
13286                    // actually re-launch them.
13287                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13288                            && ps.getStopped(userId);
13289                }
13290            }
13291            return false;
13292        }
13293
13294        @Override
13295        protected boolean isPackageForFilter(String packageName,
13296                PackageParser.ActivityIntentInfo info) {
13297            return packageName.equals(info.activity.owner.packageName);
13298        }
13299
13300        @Override
13301        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13302                int match, int userId) {
13303            if (!sUserManager.exists(userId)) return null;
13304            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13305                return null;
13306            }
13307            final PackageParser.Activity activity = info.activity;
13308            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13309            if (ps == null) {
13310                return null;
13311            }
13312            final PackageUserState userState = ps.readUserState(userId);
13313            ActivityInfo ai =
13314                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13315            if (ai == null) {
13316                return null;
13317            }
13318            final boolean matchExplicitlyVisibleOnly =
13319                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13320            final boolean matchVisibleToInstantApp =
13321                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13322            final boolean componentVisible =
13323                    matchVisibleToInstantApp
13324                    && info.isVisibleToInstantApp()
13325                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13326            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13327            // throw out filters that aren't visible to ephemeral apps
13328            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13329                return null;
13330            }
13331            // throw out instant app filters if we're not explicitly requesting them
13332            if (!matchInstantApp && userState.instantApp) {
13333                return null;
13334            }
13335            // throw out instant app filters if updates are available; will trigger
13336            // instant app resolution
13337            if (userState.instantApp && ps.isUpdateAvailable()) {
13338                return null;
13339            }
13340            final ResolveInfo res = new ResolveInfo();
13341            res.activityInfo = ai;
13342            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13343                res.filter = info;
13344            }
13345            if (info != null) {
13346                res.handleAllWebDataURI = info.handleAllWebDataURI();
13347            }
13348            res.priority = info.getPriority();
13349            res.preferredOrder = activity.owner.mPreferredOrder;
13350            //System.out.println("Result: " + res.activityInfo.className +
13351            //                   " = " + res.priority);
13352            res.match = match;
13353            res.isDefault = info.hasDefault;
13354            res.labelRes = info.labelRes;
13355            res.nonLocalizedLabel = info.nonLocalizedLabel;
13356            if (userNeedsBadging(userId)) {
13357                res.noResourceId = true;
13358            } else {
13359                res.icon = info.icon;
13360            }
13361            res.iconResourceId = info.icon;
13362            res.system = res.activityInfo.applicationInfo.isSystemApp();
13363            res.isInstantAppAvailable = userState.instantApp;
13364            return res;
13365        }
13366
13367        @Override
13368        protected void sortResults(List<ResolveInfo> results) {
13369            Collections.sort(results, mResolvePrioritySorter);
13370        }
13371
13372        @Override
13373        protected void dumpFilter(PrintWriter out, String prefix,
13374                PackageParser.ActivityIntentInfo filter) {
13375            out.print(prefix); out.print(
13376                    Integer.toHexString(System.identityHashCode(filter.activity)));
13377                    out.print(' ');
13378                    filter.activity.printComponentShortName(out);
13379                    out.print(" filter ");
13380                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13381        }
13382
13383        @Override
13384        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13385            return filter.activity;
13386        }
13387
13388        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13389            PackageParser.Activity activity = (PackageParser.Activity)label;
13390            out.print(prefix); out.print(
13391                    Integer.toHexString(System.identityHashCode(activity)));
13392                    out.print(' ');
13393                    activity.printComponentShortName(out);
13394            if (count > 1) {
13395                out.print(" ("); out.print(count); out.print(" filters)");
13396            }
13397            out.println();
13398        }
13399
13400        // Keys are String (activity class name), values are Activity.
13401        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13402                = new ArrayMap<ComponentName, PackageParser.Activity>();
13403        private int mFlags;
13404    }
13405
13406    private final class ServiceIntentResolver
13407            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13408        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13409                boolean defaultOnly, int userId) {
13410            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13411            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13412        }
13413
13414        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13415                int userId) {
13416            if (!sUserManager.exists(userId)) return null;
13417            mFlags = flags;
13418            return super.queryIntent(intent, resolvedType,
13419                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13420                    userId);
13421        }
13422
13423        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13424                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13425            if (!sUserManager.exists(userId)) return null;
13426            if (packageServices == null) {
13427                return null;
13428            }
13429            mFlags = flags;
13430            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13431            final int N = packageServices.size();
13432            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13433                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13434
13435            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13436            for (int i = 0; i < N; ++i) {
13437                intentFilters = packageServices.get(i).intents;
13438                if (intentFilters != null && intentFilters.size() > 0) {
13439                    PackageParser.ServiceIntentInfo[] array =
13440                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
13441                    intentFilters.toArray(array);
13442                    listCut.add(array);
13443                }
13444            }
13445            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13446        }
13447
13448        public final void addService(PackageParser.Service s) {
13449            mServices.put(s.getComponentName(), s);
13450            if (DEBUG_SHOW_INFO) {
13451                Log.v(TAG, "  "
13452                        + (s.info.nonLocalizedLabel != null
13453                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13454                Log.v(TAG, "    Class=" + s.info.name);
13455            }
13456            final int NI = s.intents.size();
13457            int j;
13458            for (j=0; j<NI; j++) {
13459                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13460                if (DEBUG_SHOW_INFO) {
13461                    Log.v(TAG, "    IntentFilter:");
13462                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13463                }
13464                if (!intent.debugCheck()) {
13465                    Log.w(TAG, "==> For Service " + s.info.name);
13466                }
13467                addFilter(intent);
13468            }
13469        }
13470
13471        public final void removeService(PackageParser.Service s) {
13472            mServices.remove(s.getComponentName());
13473            if (DEBUG_SHOW_INFO) {
13474                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
13475                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13476                Log.v(TAG, "    Class=" + s.info.name);
13477            }
13478            final int NI = s.intents.size();
13479            int j;
13480            for (j=0; j<NI; j++) {
13481                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13482                if (DEBUG_SHOW_INFO) {
13483                    Log.v(TAG, "    IntentFilter:");
13484                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13485                }
13486                removeFilter(intent);
13487            }
13488        }
13489
13490        @Override
13491        protected boolean allowFilterResult(
13492                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
13493            ServiceInfo filterSi = filter.service.info;
13494            for (int i=dest.size()-1; i>=0; i--) {
13495                ServiceInfo destAi = dest.get(i).serviceInfo;
13496                if (destAi.name == filterSi.name
13497                        && destAi.packageName == filterSi.packageName) {
13498                    return false;
13499                }
13500            }
13501            return true;
13502        }
13503
13504        @Override
13505        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
13506            return new PackageParser.ServiceIntentInfo[size];
13507        }
13508
13509        @Override
13510        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
13511            if (!sUserManager.exists(userId)) return true;
13512            PackageParser.Package p = filter.service.owner;
13513            if (p != null) {
13514                PackageSetting ps = (PackageSetting)p.mExtras;
13515                if (ps != null) {
13516                    // System apps are never considered stopped for purposes of
13517                    // filtering, because there may be no way for the user to
13518                    // actually re-launch them.
13519                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13520                            && ps.getStopped(userId);
13521                }
13522            }
13523            return false;
13524        }
13525
13526        @Override
13527        protected boolean isPackageForFilter(String packageName,
13528                PackageParser.ServiceIntentInfo info) {
13529            return packageName.equals(info.service.owner.packageName);
13530        }
13531
13532        @Override
13533        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
13534                int match, int userId) {
13535            if (!sUserManager.exists(userId)) return null;
13536            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
13537            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
13538                return null;
13539            }
13540            final PackageParser.Service service = info.service;
13541            PackageSetting ps = (PackageSetting) service.owner.mExtras;
13542            if (ps == null) {
13543                return null;
13544            }
13545            final PackageUserState userState = ps.readUserState(userId);
13546            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
13547                    userState, userId);
13548            if (si == null) {
13549                return null;
13550            }
13551            final boolean matchVisibleToInstantApp =
13552                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13553            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13554            // throw out filters that aren't visible to ephemeral apps
13555            if (matchVisibleToInstantApp
13556                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13557                return null;
13558            }
13559            // throw out ephemeral filters if we're not explicitly requesting them
13560            if (!isInstantApp && userState.instantApp) {
13561                return null;
13562            }
13563            // throw out instant app filters if updates are available; will trigger
13564            // instant app resolution
13565            if (userState.instantApp && ps.isUpdateAvailable()) {
13566                return null;
13567            }
13568            final ResolveInfo res = new ResolveInfo();
13569            res.serviceInfo = si;
13570            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13571                res.filter = filter;
13572            }
13573            res.priority = info.getPriority();
13574            res.preferredOrder = service.owner.mPreferredOrder;
13575            res.match = match;
13576            res.isDefault = info.hasDefault;
13577            res.labelRes = info.labelRes;
13578            res.nonLocalizedLabel = info.nonLocalizedLabel;
13579            res.icon = info.icon;
13580            res.system = res.serviceInfo.applicationInfo.isSystemApp();
13581            return res;
13582        }
13583
13584        @Override
13585        protected void sortResults(List<ResolveInfo> results) {
13586            Collections.sort(results, mResolvePrioritySorter);
13587        }
13588
13589        @Override
13590        protected void dumpFilter(PrintWriter out, String prefix,
13591                PackageParser.ServiceIntentInfo filter) {
13592            out.print(prefix); out.print(
13593                    Integer.toHexString(System.identityHashCode(filter.service)));
13594                    out.print(' ');
13595                    filter.service.printComponentShortName(out);
13596                    out.print(" filter ");
13597                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13598        }
13599
13600        @Override
13601        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13602            return filter.service;
13603        }
13604
13605        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13606            PackageParser.Service service = (PackageParser.Service)label;
13607            out.print(prefix); out.print(
13608                    Integer.toHexString(System.identityHashCode(service)));
13609                    out.print(' ');
13610                    service.printComponentShortName(out);
13611            if (count > 1) {
13612                out.print(" ("); out.print(count); out.print(" filters)");
13613            }
13614            out.println();
13615        }
13616
13617//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13618//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13619//            final List<ResolveInfo> retList = Lists.newArrayList();
13620//            while (i.hasNext()) {
13621//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13622//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13623//                    retList.add(resolveInfo);
13624//                }
13625//            }
13626//            return retList;
13627//        }
13628
13629        // Keys are String (activity class name), values are Activity.
13630        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13631                = new ArrayMap<ComponentName, PackageParser.Service>();
13632        private int mFlags;
13633    }
13634
13635    private final class ProviderIntentResolver
13636            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13637        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13638                boolean defaultOnly, int userId) {
13639            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13640            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13641        }
13642
13643        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13644                int userId) {
13645            if (!sUserManager.exists(userId))
13646                return null;
13647            mFlags = flags;
13648            return super.queryIntent(intent, resolvedType,
13649                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13650                    userId);
13651        }
13652
13653        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13654                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13655            if (!sUserManager.exists(userId))
13656                return null;
13657            if (packageProviders == null) {
13658                return null;
13659            }
13660            mFlags = flags;
13661            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13662            final int N = packageProviders.size();
13663            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13664                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13665
13666            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13667            for (int i = 0; i < N; ++i) {
13668                intentFilters = packageProviders.get(i).intents;
13669                if (intentFilters != null && intentFilters.size() > 0) {
13670                    PackageParser.ProviderIntentInfo[] array =
13671                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13672                    intentFilters.toArray(array);
13673                    listCut.add(array);
13674                }
13675            }
13676            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13677        }
13678
13679        public final void addProvider(PackageParser.Provider p) {
13680            if (mProviders.containsKey(p.getComponentName())) {
13681                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13682                return;
13683            }
13684
13685            mProviders.put(p.getComponentName(), p);
13686            if (DEBUG_SHOW_INFO) {
13687                Log.v(TAG, "  "
13688                        + (p.info.nonLocalizedLabel != null
13689                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13690                Log.v(TAG, "    Class=" + p.info.name);
13691            }
13692            final int NI = p.intents.size();
13693            int j;
13694            for (j = 0; j < NI; j++) {
13695                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13696                if (DEBUG_SHOW_INFO) {
13697                    Log.v(TAG, "    IntentFilter:");
13698                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13699                }
13700                if (!intent.debugCheck()) {
13701                    Log.w(TAG, "==> For Provider " + p.info.name);
13702                }
13703                addFilter(intent);
13704            }
13705        }
13706
13707        public final void removeProvider(PackageParser.Provider p) {
13708            mProviders.remove(p.getComponentName());
13709            if (DEBUG_SHOW_INFO) {
13710                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13711                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13712                Log.v(TAG, "    Class=" + p.info.name);
13713            }
13714            final int NI = p.intents.size();
13715            int j;
13716            for (j = 0; j < NI; j++) {
13717                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13718                if (DEBUG_SHOW_INFO) {
13719                    Log.v(TAG, "    IntentFilter:");
13720                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13721                }
13722                removeFilter(intent);
13723            }
13724        }
13725
13726        @Override
13727        protected boolean allowFilterResult(
13728                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13729            ProviderInfo filterPi = filter.provider.info;
13730            for (int i = dest.size() - 1; i >= 0; i--) {
13731                ProviderInfo destPi = dest.get(i).providerInfo;
13732                if (destPi.name == filterPi.name
13733                        && destPi.packageName == filterPi.packageName) {
13734                    return false;
13735                }
13736            }
13737            return true;
13738        }
13739
13740        @Override
13741        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13742            return new PackageParser.ProviderIntentInfo[size];
13743        }
13744
13745        @Override
13746        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13747            if (!sUserManager.exists(userId))
13748                return true;
13749            PackageParser.Package p = filter.provider.owner;
13750            if (p != null) {
13751                PackageSetting ps = (PackageSetting) p.mExtras;
13752                if (ps != null) {
13753                    // System apps are never considered stopped for purposes of
13754                    // filtering, because there may be no way for the user to
13755                    // actually re-launch them.
13756                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13757                            && ps.getStopped(userId);
13758                }
13759            }
13760            return false;
13761        }
13762
13763        @Override
13764        protected boolean isPackageForFilter(String packageName,
13765                PackageParser.ProviderIntentInfo info) {
13766            return packageName.equals(info.provider.owner.packageName);
13767        }
13768
13769        @Override
13770        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13771                int match, int userId) {
13772            if (!sUserManager.exists(userId))
13773                return null;
13774            final PackageParser.ProviderIntentInfo info = filter;
13775            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13776                return null;
13777            }
13778            final PackageParser.Provider provider = info.provider;
13779            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13780            if (ps == null) {
13781                return null;
13782            }
13783            final PackageUserState userState = ps.readUserState(userId);
13784            final boolean matchVisibleToInstantApp =
13785                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13786            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13787            // throw out filters that aren't visible to instant applications
13788            if (matchVisibleToInstantApp
13789                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13790                return null;
13791            }
13792            // throw out instant application filters if we're not explicitly requesting them
13793            if (!isInstantApp && userState.instantApp) {
13794                return null;
13795            }
13796            // throw out instant application filters if updates are available; will trigger
13797            // instant application resolution
13798            if (userState.instantApp && ps.isUpdateAvailable()) {
13799                return null;
13800            }
13801            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13802                    userState, userId);
13803            if (pi == null) {
13804                return null;
13805            }
13806            final ResolveInfo res = new ResolveInfo();
13807            res.providerInfo = pi;
13808            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13809                res.filter = filter;
13810            }
13811            res.priority = info.getPriority();
13812            res.preferredOrder = provider.owner.mPreferredOrder;
13813            res.match = match;
13814            res.isDefault = info.hasDefault;
13815            res.labelRes = info.labelRes;
13816            res.nonLocalizedLabel = info.nonLocalizedLabel;
13817            res.icon = info.icon;
13818            res.system = res.providerInfo.applicationInfo.isSystemApp();
13819            return res;
13820        }
13821
13822        @Override
13823        protected void sortResults(List<ResolveInfo> results) {
13824            Collections.sort(results, mResolvePrioritySorter);
13825        }
13826
13827        @Override
13828        protected void dumpFilter(PrintWriter out, String prefix,
13829                PackageParser.ProviderIntentInfo filter) {
13830            out.print(prefix);
13831            out.print(
13832                    Integer.toHexString(System.identityHashCode(filter.provider)));
13833            out.print(' ');
13834            filter.provider.printComponentShortName(out);
13835            out.print(" filter ");
13836            out.println(Integer.toHexString(System.identityHashCode(filter)));
13837        }
13838
13839        @Override
13840        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13841            return filter.provider;
13842        }
13843
13844        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13845            PackageParser.Provider provider = (PackageParser.Provider)label;
13846            out.print(prefix); out.print(
13847                    Integer.toHexString(System.identityHashCode(provider)));
13848                    out.print(' ');
13849                    provider.printComponentShortName(out);
13850            if (count > 1) {
13851                out.print(" ("); out.print(count); out.print(" filters)");
13852            }
13853            out.println();
13854        }
13855
13856        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13857                = new ArrayMap<ComponentName, PackageParser.Provider>();
13858        private int mFlags;
13859    }
13860
13861    static final class EphemeralIntentResolver
13862            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
13863        /**
13864         * The result that has the highest defined order. Ordering applies on a
13865         * per-package basis. Mapping is from package name to Pair of order and
13866         * EphemeralResolveInfo.
13867         * <p>
13868         * NOTE: This is implemented as a field variable for convenience and efficiency.
13869         * By having a field variable, we're able to track filter ordering as soon as
13870         * a non-zero order is defined. Otherwise, multiple loops across the result set
13871         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13872         * this needs to be contained entirely within {@link #filterResults}.
13873         */
13874        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13875
13876        @Override
13877        protected AuxiliaryResolveInfo[] newArray(int size) {
13878            return new AuxiliaryResolveInfo[size];
13879        }
13880
13881        @Override
13882        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
13883            return true;
13884        }
13885
13886        @Override
13887        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
13888                int userId) {
13889            if (!sUserManager.exists(userId)) {
13890                return null;
13891            }
13892            final String packageName = responseObj.resolveInfo.getPackageName();
13893            final Integer order = responseObj.getOrder();
13894            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13895                    mOrderResult.get(packageName);
13896            // ordering is enabled and this item's order isn't high enough
13897            if (lastOrderResult != null && lastOrderResult.first >= order) {
13898                return null;
13899            }
13900            final InstantAppResolveInfo res = responseObj.resolveInfo;
13901            if (order > 0) {
13902                // non-zero order, enable ordering
13903                mOrderResult.put(packageName, new Pair<>(order, res));
13904            }
13905            return responseObj;
13906        }
13907
13908        @Override
13909        protected void filterResults(List<AuxiliaryResolveInfo> results) {
13910            // only do work if ordering is enabled [most of the time it won't be]
13911            if (mOrderResult.size() == 0) {
13912                return;
13913            }
13914            int resultSize = results.size();
13915            for (int i = 0; i < resultSize; i++) {
13916                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13917                final String packageName = info.getPackageName();
13918                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13919                if (savedInfo == null) {
13920                    // package doesn't having ordering
13921                    continue;
13922                }
13923                if (savedInfo.second == info) {
13924                    // circled back to the highest ordered item; remove from order list
13925                    mOrderResult.remove(savedInfo);
13926                    if (mOrderResult.size() == 0) {
13927                        // no more ordered items
13928                        break;
13929                    }
13930                    continue;
13931                }
13932                // item has a worse order, remove it from the result list
13933                results.remove(i);
13934                resultSize--;
13935                i--;
13936            }
13937        }
13938    }
13939
13940    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13941            new Comparator<ResolveInfo>() {
13942        public int compare(ResolveInfo r1, ResolveInfo r2) {
13943            int v1 = r1.priority;
13944            int v2 = r2.priority;
13945            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13946            if (v1 != v2) {
13947                return (v1 > v2) ? -1 : 1;
13948            }
13949            v1 = r1.preferredOrder;
13950            v2 = r2.preferredOrder;
13951            if (v1 != v2) {
13952                return (v1 > v2) ? -1 : 1;
13953            }
13954            if (r1.isDefault != r2.isDefault) {
13955                return r1.isDefault ? -1 : 1;
13956            }
13957            v1 = r1.match;
13958            v2 = r2.match;
13959            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13960            if (v1 != v2) {
13961                return (v1 > v2) ? -1 : 1;
13962            }
13963            if (r1.system != r2.system) {
13964                return r1.system ? -1 : 1;
13965            }
13966            if (r1.activityInfo != null) {
13967                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13968            }
13969            if (r1.serviceInfo != null) {
13970                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13971            }
13972            if (r1.providerInfo != null) {
13973                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13974            }
13975            return 0;
13976        }
13977    };
13978
13979    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13980            new Comparator<ProviderInfo>() {
13981        public int compare(ProviderInfo p1, ProviderInfo p2) {
13982            final int v1 = p1.initOrder;
13983            final int v2 = p2.initOrder;
13984            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13985        }
13986    };
13987
13988    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13989            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13990            final int[] userIds) {
13991        mHandler.post(new Runnable() {
13992            @Override
13993            public void run() {
13994                try {
13995                    final IActivityManager am = ActivityManager.getService();
13996                    if (am == null) return;
13997                    final int[] resolvedUserIds;
13998                    if (userIds == null) {
13999                        resolvedUserIds = am.getRunningUserIds();
14000                    } else {
14001                        resolvedUserIds = userIds;
14002                    }
14003                    for (int id : resolvedUserIds) {
14004                        final Intent intent = new Intent(action,
14005                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
14006                        if (extras != null) {
14007                            intent.putExtras(extras);
14008                        }
14009                        if (targetPkg != null) {
14010                            intent.setPackage(targetPkg);
14011                        }
14012                        // Modify the UID when posting to other users
14013                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
14014                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
14015                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
14016                            intent.putExtra(Intent.EXTRA_UID, uid);
14017                        }
14018                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
14019                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
14020                        if (DEBUG_BROADCASTS) {
14021                            RuntimeException here = new RuntimeException("here");
14022                            here.fillInStackTrace();
14023                            Slog.d(TAG, "Sending to user " + id + ": "
14024                                    + intent.toShortString(false, true, false, false)
14025                                    + " " + intent.getExtras(), here);
14026                        }
14027                        am.broadcastIntent(null, intent, null, finishedReceiver,
14028                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
14029                                null, finishedReceiver != null, false, id);
14030                    }
14031                } catch (RemoteException ex) {
14032                }
14033            }
14034        });
14035    }
14036
14037    /**
14038     * Check if the external storage media is available. This is true if there
14039     * is a mounted external storage medium or if the external storage is
14040     * emulated.
14041     */
14042    private boolean isExternalMediaAvailable() {
14043        return mMediaMounted || Environment.isExternalStorageEmulated();
14044    }
14045
14046    @Override
14047    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
14048        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14049            return null;
14050        }
14051        // writer
14052        synchronized (mPackages) {
14053            if (!isExternalMediaAvailable()) {
14054                // If the external storage is no longer mounted at this point,
14055                // the caller may not have been able to delete all of this
14056                // packages files and can not delete any more.  Bail.
14057                return null;
14058            }
14059            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14060            if (lastPackage != null) {
14061                pkgs.remove(lastPackage);
14062            }
14063            if (pkgs.size() > 0) {
14064                return pkgs.get(0);
14065            }
14066        }
14067        return null;
14068    }
14069
14070    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14071        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14072                userId, andCode ? 1 : 0, packageName);
14073        if (mSystemReady) {
14074            msg.sendToTarget();
14075        } else {
14076            if (mPostSystemReadyMessages == null) {
14077                mPostSystemReadyMessages = new ArrayList<>();
14078            }
14079            mPostSystemReadyMessages.add(msg);
14080        }
14081    }
14082
14083    void startCleaningPackages() {
14084        // reader
14085        if (!isExternalMediaAvailable()) {
14086            return;
14087        }
14088        synchronized (mPackages) {
14089            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14090                return;
14091            }
14092        }
14093        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14094        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14095        IActivityManager am = ActivityManager.getService();
14096        if (am != null) {
14097            int dcsUid = -1;
14098            synchronized (mPackages) {
14099                if (!mDefaultContainerWhitelisted) {
14100                    mDefaultContainerWhitelisted = true;
14101                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14102                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14103                }
14104            }
14105            try {
14106                if (dcsUid > 0) {
14107                    am.backgroundWhitelistUid(dcsUid);
14108                }
14109                am.startService(null, intent, null, false, mContext.getOpPackageName(),
14110                        UserHandle.USER_SYSTEM);
14111            } catch (RemoteException e) {
14112            }
14113        }
14114    }
14115
14116    @Override
14117    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14118            int installFlags, String installerPackageName, int userId) {
14119        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14120
14121        final int callingUid = Binder.getCallingUid();
14122        enforceCrossUserPermission(callingUid, userId,
14123                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14124
14125        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14126            try {
14127                if (observer != null) {
14128                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14129                }
14130            } catch (RemoteException re) {
14131            }
14132            return;
14133        }
14134
14135        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14136            installFlags |= PackageManager.INSTALL_FROM_ADB;
14137
14138        } else {
14139            // Caller holds INSTALL_PACKAGES permission, so we're less strict
14140            // about installerPackageName.
14141
14142            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14143            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14144        }
14145
14146        UserHandle user;
14147        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14148            user = UserHandle.ALL;
14149        } else {
14150            user = new UserHandle(userId);
14151        }
14152
14153        // Only system components can circumvent runtime permissions when installing.
14154        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14155                && mContext.checkCallingOrSelfPermission(Manifest.permission
14156                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14157            throw new SecurityException("You need the "
14158                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14159                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14160        }
14161
14162        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14163                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14164            throw new IllegalArgumentException(
14165                    "New installs into ASEC containers no longer supported");
14166        }
14167
14168        final File originFile = new File(originPath);
14169        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14170
14171        final Message msg = mHandler.obtainMessage(INIT_COPY);
14172        final VerificationInfo verificationInfo = new VerificationInfo(
14173                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14174        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14175                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14176                null /*packageAbiOverride*/, null /*grantedPermissions*/,
14177                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14178        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14179        msg.obj = params;
14180
14181        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14182                System.identityHashCode(msg.obj));
14183        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14184                System.identityHashCode(msg.obj));
14185
14186        mHandler.sendMessage(msg);
14187    }
14188
14189
14190    /**
14191     * Ensure that the install reason matches what we know about the package installer (e.g. whether
14192     * it is acting on behalf on an enterprise or the user).
14193     *
14194     * Note that the ordering of the conditionals in this method is important. The checks we perform
14195     * are as follows, in this order:
14196     *
14197     * 1) If the install is being performed by a system app, we can trust the app to have set the
14198     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14199     *    what it is.
14200     * 2) If the install is being performed by a device or profile owner app, the install reason
14201     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14202     *    set the install reason correctly. If the app targets an older SDK version where install
14203     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14204     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14205     * 3) In all other cases, the install is being performed by a regular app that is neither part
14206     *    of the system nor a device or profile owner. We have no reason to believe that this app is
14207     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14208     *    set to enterprise policy and if so, change it to unknown instead.
14209     */
14210    private int fixUpInstallReason(String installerPackageName, int installerUid,
14211            int installReason) {
14212        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14213                == PERMISSION_GRANTED) {
14214            // If the install is being performed by a system app, we trust that app to have set the
14215            // install reason correctly.
14216            return installReason;
14217        }
14218
14219        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14220            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14221        if (dpm != null) {
14222            ComponentName owner = null;
14223            try {
14224                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14225                if (owner == null) {
14226                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14227                }
14228            } catch (RemoteException e) {
14229            }
14230            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14231                // If the install is being performed by a device or profile owner, the install
14232                // reason should be enterprise policy.
14233                return PackageManager.INSTALL_REASON_POLICY;
14234            }
14235        }
14236
14237        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14238            // If the install is being performed by a regular app (i.e. neither system app nor
14239            // device or profile owner), we have no reason to believe that the app is acting on
14240            // behalf of an enterprise. If the app set the install reason to enterprise policy,
14241            // change it to unknown instead.
14242            return PackageManager.INSTALL_REASON_UNKNOWN;
14243        }
14244
14245        // If the install is being performed by a regular app and the install reason was set to any
14246        // value but enterprise policy, leave the install reason unchanged.
14247        return installReason;
14248    }
14249
14250    void installStage(String packageName, File stagedDir, String stagedCid,
14251            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14252            String installerPackageName, int installerUid, UserHandle user,
14253            Certificate[][] certificates) {
14254        if (DEBUG_EPHEMERAL) {
14255            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14256                Slog.d(TAG, "Ephemeral install of " + packageName);
14257            }
14258        }
14259        final VerificationInfo verificationInfo = new VerificationInfo(
14260                sessionParams.originatingUri, sessionParams.referrerUri,
14261                sessionParams.originatingUid, installerUid);
14262
14263        final OriginInfo origin;
14264        if (stagedDir != null) {
14265            origin = OriginInfo.fromStagedFile(stagedDir);
14266        } else {
14267            origin = OriginInfo.fromStagedContainer(stagedCid);
14268        }
14269
14270        final Message msg = mHandler.obtainMessage(INIT_COPY);
14271        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14272                sessionParams.installReason);
14273        final InstallParams params = new InstallParams(origin, null, observer,
14274                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14275                verificationInfo, user, sessionParams.abiOverride,
14276                sessionParams.grantedRuntimePermissions, certificates, installReason);
14277        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14278        msg.obj = params;
14279
14280        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14281                System.identityHashCode(msg.obj));
14282        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14283                System.identityHashCode(msg.obj));
14284
14285        mHandler.sendMessage(msg);
14286    }
14287
14288    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14289            int userId) {
14290        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14291        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
14292
14293        // Send a session commit broadcast
14294        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14295        info.installReason = pkgSetting.getInstallReason(userId);
14296        info.appPackageName = packageName;
14297        sendSessionCommitBroadcast(info, userId);
14298    }
14299
14300    public void sendPackageAddedForNewUsers(String packageName, boolean isSystem, int appId, int... userIds) {
14301        if (ArrayUtils.isEmpty(userIds)) {
14302            return;
14303        }
14304        Bundle extras = new Bundle(1);
14305        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14306        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14307
14308        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14309                packageName, extras, 0, null, null, userIds);
14310        if (isSystem) {
14311            mHandler.post(() -> {
14312                        for (int userId : userIds) {
14313                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
14314                        }
14315                    }
14316            );
14317        }
14318    }
14319
14320    /**
14321     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14322     * automatically without needing an explicit launch.
14323     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14324     */
14325    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
14326        // If user is not running, the app didn't miss any broadcast
14327        if (!mUserManagerInternal.isUserRunning(userId)) {
14328            return;
14329        }
14330        final IActivityManager am = ActivityManager.getService();
14331        try {
14332            // Deliver LOCKED_BOOT_COMPLETED first
14333            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14334                    .setPackage(packageName);
14335            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14336            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14337                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14338
14339            // Deliver BOOT_COMPLETED only if user is unlocked
14340            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14341                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14342                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14343                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14344            }
14345        } catch (RemoteException e) {
14346            throw e.rethrowFromSystemServer();
14347        }
14348    }
14349
14350    @Override
14351    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14352            int userId) {
14353        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14354        PackageSetting pkgSetting;
14355        final int callingUid = Binder.getCallingUid();
14356        enforceCrossUserPermission(callingUid, userId,
14357                true /* requireFullPermission */, true /* checkShell */,
14358                "setApplicationHiddenSetting for user " + userId);
14359
14360        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14361            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14362            return false;
14363        }
14364
14365        long callingId = Binder.clearCallingIdentity();
14366        try {
14367            boolean sendAdded = false;
14368            boolean sendRemoved = false;
14369            // writer
14370            synchronized (mPackages) {
14371                pkgSetting = mSettings.mPackages.get(packageName);
14372                if (pkgSetting == null) {
14373                    return false;
14374                }
14375                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14376                    return false;
14377                }
14378                // Do not allow "android" is being disabled
14379                if ("android".equals(packageName)) {
14380                    Slog.w(TAG, "Cannot hide package: android");
14381                    return false;
14382                }
14383                // Cannot hide static shared libs as they are considered
14384                // a part of the using app (emulating static linking). Also
14385                // static libs are installed always on internal storage.
14386                PackageParser.Package pkg = mPackages.get(packageName);
14387                if (pkg != null && pkg.staticSharedLibName != null) {
14388                    Slog.w(TAG, "Cannot hide package: " + packageName
14389                            + " providing static shared library: "
14390                            + pkg.staticSharedLibName);
14391                    return false;
14392                }
14393                // Only allow protected packages to hide themselves.
14394                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14395                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14396                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14397                    return false;
14398                }
14399
14400                if (pkgSetting.getHidden(userId) != hidden) {
14401                    pkgSetting.setHidden(hidden, userId);
14402                    mSettings.writePackageRestrictionsLPr(userId);
14403                    if (hidden) {
14404                        sendRemoved = true;
14405                    } else {
14406                        sendAdded = true;
14407                    }
14408                }
14409            }
14410            if (sendAdded) {
14411                sendPackageAddedForUser(packageName, pkgSetting, userId);
14412                return true;
14413            }
14414            if (sendRemoved) {
14415                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14416                        "hiding pkg");
14417                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14418                return true;
14419            }
14420        } finally {
14421            Binder.restoreCallingIdentity(callingId);
14422        }
14423        return false;
14424    }
14425
14426    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14427            int userId) {
14428        final PackageRemovedInfo info = new PackageRemovedInfo(this);
14429        info.removedPackage = packageName;
14430        info.installerPackageName = pkgSetting.installerPackageName;
14431        info.removedUsers = new int[] {userId};
14432        info.broadcastUsers = new int[] {userId};
14433        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14434        info.sendPackageRemovedBroadcasts(true /*killApp*/);
14435    }
14436
14437    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14438        if (pkgList.length > 0) {
14439            Bundle extras = new Bundle(1);
14440            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14441
14442            sendPackageBroadcast(
14443                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14444                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
14445                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14446                    new int[] {userId});
14447        }
14448    }
14449
14450    /**
14451     * Returns true if application is not found or there was an error. Otherwise it returns
14452     * the hidden state of the package for the given user.
14453     */
14454    @Override
14455    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14456        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14457        final int callingUid = Binder.getCallingUid();
14458        enforceCrossUserPermission(callingUid, userId,
14459                true /* requireFullPermission */, false /* checkShell */,
14460                "getApplicationHidden for user " + userId);
14461        PackageSetting ps;
14462        long callingId = Binder.clearCallingIdentity();
14463        try {
14464            // writer
14465            synchronized (mPackages) {
14466                ps = mSettings.mPackages.get(packageName);
14467                if (ps == null) {
14468                    return true;
14469                }
14470                if (filterAppAccessLPr(ps, callingUid, userId)) {
14471                    return true;
14472                }
14473                return ps.getHidden(userId);
14474            }
14475        } finally {
14476            Binder.restoreCallingIdentity(callingId);
14477        }
14478    }
14479
14480    /**
14481     * @hide
14482     */
14483    @Override
14484    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
14485            int installReason) {
14486        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
14487                null);
14488        PackageSetting pkgSetting;
14489        final int callingUid = Binder.getCallingUid();
14490        enforceCrossUserPermission(callingUid, userId,
14491                true /* requireFullPermission */, true /* checkShell */,
14492                "installExistingPackage for user " + userId);
14493        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14494            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
14495        }
14496
14497        long callingId = Binder.clearCallingIdentity();
14498        try {
14499            boolean installed = false;
14500            final boolean instantApp =
14501                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14502            final boolean fullApp =
14503                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
14504
14505            // writer
14506            synchronized (mPackages) {
14507                pkgSetting = mSettings.mPackages.get(packageName);
14508                if (pkgSetting == null) {
14509                    return PackageManager.INSTALL_FAILED_INVALID_URI;
14510                }
14511                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
14512                    // only allow the existing package to be used if it's installed as a full
14513                    // application for at least one user
14514                    boolean installAllowed = false;
14515                    for (int checkUserId : sUserManager.getUserIds()) {
14516                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
14517                        if (installAllowed) {
14518                            break;
14519                        }
14520                    }
14521                    if (!installAllowed) {
14522                        return PackageManager.INSTALL_FAILED_INVALID_URI;
14523                    }
14524                }
14525                if (!pkgSetting.getInstalled(userId)) {
14526                    pkgSetting.setInstalled(true, userId);
14527                    pkgSetting.setHidden(false, userId);
14528                    pkgSetting.setInstallReason(installReason, userId);
14529                    mSettings.writePackageRestrictionsLPr(userId);
14530                    mSettings.writeKernelMappingLPr(pkgSetting);
14531                    installed = true;
14532                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14533                    // upgrade app from instant to full; we don't allow app downgrade
14534                    installed = true;
14535                }
14536                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
14537            }
14538
14539            if (installed) {
14540                if (pkgSetting.pkg != null) {
14541                    synchronized (mInstallLock) {
14542                        // We don't need to freeze for a brand new install
14543                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
14544                    }
14545                }
14546                sendPackageAddedForUser(packageName, pkgSetting, userId);
14547                synchronized (mPackages) {
14548                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
14549                }
14550            }
14551        } finally {
14552            Binder.restoreCallingIdentity(callingId);
14553        }
14554
14555        return PackageManager.INSTALL_SUCCEEDED;
14556    }
14557
14558    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
14559            boolean instantApp, boolean fullApp) {
14560        // no state specified; do nothing
14561        if (!instantApp && !fullApp) {
14562            return;
14563        }
14564        if (userId != UserHandle.USER_ALL) {
14565            if (instantApp && !pkgSetting.getInstantApp(userId)) {
14566                pkgSetting.setInstantApp(true /*instantApp*/, userId);
14567            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14568                pkgSetting.setInstantApp(false /*instantApp*/, userId);
14569            }
14570        } else {
14571            for (int currentUserId : sUserManager.getUserIds()) {
14572                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14573                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14574                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14575                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14576                }
14577            }
14578        }
14579    }
14580
14581    boolean isUserRestricted(int userId, String restrictionKey) {
14582        Bundle restrictions = sUserManager.getUserRestrictions(userId);
14583        if (restrictions.getBoolean(restrictionKey, false)) {
14584            Log.w(TAG, "User is restricted: " + restrictionKey);
14585            return true;
14586        }
14587        return false;
14588    }
14589
14590    @Override
14591    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14592            int userId) {
14593        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14594        final int callingUid = Binder.getCallingUid();
14595        enforceCrossUserPermission(callingUid, userId,
14596                true /* requireFullPermission */, true /* checkShell */,
14597                "setPackagesSuspended for user " + userId);
14598
14599        if (ArrayUtils.isEmpty(packageNames)) {
14600            return packageNames;
14601        }
14602
14603        // List of package names for whom the suspended state has changed.
14604        List<String> changedPackages = new ArrayList<>(packageNames.length);
14605        // List of package names for whom the suspended state is not set as requested in this
14606        // method.
14607        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14608        long callingId = Binder.clearCallingIdentity();
14609        try {
14610            for (int i = 0; i < packageNames.length; i++) {
14611                String packageName = packageNames[i];
14612                boolean changed = false;
14613                final int appId;
14614                synchronized (mPackages) {
14615                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14616                    if (pkgSetting == null
14617                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14618                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
14619                                + "\". Skipping suspending/un-suspending.");
14620                        unactionedPackages.add(packageName);
14621                        continue;
14622                    }
14623                    appId = pkgSetting.appId;
14624                    if (pkgSetting.getSuspended(userId) != suspended) {
14625                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
14626                            unactionedPackages.add(packageName);
14627                            continue;
14628                        }
14629                        pkgSetting.setSuspended(suspended, userId);
14630                        mSettings.writePackageRestrictionsLPr(userId);
14631                        changed = true;
14632                        changedPackages.add(packageName);
14633                    }
14634                }
14635
14636                if (changed && suspended) {
14637                    killApplication(packageName, UserHandle.getUid(userId, appId),
14638                            "suspending package");
14639                }
14640            }
14641        } finally {
14642            Binder.restoreCallingIdentity(callingId);
14643        }
14644
14645        if (!changedPackages.isEmpty()) {
14646            sendPackagesSuspendedForUser(changedPackages.toArray(
14647                    new String[changedPackages.size()]), userId, suspended);
14648        }
14649
14650        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14651    }
14652
14653    @Override
14654    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14655        final int callingUid = Binder.getCallingUid();
14656        enforceCrossUserPermission(callingUid, userId,
14657                true /* requireFullPermission */, false /* checkShell */,
14658                "isPackageSuspendedForUser for user " + userId);
14659        synchronized (mPackages) {
14660            final PackageSetting ps = mSettings.mPackages.get(packageName);
14661            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14662                throw new IllegalArgumentException("Unknown target package: " + packageName);
14663            }
14664            return ps.getSuspended(userId);
14665        }
14666    }
14667
14668    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14669        if (isPackageDeviceAdmin(packageName, userId)) {
14670            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14671                    + "\": has an active device admin");
14672            return false;
14673        }
14674
14675        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14676        if (packageName.equals(activeLauncherPackageName)) {
14677            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14678                    + "\": contains the active launcher");
14679            return false;
14680        }
14681
14682        if (packageName.equals(mRequiredInstallerPackage)) {
14683            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14684                    + "\": required for package installation");
14685            return false;
14686        }
14687
14688        if (packageName.equals(mRequiredUninstallerPackage)) {
14689            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14690                    + "\": required for package uninstallation");
14691            return false;
14692        }
14693
14694        if (packageName.equals(mRequiredVerifierPackage)) {
14695            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14696                    + "\": required for package verification");
14697            return false;
14698        }
14699
14700        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14701            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14702                    + "\": is the default dialer");
14703            return false;
14704        }
14705
14706        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14707            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14708                    + "\": protected package");
14709            return false;
14710        }
14711
14712        // Cannot suspend static shared libs as they are considered
14713        // a part of the using app (emulating static linking). Also
14714        // static libs are installed always on internal storage.
14715        PackageParser.Package pkg = mPackages.get(packageName);
14716        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14717            Slog.w(TAG, "Cannot suspend package: " + packageName
14718                    + " providing static shared library: "
14719                    + pkg.staticSharedLibName);
14720            return false;
14721        }
14722
14723        return true;
14724    }
14725
14726    private String getActiveLauncherPackageName(int userId) {
14727        Intent intent = new Intent(Intent.ACTION_MAIN);
14728        intent.addCategory(Intent.CATEGORY_HOME);
14729        ResolveInfo resolveInfo = resolveIntent(
14730                intent,
14731                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14732                PackageManager.MATCH_DEFAULT_ONLY,
14733                userId);
14734
14735        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14736    }
14737
14738    private String getDefaultDialerPackageName(int userId) {
14739        synchronized (mPackages) {
14740            return mSettings.getDefaultDialerPackageNameLPw(userId);
14741        }
14742    }
14743
14744    @Override
14745    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14746        mContext.enforceCallingOrSelfPermission(
14747                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14748                "Only package verification agents can verify applications");
14749
14750        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14751        final PackageVerificationResponse response = new PackageVerificationResponse(
14752                verificationCode, Binder.getCallingUid());
14753        msg.arg1 = id;
14754        msg.obj = response;
14755        mHandler.sendMessage(msg);
14756    }
14757
14758    @Override
14759    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14760            long millisecondsToDelay) {
14761        mContext.enforceCallingOrSelfPermission(
14762                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14763                "Only package verification agents can extend verification timeouts");
14764
14765        final PackageVerificationState state = mPendingVerification.get(id);
14766        final PackageVerificationResponse response = new PackageVerificationResponse(
14767                verificationCodeAtTimeout, Binder.getCallingUid());
14768
14769        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14770            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14771        }
14772        if (millisecondsToDelay < 0) {
14773            millisecondsToDelay = 0;
14774        }
14775        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14776                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14777            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14778        }
14779
14780        if ((state != null) && !state.timeoutExtended()) {
14781            state.extendTimeout();
14782
14783            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14784            msg.arg1 = id;
14785            msg.obj = response;
14786            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14787        }
14788    }
14789
14790    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14791            int verificationCode, UserHandle user) {
14792        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14793        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14794        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14795        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14796        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14797
14798        mContext.sendBroadcastAsUser(intent, user,
14799                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14800    }
14801
14802    private ComponentName matchComponentForVerifier(String packageName,
14803            List<ResolveInfo> receivers) {
14804        ActivityInfo targetReceiver = null;
14805
14806        final int NR = receivers.size();
14807        for (int i = 0; i < NR; i++) {
14808            final ResolveInfo info = receivers.get(i);
14809            if (info.activityInfo == null) {
14810                continue;
14811            }
14812
14813            if (packageName.equals(info.activityInfo.packageName)) {
14814                targetReceiver = info.activityInfo;
14815                break;
14816            }
14817        }
14818
14819        if (targetReceiver == null) {
14820            return null;
14821        }
14822
14823        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14824    }
14825
14826    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14827            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14828        if (pkgInfo.verifiers.length == 0) {
14829            return null;
14830        }
14831
14832        final int N = pkgInfo.verifiers.length;
14833        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14834        for (int i = 0; i < N; i++) {
14835            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14836
14837            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14838                    receivers);
14839            if (comp == null) {
14840                continue;
14841            }
14842
14843            final int verifierUid = getUidForVerifier(verifierInfo);
14844            if (verifierUid == -1) {
14845                continue;
14846            }
14847
14848            if (DEBUG_VERIFY) {
14849                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14850                        + " with the correct signature");
14851            }
14852            sufficientVerifiers.add(comp);
14853            verificationState.addSufficientVerifier(verifierUid);
14854        }
14855
14856        return sufficientVerifiers;
14857    }
14858
14859    private int getUidForVerifier(VerifierInfo verifierInfo) {
14860        synchronized (mPackages) {
14861            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14862            if (pkg == null) {
14863                return -1;
14864            } else if (pkg.mSignatures.length != 1) {
14865                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14866                        + " has more than one signature; ignoring");
14867                return -1;
14868            }
14869
14870            /*
14871             * If the public key of the package's signature does not match
14872             * our expected public key, then this is a different package and
14873             * we should skip.
14874             */
14875
14876            final byte[] expectedPublicKey;
14877            try {
14878                final Signature verifierSig = pkg.mSignatures[0];
14879                final PublicKey publicKey = verifierSig.getPublicKey();
14880                expectedPublicKey = publicKey.getEncoded();
14881            } catch (CertificateException e) {
14882                return -1;
14883            }
14884
14885            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14886
14887            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14888                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14889                        + " does not have the expected public key; ignoring");
14890                return -1;
14891            }
14892
14893            return pkg.applicationInfo.uid;
14894        }
14895    }
14896
14897    @Override
14898    public void finishPackageInstall(int token, boolean didLaunch) {
14899        enforceSystemOrRoot("Only the system is allowed to finish installs");
14900
14901        if (DEBUG_INSTALL) {
14902            Slog.v(TAG, "BM finishing package install for " + token);
14903        }
14904        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14905
14906        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14907        mHandler.sendMessage(msg);
14908    }
14909
14910    /**
14911     * Get the verification agent timeout.  Used for both the APK verifier and the
14912     * intent filter verifier.
14913     *
14914     * @return verification timeout in milliseconds
14915     */
14916    private long getVerificationTimeout() {
14917        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14918                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14919                DEFAULT_VERIFICATION_TIMEOUT);
14920    }
14921
14922    /**
14923     * Get the default verification agent response code.
14924     *
14925     * @return default verification response code
14926     */
14927    private int getDefaultVerificationResponse(UserHandle user) {
14928        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14929            return PackageManager.VERIFICATION_REJECT;
14930        }
14931        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14932                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14933                DEFAULT_VERIFICATION_RESPONSE);
14934    }
14935
14936    /**
14937     * Check whether or not package verification has been enabled.
14938     *
14939     * @return true if verification should be performed
14940     */
14941    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
14942        if (!DEFAULT_VERIFY_ENABLE) {
14943            return false;
14944        }
14945
14946        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14947
14948        // Check if installing from ADB
14949        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14950            // Do not run verification in a test harness environment
14951            if (ActivityManager.isRunningInTestHarness()) {
14952                return false;
14953            }
14954            if (ensureVerifyAppsEnabled) {
14955                return true;
14956            }
14957            // Check if the developer does not want package verification for ADB installs
14958            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14959                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14960                return false;
14961            }
14962        } else {
14963            // only when not installed from ADB, skip verification for instant apps when
14964            // the installer and verifier are the same.
14965            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14966                if (mInstantAppInstallerActivity != null
14967                        && mInstantAppInstallerActivity.packageName.equals(
14968                                mRequiredVerifierPackage)) {
14969                    try {
14970                        mContext.getSystemService(AppOpsManager.class)
14971                                .checkPackage(installerUid, mRequiredVerifierPackage);
14972                        if (DEBUG_VERIFY) {
14973                            Slog.i(TAG, "disable verification for instant app");
14974                        }
14975                        return false;
14976                    } catch (SecurityException ignore) { }
14977                }
14978            }
14979        }
14980
14981        if (ensureVerifyAppsEnabled) {
14982            return true;
14983        }
14984
14985        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14986                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14987    }
14988
14989    @Override
14990    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14991            throws RemoteException {
14992        mContext.enforceCallingOrSelfPermission(
14993                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14994                "Only intentfilter verification agents can verify applications");
14995
14996        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14997        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14998                Binder.getCallingUid(), verificationCode, failedDomains);
14999        msg.arg1 = id;
15000        msg.obj = response;
15001        mHandler.sendMessage(msg);
15002    }
15003
15004    @Override
15005    public int getIntentVerificationStatus(String packageName, int userId) {
15006        final int callingUid = Binder.getCallingUid();
15007        if (getInstantAppPackageName(callingUid) != null) {
15008            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15009        }
15010        synchronized (mPackages) {
15011            final PackageSetting ps = mSettings.mPackages.get(packageName);
15012            if (ps == null
15013                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15014                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15015            }
15016            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
15017        }
15018    }
15019
15020    @Override
15021    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
15022        mContext.enforceCallingOrSelfPermission(
15023                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15024
15025        boolean result = false;
15026        synchronized (mPackages) {
15027            final PackageSetting ps = mSettings.mPackages.get(packageName);
15028            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15029                return false;
15030            }
15031            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
15032        }
15033        if (result) {
15034            scheduleWritePackageRestrictionsLocked(userId);
15035        }
15036        return result;
15037    }
15038
15039    @Override
15040    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
15041            String packageName) {
15042        final int callingUid = Binder.getCallingUid();
15043        if (getInstantAppPackageName(callingUid) != null) {
15044            return ParceledListSlice.emptyList();
15045        }
15046        synchronized (mPackages) {
15047            final PackageSetting ps = mSettings.mPackages.get(packageName);
15048            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15049                return ParceledListSlice.emptyList();
15050            }
15051            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
15052        }
15053    }
15054
15055    @Override
15056    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
15057        if (TextUtils.isEmpty(packageName)) {
15058            return ParceledListSlice.emptyList();
15059        }
15060        final int callingUid = Binder.getCallingUid();
15061        final int callingUserId = UserHandle.getUserId(callingUid);
15062        synchronized (mPackages) {
15063            PackageParser.Package pkg = mPackages.get(packageName);
15064            if (pkg == null || pkg.activities == null) {
15065                return ParceledListSlice.emptyList();
15066            }
15067            if (pkg.mExtras == null) {
15068                return ParceledListSlice.emptyList();
15069            }
15070            final PackageSetting ps = (PackageSetting) pkg.mExtras;
15071            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15072                return ParceledListSlice.emptyList();
15073            }
15074            final int count = pkg.activities.size();
15075            ArrayList<IntentFilter> result = new ArrayList<>();
15076            for (int n=0; n<count; n++) {
15077                PackageParser.Activity activity = pkg.activities.get(n);
15078                if (activity.intents != null && activity.intents.size() > 0) {
15079                    result.addAll(activity.intents);
15080                }
15081            }
15082            return new ParceledListSlice<>(result);
15083        }
15084    }
15085
15086    @Override
15087    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15088        mContext.enforceCallingOrSelfPermission(
15089                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15090
15091        synchronized (mPackages) {
15092            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15093            if (packageName != null) {
15094                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
15095                        packageName, userId);
15096            }
15097            return result;
15098        }
15099    }
15100
15101    @Override
15102    public String getDefaultBrowserPackageName(int userId) {
15103        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15104            return null;
15105        }
15106        synchronized (mPackages) {
15107            return mSettings.getDefaultBrowserPackageNameLPw(userId);
15108        }
15109    }
15110
15111    /**
15112     * Get the "allow unknown sources" setting.
15113     *
15114     * @return the current "allow unknown sources" setting
15115     */
15116    private int getUnknownSourcesSettings() {
15117        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15118                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15119                -1);
15120    }
15121
15122    @Override
15123    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15124        final int callingUid = Binder.getCallingUid();
15125        if (getInstantAppPackageName(callingUid) != null) {
15126            return;
15127        }
15128        // writer
15129        synchronized (mPackages) {
15130            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15131            if (targetPackageSetting == null
15132                    || filterAppAccessLPr(
15133                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15134                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15135            }
15136
15137            PackageSetting installerPackageSetting;
15138            if (installerPackageName != null) {
15139                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15140                if (installerPackageSetting == null) {
15141                    throw new IllegalArgumentException("Unknown installer package: "
15142                            + installerPackageName);
15143                }
15144            } else {
15145                installerPackageSetting = null;
15146            }
15147
15148            Signature[] callerSignature;
15149            Object obj = mSettings.getUserIdLPr(callingUid);
15150            if (obj != null) {
15151                if (obj instanceof SharedUserSetting) {
15152                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15153                } else if (obj instanceof PackageSetting) {
15154                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15155                } else {
15156                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15157                }
15158            } else {
15159                throw new SecurityException("Unknown calling UID: " + callingUid);
15160            }
15161
15162            // Verify: can't set installerPackageName to a package that is
15163            // not signed with the same cert as the caller.
15164            if (installerPackageSetting != null) {
15165                if (compareSignatures(callerSignature,
15166                        installerPackageSetting.signatures.mSignatures)
15167                        != PackageManager.SIGNATURE_MATCH) {
15168                    throw new SecurityException(
15169                            "Caller does not have same cert as new installer package "
15170                            + installerPackageName);
15171                }
15172            }
15173
15174            // Verify: if target already has an installer package, it must
15175            // be signed with the same cert as the caller.
15176            if (targetPackageSetting.installerPackageName != null) {
15177                PackageSetting setting = mSettings.mPackages.get(
15178                        targetPackageSetting.installerPackageName);
15179                // If the currently set package isn't valid, then it's always
15180                // okay to change it.
15181                if (setting != null) {
15182                    if (compareSignatures(callerSignature,
15183                            setting.signatures.mSignatures)
15184                            != PackageManager.SIGNATURE_MATCH) {
15185                        throw new SecurityException(
15186                                "Caller does not have same cert as old installer package "
15187                                + targetPackageSetting.installerPackageName);
15188                    }
15189                }
15190            }
15191
15192            // Okay!
15193            targetPackageSetting.installerPackageName = installerPackageName;
15194            if (installerPackageName != null) {
15195                mSettings.mInstallerPackages.add(installerPackageName);
15196            }
15197            scheduleWriteSettingsLocked();
15198        }
15199    }
15200
15201    @Override
15202    public void setApplicationCategoryHint(String packageName, int categoryHint,
15203            String callerPackageName) {
15204        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15205            throw new SecurityException("Instant applications don't have access to this method");
15206        }
15207        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15208                callerPackageName);
15209        synchronized (mPackages) {
15210            PackageSetting ps = mSettings.mPackages.get(packageName);
15211            if (ps == null) {
15212                throw new IllegalArgumentException("Unknown target package " + packageName);
15213            }
15214            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15215                throw new IllegalArgumentException("Unknown target package " + packageName);
15216            }
15217            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15218                throw new IllegalArgumentException("Calling package " + callerPackageName
15219                        + " is not installer for " + packageName);
15220            }
15221
15222            if (ps.categoryHint != categoryHint) {
15223                ps.categoryHint = categoryHint;
15224                scheduleWriteSettingsLocked();
15225            }
15226        }
15227    }
15228
15229    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15230        // Queue up an async operation since the package installation may take a little while.
15231        mHandler.post(new Runnable() {
15232            public void run() {
15233                mHandler.removeCallbacks(this);
15234                 // Result object to be returned
15235                PackageInstalledInfo res = new PackageInstalledInfo();
15236                res.setReturnCode(currentStatus);
15237                res.uid = -1;
15238                res.pkg = null;
15239                res.removedInfo = null;
15240                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15241                    args.doPreInstall(res.returnCode);
15242                    synchronized (mInstallLock) {
15243                        installPackageTracedLI(args, res);
15244                    }
15245                    args.doPostInstall(res.returnCode, res.uid);
15246                }
15247
15248                // A restore should be performed at this point if (a) the install
15249                // succeeded, (b) the operation is not an update, and (c) the new
15250                // package has not opted out of backup participation.
15251                final boolean update = res.removedInfo != null
15252                        && res.removedInfo.removedPackage != null;
15253                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15254                boolean doRestore = !update
15255                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15256
15257                // Set up the post-install work request bookkeeping.  This will be used
15258                // and cleaned up by the post-install event handling regardless of whether
15259                // there's a restore pass performed.  Token values are >= 1.
15260                int token;
15261                if (mNextInstallToken < 0) mNextInstallToken = 1;
15262                token = mNextInstallToken++;
15263
15264                PostInstallData data = new PostInstallData(args, res);
15265                mRunningInstalls.put(token, data);
15266                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15267
15268                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15269                    // Pass responsibility to the Backup Manager.  It will perform a
15270                    // restore if appropriate, then pass responsibility back to the
15271                    // Package Manager to run the post-install observer callbacks
15272                    // and broadcasts.
15273                    IBackupManager bm = IBackupManager.Stub.asInterface(
15274                            ServiceManager.getService(Context.BACKUP_SERVICE));
15275                    if (bm != null) {
15276                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15277                                + " to BM for possible restore");
15278                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15279                        try {
15280                            // TODO: http://b/22388012
15281                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15282                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15283                            } else {
15284                                doRestore = false;
15285                            }
15286                        } catch (RemoteException e) {
15287                            // can't happen; the backup manager is local
15288                        } catch (Exception e) {
15289                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15290                            doRestore = false;
15291                        }
15292                    } else {
15293                        Slog.e(TAG, "Backup Manager not found!");
15294                        doRestore = false;
15295                    }
15296                }
15297
15298                if (!doRestore) {
15299                    // No restore possible, or the Backup Manager was mysteriously not
15300                    // available -- just fire the post-install work request directly.
15301                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15302
15303                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15304
15305                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15306                    mHandler.sendMessage(msg);
15307                }
15308            }
15309        });
15310    }
15311
15312    /**
15313     * Callback from PackageSettings whenever an app is first transitioned out of the
15314     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15315     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15316     * here whether the app is the target of an ongoing install, and only send the
15317     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15318     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15319     * handling.
15320     */
15321    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15322        // Serialize this with the rest of the install-process message chain.  In the
15323        // restore-at-install case, this Runnable will necessarily run before the
15324        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15325        // are coherent.  In the non-restore case, the app has already completed install
15326        // and been launched through some other means, so it is not in a problematic
15327        // state for observers to see the FIRST_LAUNCH signal.
15328        mHandler.post(new Runnable() {
15329            @Override
15330            public void run() {
15331                for (int i = 0; i < mRunningInstalls.size(); i++) {
15332                    final PostInstallData data = mRunningInstalls.valueAt(i);
15333                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15334                        continue;
15335                    }
15336                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15337                        // right package; but is it for the right user?
15338                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15339                            if (userId == data.res.newUsers[uIndex]) {
15340                                if (DEBUG_BACKUP) {
15341                                    Slog.i(TAG, "Package " + pkgName
15342                                            + " being restored so deferring FIRST_LAUNCH");
15343                                }
15344                                return;
15345                            }
15346                        }
15347                    }
15348                }
15349                // didn't find it, so not being restored
15350                if (DEBUG_BACKUP) {
15351                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15352                }
15353                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15354            }
15355        });
15356    }
15357
15358    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15359        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15360                installerPkg, null, userIds);
15361    }
15362
15363    private abstract class HandlerParams {
15364        private static final int MAX_RETRIES = 4;
15365
15366        /**
15367         * Number of times startCopy() has been attempted and had a non-fatal
15368         * error.
15369         */
15370        private int mRetries = 0;
15371
15372        /** User handle for the user requesting the information or installation. */
15373        private final UserHandle mUser;
15374        String traceMethod;
15375        int traceCookie;
15376
15377        HandlerParams(UserHandle user) {
15378            mUser = user;
15379        }
15380
15381        UserHandle getUser() {
15382            return mUser;
15383        }
15384
15385        HandlerParams setTraceMethod(String traceMethod) {
15386            this.traceMethod = traceMethod;
15387            return this;
15388        }
15389
15390        HandlerParams setTraceCookie(int traceCookie) {
15391            this.traceCookie = traceCookie;
15392            return this;
15393        }
15394
15395        final boolean startCopy() {
15396            boolean res;
15397            try {
15398                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15399
15400                if (++mRetries > MAX_RETRIES) {
15401                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15402                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15403                    handleServiceError();
15404                    return false;
15405                } else {
15406                    handleStartCopy();
15407                    res = true;
15408                }
15409            } catch (RemoteException e) {
15410                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15411                mHandler.sendEmptyMessage(MCS_RECONNECT);
15412                res = false;
15413            }
15414            handleReturnCode();
15415            return res;
15416        }
15417
15418        final void serviceError() {
15419            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15420            handleServiceError();
15421            handleReturnCode();
15422        }
15423
15424        abstract void handleStartCopy() throws RemoteException;
15425        abstract void handleServiceError();
15426        abstract void handleReturnCode();
15427    }
15428
15429    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15430        for (File path : paths) {
15431            try {
15432                mcs.clearDirectory(path.getAbsolutePath());
15433            } catch (RemoteException e) {
15434            }
15435        }
15436    }
15437
15438    static class OriginInfo {
15439        /**
15440         * Location where install is coming from, before it has been
15441         * copied/renamed into place. This could be a single monolithic APK
15442         * file, or a cluster directory. This location may be untrusted.
15443         */
15444        final File file;
15445        final String cid;
15446
15447        /**
15448         * Flag indicating that {@link #file} or {@link #cid} has already been
15449         * staged, meaning downstream users don't need to defensively copy the
15450         * contents.
15451         */
15452        final boolean staged;
15453
15454        /**
15455         * Flag indicating that {@link #file} or {@link #cid} is an already
15456         * installed app that is being moved.
15457         */
15458        final boolean existing;
15459
15460        final String resolvedPath;
15461        final File resolvedFile;
15462
15463        static OriginInfo fromNothing() {
15464            return new OriginInfo(null, null, false, false);
15465        }
15466
15467        static OriginInfo fromUntrustedFile(File file) {
15468            return new OriginInfo(file, null, false, false);
15469        }
15470
15471        static OriginInfo fromExistingFile(File file) {
15472            return new OriginInfo(file, null, false, true);
15473        }
15474
15475        static OriginInfo fromStagedFile(File file) {
15476            return new OriginInfo(file, null, true, false);
15477        }
15478
15479        static OriginInfo fromStagedContainer(String cid) {
15480            return new OriginInfo(null, cid, true, false);
15481        }
15482
15483        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
15484            this.file = file;
15485            this.cid = cid;
15486            this.staged = staged;
15487            this.existing = existing;
15488
15489            if (cid != null) {
15490                resolvedPath = PackageHelper.getSdDir(cid);
15491                resolvedFile = new File(resolvedPath);
15492            } else if (file != null) {
15493                resolvedPath = file.getAbsolutePath();
15494                resolvedFile = file;
15495            } else {
15496                resolvedPath = null;
15497                resolvedFile = null;
15498            }
15499        }
15500    }
15501
15502    static class MoveInfo {
15503        final int moveId;
15504        final String fromUuid;
15505        final String toUuid;
15506        final String packageName;
15507        final String dataAppName;
15508        final int appId;
15509        final String seinfo;
15510        final int targetSdkVersion;
15511
15512        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15513                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15514            this.moveId = moveId;
15515            this.fromUuid = fromUuid;
15516            this.toUuid = toUuid;
15517            this.packageName = packageName;
15518            this.dataAppName = dataAppName;
15519            this.appId = appId;
15520            this.seinfo = seinfo;
15521            this.targetSdkVersion = targetSdkVersion;
15522        }
15523    }
15524
15525    static class VerificationInfo {
15526        /** A constant used to indicate that a uid value is not present. */
15527        public static final int NO_UID = -1;
15528
15529        /** URI referencing where the package was downloaded from. */
15530        final Uri originatingUri;
15531
15532        /** HTTP referrer URI associated with the originatingURI. */
15533        final Uri referrer;
15534
15535        /** UID of the application that the install request originated from. */
15536        final int originatingUid;
15537
15538        /** UID of application requesting the install */
15539        final int installerUid;
15540
15541        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15542            this.originatingUri = originatingUri;
15543            this.referrer = referrer;
15544            this.originatingUid = originatingUid;
15545            this.installerUid = installerUid;
15546        }
15547    }
15548
15549    class InstallParams extends HandlerParams {
15550        final OriginInfo origin;
15551        final MoveInfo move;
15552        final IPackageInstallObserver2 observer;
15553        int installFlags;
15554        final String installerPackageName;
15555        final String volumeUuid;
15556        private InstallArgs mArgs;
15557        private int mRet;
15558        final String packageAbiOverride;
15559        final String[] grantedRuntimePermissions;
15560        final VerificationInfo verificationInfo;
15561        final Certificate[][] certificates;
15562        final int installReason;
15563
15564        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15565                int installFlags, String installerPackageName, String volumeUuid,
15566                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15567                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
15568            super(user);
15569            this.origin = origin;
15570            this.move = move;
15571            this.observer = observer;
15572            this.installFlags = installFlags;
15573            this.installerPackageName = installerPackageName;
15574            this.volumeUuid = volumeUuid;
15575            this.verificationInfo = verificationInfo;
15576            this.packageAbiOverride = packageAbiOverride;
15577            this.grantedRuntimePermissions = grantedPermissions;
15578            this.certificates = certificates;
15579            this.installReason = installReason;
15580        }
15581
15582        @Override
15583        public String toString() {
15584            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15585                    + " file=" + origin.file + " cid=" + origin.cid + "}";
15586        }
15587
15588        private int installLocationPolicy(PackageInfoLite pkgLite) {
15589            String packageName = pkgLite.packageName;
15590            int installLocation = pkgLite.installLocation;
15591            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15592            // reader
15593            synchronized (mPackages) {
15594                // Currently installed package which the new package is attempting to replace or
15595                // null if no such package is installed.
15596                PackageParser.Package installedPkg = mPackages.get(packageName);
15597                // Package which currently owns the data which the new package will own if installed.
15598                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15599                // will be null whereas dataOwnerPkg will contain information about the package
15600                // which was uninstalled while keeping its data.
15601                PackageParser.Package dataOwnerPkg = installedPkg;
15602                if (dataOwnerPkg  == null) {
15603                    PackageSetting ps = mSettings.mPackages.get(packageName);
15604                    if (ps != null) {
15605                        dataOwnerPkg = ps.pkg;
15606                    }
15607                }
15608
15609                if (dataOwnerPkg != null) {
15610                    // If installed, the package will get access to data left on the device by its
15611                    // predecessor. As a security measure, this is permited only if this is not a
15612                    // version downgrade or if the predecessor package is marked as debuggable and
15613                    // a downgrade is explicitly requested.
15614                    //
15615                    // On debuggable platform builds, downgrades are permitted even for
15616                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15617                    // not offer security guarantees and thus it's OK to disable some security
15618                    // mechanisms to make debugging/testing easier on those builds. However, even on
15619                    // debuggable builds downgrades of packages are permitted only if requested via
15620                    // installFlags. This is because we aim to keep the behavior of debuggable
15621                    // platform builds as close as possible to the behavior of non-debuggable
15622                    // platform builds.
15623                    final boolean downgradeRequested =
15624                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15625                    final boolean packageDebuggable =
15626                                (dataOwnerPkg.applicationInfo.flags
15627                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15628                    final boolean downgradePermitted =
15629                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15630                    if (!downgradePermitted) {
15631                        try {
15632                            checkDowngrade(dataOwnerPkg, pkgLite);
15633                        } catch (PackageManagerException e) {
15634                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15635                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15636                        }
15637                    }
15638                }
15639
15640                if (installedPkg != null) {
15641                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15642                        // Check for updated system application.
15643                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15644                            if (onSd) {
15645                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15646                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15647                            }
15648                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15649                        } else {
15650                            if (onSd) {
15651                                // Install flag overrides everything.
15652                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15653                            }
15654                            // If current upgrade specifies particular preference
15655                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15656                                // Application explicitly specified internal.
15657                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15658                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15659                                // App explictly prefers external. Let policy decide
15660                            } else {
15661                                // Prefer previous location
15662                                if (isExternal(installedPkg)) {
15663                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15664                                }
15665                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15666                            }
15667                        }
15668                    } else {
15669                        // Invalid install. Return error code
15670                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15671                    }
15672                }
15673            }
15674            // All the special cases have been taken care of.
15675            // Return result based on recommended install location.
15676            if (onSd) {
15677                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15678            }
15679            return pkgLite.recommendedInstallLocation;
15680        }
15681
15682        /*
15683         * Invoke remote method to get package information and install
15684         * location values. Override install location based on default
15685         * policy if needed and then create install arguments based
15686         * on the install location.
15687         */
15688        public void handleStartCopy() throws RemoteException {
15689            int ret = PackageManager.INSTALL_SUCCEEDED;
15690
15691            // If we're already staged, we've firmly committed to an install location
15692            if (origin.staged) {
15693                if (origin.file != null) {
15694                    installFlags |= PackageManager.INSTALL_INTERNAL;
15695                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15696                } else if (origin.cid != null) {
15697                    installFlags |= PackageManager.INSTALL_EXTERNAL;
15698                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
15699                } else {
15700                    throw new IllegalStateException("Invalid stage location");
15701                }
15702            }
15703
15704            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15705            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15706            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15707            PackageInfoLite pkgLite = null;
15708
15709            if (onInt && onSd) {
15710                // Check if both bits are set.
15711                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15712                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15713            } else if (onSd && ephemeral) {
15714                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15715                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15716            } else {
15717                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15718                        packageAbiOverride);
15719
15720                if (DEBUG_EPHEMERAL && ephemeral) {
15721                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15722                }
15723
15724                /*
15725                 * If we have too little free space, try to free cache
15726                 * before giving up.
15727                 */
15728                if (!origin.staged && pkgLite.recommendedInstallLocation
15729                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15730                    // TODO: focus freeing disk space on the target device
15731                    final StorageManager storage = StorageManager.from(mContext);
15732                    final long lowThreshold = storage.getStorageLowBytes(
15733                            Environment.getDataDirectory());
15734
15735                    final long sizeBytes = mContainerService.calculateInstalledSize(
15736                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
15737
15738                    try {
15739                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15740                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15741                                installFlags, packageAbiOverride);
15742                    } catch (InstallerException e) {
15743                        Slog.w(TAG, "Failed to free cache", e);
15744                    }
15745
15746                    /*
15747                     * The cache free must have deleted the file we
15748                     * downloaded to install.
15749                     *
15750                     * TODO: fix the "freeCache" call to not delete
15751                     *       the file we care about.
15752                     */
15753                    if (pkgLite.recommendedInstallLocation
15754                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15755                        pkgLite.recommendedInstallLocation
15756                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15757                    }
15758                }
15759            }
15760
15761            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15762                int loc = pkgLite.recommendedInstallLocation;
15763                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15764                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15765                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15766                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15767                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15768                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15769                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15770                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15771                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15772                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15773                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15774                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15775                } else {
15776                    // Override with defaults if needed.
15777                    loc = installLocationPolicy(pkgLite);
15778                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15779                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15780                    } else if (!onSd && !onInt) {
15781                        // Override install location with flags
15782                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15783                            // Set the flag to install on external media.
15784                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15785                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15786                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15787                            if (DEBUG_EPHEMERAL) {
15788                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15789                            }
15790                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15791                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15792                                    |PackageManager.INSTALL_INTERNAL);
15793                        } else {
15794                            // Make sure the flag for installing on external
15795                            // media is unset
15796                            installFlags |= PackageManager.INSTALL_INTERNAL;
15797                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15798                        }
15799                    }
15800                }
15801            }
15802
15803            final InstallArgs args = createInstallArgs(this);
15804            mArgs = args;
15805
15806            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15807                // TODO: http://b/22976637
15808                // Apps installed for "all" users use the device owner to verify the app
15809                UserHandle verifierUser = getUser();
15810                if (verifierUser == UserHandle.ALL) {
15811                    verifierUser = UserHandle.SYSTEM;
15812                }
15813
15814                /*
15815                 * Determine if we have any installed package verifiers. If we
15816                 * do, then we'll defer to them to verify the packages.
15817                 */
15818                final int requiredUid = mRequiredVerifierPackage == null ? -1
15819                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15820                                verifierUser.getIdentifier());
15821                final int installerUid =
15822                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15823                if (!origin.existing && requiredUid != -1
15824                        && isVerificationEnabled(
15825                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15826                    final Intent verification = new Intent(
15827                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15828                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15829                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15830                            PACKAGE_MIME_TYPE);
15831                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15832
15833                    // Query all live verifiers based on current user state
15834                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15835                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
15836
15837                    if (DEBUG_VERIFY) {
15838                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15839                                + verification.toString() + " with " + pkgLite.verifiers.length
15840                                + " optional verifiers");
15841                    }
15842
15843                    final int verificationId = mPendingVerificationToken++;
15844
15845                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15846
15847                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15848                            installerPackageName);
15849
15850                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15851                            installFlags);
15852
15853                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15854                            pkgLite.packageName);
15855
15856                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15857                            pkgLite.versionCode);
15858
15859                    if (verificationInfo != null) {
15860                        if (verificationInfo.originatingUri != null) {
15861                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15862                                    verificationInfo.originatingUri);
15863                        }
15864                        if (verificationInfo.referrer != null) {
15865                            verification.putExtra(Intent.EXTRA_REFERRER,
15866                                    verificationInfo.referrer);
15867                        }
15868                        if (verificationInfo.originatingUid >= 0) {
15869                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15870                                    verificationInfo.originatingUid);
15871                        }
15872                        if (verificationInfo.installerUid >= 0) {
15873                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15874                                    verificationInfo.installerUid);
15875                        }
15876                    }
15877
15878                    final PackageVerificationState verificationState = new PackageVerificationState(
15879                            requiredUid, args);
15880
15881                    mPendingVerification.append(verificationId, verificationState);
15882
15883                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15884                            receivers, verificationState);
15885
15886                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15887                    final long idleDuration = getVerificationTimeout();
15888
15889                    /*
15890                     * If any sufficient verifiers were listed in the package
15891                     * manifest, attempt to ask them.
15892                     */
15893                    if (sufficientVerifiers != null) {
15894                        final int N = sufficientVerifiers.size();
15895                        if (N == 0) {
15896                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15897                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15898                        } else {
15899                            for (int i = 0; i < N; i++) {
15900                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15901                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15902                                        verifierComponent.getPackageName(), idleDuration,
15903                                        verifierUser.getIdentifier(), false, "package verifier");
15904
15905                                final Intent sufficientIntent = new Intent(verification);
15906                                sufficientIntent.setComponent(verifierComponent);
15907                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15908                            }
15909                        }
15910                    }
15911
15912                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15913                            mRequiredVerifierPackage, receivers);
15914                    if (ret == PackageManager.INSTALL_SUCCEEDED
15915                            && mRequiredVerifierPackage != null) {
15916                        Trace.asyncTraceBegin(
15917                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15918                        /*
15919                         * Send the intent to the required verification agent,
15920                         * but only start the verification timeout after the
15921                         * target BroadcastReceivers have run.
15922                         */
15923                        verification.setComponent(requiredVerifierComponent);
15924                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15925                                mRequiredVerifierPackage, idleDuration,
15926                                verifierUser.getIdentifier(), false, "package verifier");
15927                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15928                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15929                                new BroadcastReceiver() {
15930                                    @Override
15931                                    public void onReceive(Context context, Intent intent) {
15932                                        final Message msg = mHandler
15933                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15934                                        msg.arg1 = verificationId;
15935                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15936                                    }
15937                                }, null, 0, null, null);
15938
15939                        /*
15940                         * We don't want the copy to proceed until verification
15941                         * succeeds, so null out this field.
15942                         */
15943                        mArgs = null;
15944                    }
15945                } else {
15946                    /*
15947                     * No package verification is enabled, so immediately start
15948                     * the remote call to initiate copy using temporary file.
15949                     */
15950                    ret = args.copyApk(mContainerService, true);
15951                }
15952            }
15953
15954            mRet = ret;
15955        }
15956
15957        @Override
15958        void handleReturnCode() {
15959            // If mArgs is null, then MCS couldn't be reached. When it
15960            // reconnects, it will try again to install. At that point, this
15961            // will succeed.
15962            if (mArgs != null) {
15963                processPendingInstall(mArgs, mRet);
15964            }
15965        }
15966
15967        @Override
15968        void handleServiceError() {
15969            mArgs = createInstallArgs(this);
15970            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15971        }
15972
15973        public boolean isForwardLocked() {
15974            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15975        }
15976    }
15977
15978    /**
15979     * Used during creation of InstallArgs
15980     *
15981     * @param installFlags package installation flags
15982     * @return true if should be installed on external storage
15983     */
15984    private static boolean installOnExternalAsec(int installFlags) {
15985        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
15986            return false;
15987        }
15988        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
15989            return true;
15990        }
15991        return false;
15992    }
15993
15994    /**
15995     * Used during creation of InstallArgs
15996     *
15997     * @param installFlags package installation flags
15998     * @return true if should be installed as forward locked
15999     */
16000    private static boolean installForwardLocked(int installFlags) {
16001        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16002    }
16003
16004    private InstallArgs createInstallArgs(InstallParams params) {
16005        if (params.move != null) {
16006            return new MoveInstallArgs(params);
16007        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
16008            return new AsecInstallArgs(params);
16009        } else {
16010            return new FileInstallArgs(params);
16011        }
16012    }
16013
16014    /**
16015     * Create args that describe an existing installed package. Typically used
16016     * when cleaning up old installs, or used as a move source.
16017     */
16018    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
16019            String resourcePath, String[] instructionSets) {
16020        final boolean isInAsec;
16021        if (installOnExternalAsec(installFlags)) {
16022            /* Apps on SD card are always in ASEC containers. */
16023            isInAsec = true;
16024        } else if (installForwardLocked(installFlags)
16025                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
16026            /*
16027             * Forward-locked apps are only in ASEC containers if they're the
16028             * new style
16029             */
16030            isInAsec = true;
16031        } else {
16032            isInAsec = false;
16033        }
16034
16035        if (isInAsec) {
16036            return new AsecInstallArgs(codePath, instructionSets,
16037                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
16038        } else {
16039            return new FileInstallArgs(codePath, resourcePath, instructionSets);
16040        }
16041    }
16042
16043    static abstract class InstallArgs {
16044        /** @see InstallParams#origin */
16045        final OriginInfo origin;
16046        /** @see InstallParams#move */
16047        final MoveInfo move;
16048
16049        final IPackageInstallObserver2 observer;
16050        // Always refers to PackageManager flags only
16051        final int installFlags;
16052        final String installerPackageName;
16053        final String volumeUuid;
16054        final UserHandle user;
16055        final String abiOverride;
16056        final String[] installGrantPermissions;
16057        /** If non-null, drop an async trace when the install completes */
16058        final String traceMethod;
16059        final int traceCookie;
16060        final Certificate[][] certificates;
16061        final int installReason;
16062
16063        // The list of instruction sets supported by this app. This is currently
16064        // only used during the rmdex() phase to clean up resources. We can get rid of this
16065        // if we move dex files under the common app path.
16066        /* nullable */ String[] instructionSets;
16067
16068        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16069                int installFlags, String installerPackageName, String volumeUuid,
16070                UserHandle user, String[] instructionSets,
16071                String abiOverride, String[] installGrantPermissions,
16072                String traceMethod, int traceCookie, Certificate[][] certificates,
16073                int installReason) {
16074            this.origin = origin;
16075            this.move = move;
16076            this.installFlags = installFlags;
16077            this.observer = observer;
16078            this.installerPackageName = installerPackageName;
16079            this.volumeUuid = volumeUuid;
16080            this.user = user;
16081            this.instructionSets = instructionSets;
16082            this.abiOverride = abiOverride;
16083            this.installGrantPermissions = installGrantPermissions;
16084            this.traceMethod = traceMethod;
16085            this.traceCookie = traceCookie;
16086            this.certificates = certificates;
16087            this.installReason = installReason;
16088        }
16089
16090        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16091        abstract int doPreInstall(int status);
16092
16093        /**
16094         * Rename package into final resting place. All paths on the given
16095         * scanned package should be updated to reflect the rename.
16096         */
16097        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16098        abstract int doPostInstall(int status, int uid);
16099
16100        /** @see PackageSettingBase#codePathString */
16101        abstract String getCodePath();
16102        /** @see PackageSettingBase#resourcePathString */
16103        abstract String getResourcePath();
16104
16105        // Need installer lock especially for dex file removal.
16106        abstract void cleanUpResourcesLI();
16107        abstract boolean doPostDeleteLI(boolean delete);
16108
16109        /**
16110         * Called before the source arguments are copied. This is used mostly
16111         * for MoveParams when it needs to read the source file to put it in the
16112         * destination.
16113         */
16114        int doPreCopy() {
16115            return PackageManager.INSTALL_SUCCEEDED;
16116        }
16117
16118        /**
16119         * Called after the source arguments are copied. This is used mostly for
16120         * MoveParams when it needs to read the source file to put it in the
16121         * destination.
16122         */
16123        int doPostCopy(int uid) {
16124            return PackageManager.INSTALL_SUCCEEDED;
16125        }
16126
16127        protected boolean isFwdLocked() {
16128            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16129        }
16130
16131        protected boolean isExternalAsec() {
16132            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16133        }
16134
16135        protected boolean isEphemeral() {
16136            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16137        }
16138
16139        UserHandle getUser() {
16140            return user;
16141        }
16142    }
16143
16144    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16145        if (!allCodePaths.isEmpty()) {
16146            if (instructionSets == null) {
16147                throw new IllegalStateException("instructionSet == null");
16148            }
16149            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16150            for (String codePath : allCodePaths) {
16151                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16152                    try {
16153                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
16154                    } catch (InstallerException ignored) {
16155                    }
16156                }
16157            }
16158        }
16159    }
16160
16161    /**
16162     * Logic to handle installation of non-ASEC applications, including copying
16163     * and renaming logic.
16164     */
16165    class FileInstallArgs extends InstallArgs {
16166        private File codeFile;
16167        private File resourceFile;
16168
16169        // Example topology:
16170        // /data/app/com.example/base.apk
16171        // /data/app/com.example/split_foo.apk
16172        // /data/app/com.example/lib/arm/libfoo.so
16173        // /data/app/com.example/lib/arm64/libfoo.so
16174        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16175
16176        /** New install */
16177        FileInstallArgs(InstallParams params) {
16178            super(params.origin, params.move, params.observer, params.installFlags,
16179                    params.installerPackageName, params.volumeUuid,
16180                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16181                    params.grantedRuntimePermissions,
16182                    params.traceMethod, params.traceCookie, params.certificates,
16183                    params.installReason);
16184            if (isFwdLocked()) {
16185                throw new IllegalArgumentException("Forward locking only supported in ASEC");
16186            }
16187        }
16188
16189        /** Existing install */
16190        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16191            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16192                    null, null, null, 0, null /*certificates*/,
16193                    PackageManager.INSTALL_REASON_UNKNOWN);
16194            this.codeFile = (codePath != null) ? new File(codePath) : null;
16195            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16196        }
16197
16198        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16199            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16200            try {
16201                return doCopyApk(imcs, temp);
16202            } finally {
16203                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16204            }
16205        }
16206
16207        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16208            if (origin.staged) {
16209                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16210                codeFile = origin.file;
16211                resourceFile = origin.file;
16212                return PackageManager.INSTALL_SUCCEEDED;
16213            }
16214
16215            try {
16216                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16217                final File tempDir =
16218                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16219                codeFile = tempDir;
16220                resourceFile = tempDir;
16221            } catch (IOException e) {
16222                Slog.w(TAG, "Failed to create copy file: " + e);
16223                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16224            }
16225
16226            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16227                @Override
16228                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16229                    if (!FileUtils.isValidExtFilename(name)) {
16230                        throw new IllegalArgumentException("Invalid filename: " + name);
16231                    }
16232                    try {
16233                        final File file = new File(codeFile, name);
16234                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16235                                O_RDWR | O_CREAT, 0644);
16236                        Os.chmod(file.getAbsolutePath(), 0644);
16237                        return new ParcelFileDescriptor(fd);
16238                    } catch (ErrnoException e) {
16239                        throw new RemoteException("Failed to open: " + e.getMessage());
16240                    }
16241                }
16242            };
16243
16244            int ret = PackageManager.INSTALL_SUCCEEDED;
16245            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16246            if (ret != PackageManager.INSTALL_SUCCEEDED) {
16247                Slog.e(TAG, "Failed to copy package");
16248                return ret;
16249            }
16250
16251            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16252            NativeLibraryHelper.Handle handle = null;
16253            try {
16254                handle = NativeLibraryHelper.Handle.create(codeFile);
16255                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16256                        abiOverride);
16257            } catch (IOException e) {
16258                Slog.e(TAG, "Copying native libraries failed", e);
16259                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16260            } finally {
16261                IoUtils.closeQuietly(handle);
16262            }
16263
16264            return ret;
16265        }
16266
16267        int doPreInstall(int status) {
16268            if (status != PackageManager.INSTALL_SUCCEEDED) {
16269                cleanUp();
16270            }
16271            return status;
16272        }
16273
16274        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16275            if (status != PackageManager.INSTALL_SUCCEEDED) {
16276                cleanUp();
16277                return false;
16278            }
16279
16280            final File targetDir = codeFile.getParentFile();
16281            final File beforeCodeFile = codeFile;
16282            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16283
16284            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16285            try {
16286                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16287            } catch (ErrnoException e) {
16288                Slog.w(TAG, "Failed to rename", e);
16289                return false;
16290            }
16291
16292            if (!SELinux.restoreconRecursive(afterCodeFile)) {
16293                Slog.w(TAG, "Failed to restorecon");
16294                return false;
16295            }
16296
16297            // Reflect the rename internally
16298            codeFile = afterCodeFile;
16299            resourceFile = afterCodeFile;
16300
16301            // Reflect the rename in scanned details
16302            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16303            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16304                    afterCodeFile, pkg.baseCodePath));
16305            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16306                    afterCodeFile, pkg.splitCodePaths));
16307
16308            // Reflect the rename in app info
16309            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16310            pkg.setApplicationInfoCodePath(pkg.codePath);
16311            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16312            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16313            pkg.setApplicationInfoResourcePath(pkg.codePath);
16314            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16315            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16316
16317            return true;
16318        }
16319
16320        int doPostInstall(int status, int uid) {
16321            if (status != PackageManager.INSTALL_SUCCEEDED) {
16322                cleanUp();
16323            }
16324            return status;
16325        }
16326
16327        @Override
16328        String getCodePath() {
16329            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16330        }
16331
16332        @Override
16333        String getResourcePath() {
16334            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16335        }
16336
16337        private boolean cleanUp() {
16338            if (codeFile == null || !codeFile.exists()) {
16339                return false;
16340            }
16341
16342            removeCodePathLI(codeFile);
16343
16344            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16345                resourceFile.delete();
16346            }
16347
16348            return true;
16349        }
16350
16351        void cleanUpResourcesLI() {
16352            // Try enumerating all code paths before deleting
16353            List<String> allCodePaths = Collections.EMPTY_LIST;
16354            if (codeFile != null && codeFile.exists()) {
16355                try {
16356                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16357                    allCodePaths = pkg.getAllCodePaths();
16358                } catch (PackageParserException e) {
16359                    // Ignored; we tried our best
16360                }
16361            }
16362
16363            cleanUp();
16364            removeDexFiles(allCodePaths, instructionSets);
16365        }
16366
16367        boolean doPostDeleteLI(boolean delete) {
16368            // XXX err, shouldn't we respect the delete flag?
16369            cleanUpResourcesLI();
16370            return true;
16371        }
16372    }
16373
16374    private boolean isAsecExternal(String cid) {
16375        final String asecPath = PackageHelper.getSdFilesystem(cid);
16376        return !asecPath.startsWith(mAsecInternalPath);
16377    }
16378
16379    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16380            PackageManagerException {
16381        if (copyRet < 0) {
16382            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16383                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16384                throw new PackageManagerException(copyRet, message);
16385            }
16386        }
16387    }
16388
16389    /**
16390     * Extract the StorageManagerService "container ID" from the full code path of an
16391     * .apk.
16392     */
16393    static String cidFromCodePath(String fullCodePath) {
16394        int eidx = fullCodePath.lastIndexOf("/");
16395        String subStr1 = fullCodePath.substring(0, eidx);
16396        int sidx = subStr1.lastIndexOf("/");
16397        return subStr1.substring(sidx+1, eidx);
16398    }
16399
16400    /**
16401     * Logic to handle installation of ASEC applications, including copying and
16402     * renaming logic.
16403     */
16404    class AsecInstallArgs extends InstallArgs {
16405        static final String RES_FILE_NAME = "pkg.apk";
16406        static final String PUBLIC_RES_FILE_NAME = "res.zip";
16407
16408        String cid;
16409        String packagePath;
16410        String resourcePath;
16411
16412        /** New install */
16413        AsecInstallArgs(InstallParams params) {
16414            super(params.origin, params.move, params.observer, params.installFlags,
16415                    params.installerPackageName, params.volumeUuid,
16416                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16417                    params.grantedRuntimePermissions,
16418                    params.traceMethod, params.traceCookie, params.certificates,
16419                    params.installReason);
16420        }
16421
16422        /** Existing install */
16423        AsecInstallArgs(String fullCodePath, String[] instructionSets,
16424                        boolean isExternal, boolean isForwardLocked) {
16425            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
16426                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16427                    instructionSets, null, null, null, 0, null /*certificates*/,
16428                    PackageManager.INSTALL_REASON_UNKNOWN);
16429            // Hackily pretend we're still looking at a full code path
16430            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
16431                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
16432            }
16433
16434            // Extract cid from fullCodePath
16435            int eidx = fullCodePath.lastIndexOf("/");
16436            String subStr1 = fullCodePath.substring(0, eidx);
16437            int sidx = subStr1.lastIndexOf("/");
16438            cid = subStr1.substring(sidx+1, eidx);
16439            setMountPath(subStr1);
16440        }
16441
16442        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
16443            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
16444                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16445                    instructionSets, null, null, null, 0, null /*certificates*/,
16446                    PackageManager.INSTALL_REASON_UNKNOWN);
16447            this.cid = cid;
16448            setMountPath(PackageHelper.getSdDir(cid));
16449        }
16450
16451        void createCopyFile() {
16452            cid = mInstallerService.allocateExternalStageCidLegacy();
16453        }
16454
16455        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16456            if (origin.staged && origin.cid != null) {
16457                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
16458                cid = origin.cid;
16459                setMountPath(PackageHelper.getSdDir(cid));
16460                return PackageManager.INSTALL_SUCCEEDED;
16461            }
16462
16463            if (temp) {
16464                createCopyFile();
16465            } else {
16466                /*
16467                 * Pre-emptively destroy the container since it's destroyed if
16468                 * copying fails due to it existing anyway.
16469                 */
16470                PackageHelper.destroySdDir(cid);
16471            }
16472
16473            final String newMountPath = imcs.copyPackageToContainer(
16474                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
16475                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
16476
16477            if (newMountPath != null) {
16478                setMountPath(newMountPath);
16479                return PackageManager.INSTALL_SUCCEEDED;
16480            } else {
16481                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16482            }
16483        }
16484
16485        @Override
16486        String getCodePath() {
16487            return packagePath;
16488        }
16489
16490        @Override
16491        String getResourcePath() {
16492            return resourcePath;
16493        }
16494
16495        int doPreInstall(int status) {
16496            if (status != PackageManager.INSTALL_SUCCEEDED) {
16497                // Destroy container
16498                PackageHelper.destroySdDir(cid);
16499            } else {
16500                boolean mounted = PackageHelper.isContainerMounted(cid);
16501                if (!mounted) {
16502                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
16503                            Process.SYSTEM_UID);
16504                    if (newMountPath != null) {
16505                        setMountPath(newMountPath);
16506                    } else {
16507                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16508                    }
16509                }
16510            }
16511            return status;
16512        }
16513
16514        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16515            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
16516            String newMountPath = null;
16517            if (PackageHelper.isContainerMounted(cid)) {
16518                // Unmount the container
16519                if (!PackageHelper.unMountSdDir(cid)) {
16520                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
16521                    return false;
16522                }
16523            }
16524            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16525                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
16526                        " which might be stale. Will try to clean up.");
16527                // Clean up the stale container and proceed to recreate.
16528                if (!PackageHelper.destroySdDir(newCacheId)) {
16529                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
16530                    return false;
16531                }
16532                // Successfully cleaned up stale container. Try to rename again.
16533                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16534                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
16535                            + " inspite of cleaning it up.");
16536                    return false;
16537                }
16538            }
16539            if (!PackageHelper.isContainerMounted(newCacheId)) {
16540                Slog.w(TAG, "Mounting container " + newCacheId);
16541                newMountPath = PackageHelper.mountSdDir(newCacheId,
16542                        getEncryptKey(), Process.SYSTEM_UID);
16543            } else {
16544                newMountPath = PackageHelper.getSdDir(newCacheId);
16545            }
16546            if (newMountPath == null) {
16547                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
16548                return false;
16549            }
16550            Log.i(TAG, "Succesfully renamed " + cid +
16551                    " to " + newCacheId +
16552                    " at new path: " + newMountPath);
16553            cid = newCacheId;
16554
16555            final File beforeCodeFile = new File(packagePath);
16556            setMountPath(newMountPath);
16557            final File afterCodeFile = new File(packagePath);
16558
16559            // Reflect the rename in scanned details
16560            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16561            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16562                    afterCodeFile, pkg.baseCodePath));
16563            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16564                    afterCodeFile, pkg.splitCodePaths));
16565
16566            // Reflect the rename in app info
16567            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16568            pkg.setApplicationInfoCodePath(pkg.codePath);
16569            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16570            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16571            pkg.setApplicationInfoResourcePath(pkg.codePath);
16572            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16573            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16574
16575            return true;
16576        }
16577
16578        private void setMountPath(String mountPath) {
16579            final File mountFile = new File(mountPath);
16580
16581            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
16582            if (monolithicFile.exists()) {
16583                packagePath = monolithicFile.getAbsolutePath();
16584                if (isFwdLocked()) {
16585                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
16586                } else {
16587                    resourcePath = packagePath;
16588                }
16589            } else {
16590                packagePath = mountFile.getAbsolutePath();
16591                resourcePath = packagePath;
16592            }
16593        }
16594
16595        int doPostInstall(int status, int uid) {
16596            if (status != PackageManager.INSTALL_SUCCEEDED) {
16597                cleanUp();
16598            } else {
16599                final int groupOwner;
16600                final String protectedFile;
16601                if (isFwdLocked()) {
16602                    groupOwner = UserHandle.getSharedAppGid(uid);
16603                    protectedFile = RES_FILE_NAME;
16604                } else {
16605                    groupOwner = -1;
16606                    protectedFile = null;
16607                }
16608
16609                if (uid < Process.FIRST_APPLICATION_UID
16610                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
16611                    Slog.e(TAG, "Failed to finalize " + cid);
16612                    PackageHelper.destroySdDir(cid);
16613                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16614                }
16615
16616                boolean mounted = PackageHelper.isContainerMounted(cid);
16617                if (!mounted) {
16618                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
16619                }
16620            }
16621            return status;
16622        }
16623
16624        private void cleanUp() {
16625            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
16626
16627            // Destroy secure container
16628            PackageHelper.destroySdDir(cid);
16629        }
16630
16631        private List<String> getAllCodePaths() {
16632            final File codeFile = new File(getCodePath());
16633            if (codeFile != null && codeFile.exists()) {
16634                try {
16635                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16636                    return pkg.getAllCodePaths();
16637                } catch (PackageParserException e) {
16638                    // Ignored; we tried our best
16639                }
16640            }
16641            return Collections.EMPTY_LIST;
16642        }
16643
16644        void cleanUpResourcesLI() {
16645            // Enumerate all code paths before deleting
16646            cleanUpResourcesLI(getAllCodePaths());
16647        }
16648
16649        private void cleanUpResourcesLI(List<String> allCodePaths) {
16650            cleanUp();
16651            removeDexFiles(allCodePaths, instructionSets);
16652        }
16653
16654        String getPackageName() {
16655            return getAsecPackageName(cid);
16656        }
16657
16658        boolean doPostDeleteLI(boolean delete) {
16659            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
16660            final List<String> allCodePaths = getAllCodePaths();
16661            boolean mounted = PackageHelper.isContainerMounted(cid);
16662            if (mounted) {
16663                // Unmount first
16664                if (PackageHelper.unMountSdDir(cid)) {
16665                    mounted = false;
16666                }
16667            }
16668            if (!mounted && delete) {
16669                cleanUpResourcesLI(allCodePaths);
16670            }
16671            return !mounted;
16672        }
16673
16674        @Override
16675        int doPreCopy() {
16676            if (isFwdLocked()) {
16677                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
16678                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
16679                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16680                }
16681            }
16682
16683            return PackageManager.INSTALL_SUCCEEDED;
16684        }
16685
16686        @Override
16687        int doPostCopy(int uid) {
16688            if (isFwdLocked()) {
16689                if (uid < Process.FIRST_APPLICATION_UID
16690                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
16691                                RES_FILE_NAME)) {
16692                    Slog.e(TAG, "Failed to finalize " + cid);
16693                    PackageHelper.destroySdDir(cid);
16694                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16695                }
16696            }
16697
16698            return PackageManager.INSTALL_SUCCEEDED;
16699        }
16700    }
16701
16702    /**
16703     * Logic to handle movement of existing installed applications.
16704     */
16705    class MoveInstallArgs extends InstallArgs {
16706        private File codeFile;
16707        private File resourceFile;
16708
16709        /** New install */
16710        MoveInstallArgs(InstallParams params) {
16711            super(params.origin, params.move, params.observer, params.installFlags,
16712                    params.installerPackageName, params.volumeUuid,
16713                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16714                    params.grantedRuntimePermissions,
16715                    params.traceMethod, params.traceCookie, params.certificates,
16716                    params.installReason);
16717        }
16718
16719        int copyApk(IMediaContainerService imcs, boolean temp) {
16720            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
16721                    + move.fromUuid + " to " + move.toUuid);
16722            synchronized (mInstaller) {
16723                try {
16724                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
16725                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
16726                } catch (InstallerException e) {
16727                    Slog.w(TAG, "Failed to move app", e);
16728                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16729                }
16730            }
16731
16732            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
16733            resourceFile = codeFile;
16734            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
16735
16736            return PackageManager.INSTALL_SUCCEEDED;
16737        }
16738
16739        int doPreInstall(int status) {
16740            if (status != PackageManager.INSTALL_SUCCEEDED) {
16741                cleanUp(move.toUuid);
16742            }
16743            return status;
16744        }
16745
16746        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16747            if (status != PackageManager.INSTALL_SUCCEEDED) {
16748                cleanUp(move.toUuid);
16749                return false;
16750            }
16751
16752            // Reflect the move in app info
16753            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16754            pkg.setApplicationInfoCodePath(pkg.codePath);
16755            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16756            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16757            pkg.setApplicationInfoResourcePath(pkg.codePath);
16758            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16759            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16760
16761            return true;
16762        }
16763
16764        int doPostInstall(int status, int uid) {
16765            if (status == PackageManager.INSTALL_SUCCEEDED) {
16766                cleanUp(move.fromUuid);
16767            } else {
16768                cleanUp(move.toUuid);
16769            }
16770            return status;
16771        }
16772
16773        @Override
16774        String getCodePath() {
16775            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16776        }
16777
16778        @Override
16779        String getResourcePath() {
16780            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16781        }
16782
16783        private boolean cleanUp(String volumeUuid) {
16784            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
16785                    move.dataAppName);
16786            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
16787            final int[] userIds = sUserManager.getUserIds();
16788            synchronized (mInstallLock) {
16789                // Clean up both app data and code
16790                // All package moves are frozen until finished
16791                for (int userId : userIds) {
16792                    try {
16793                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
16794                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
16795                    } catch (InstallerException e) {
16796                        Slog.w(TAG, String.valueOf(e));
16797                    }
16798                }
16799                removeCodePathLI(codeFile);
16800            }
16801            return true;
16802        }
16803
16804        void cleanUpResourcesLI() {
16805            throw new UnsupportedOperationException();
16806        }
16807
16808        boolean doPostDeleteLI(boolean delete) {
16809            throw new UnsupportedOperationException();
16810        }
16811    }
16812
16813    static String getAsecPackageName(String packageCid) {
16814        int idx = packageCid.lastIndexOf("-");
16815        if (idx == -1) {
16816            return packageCid;
16817        }
16818        return packageCid.substring(0, idx);
16819    }
16820
16821    // Utility method used to create code paths based on package name and available index.
16822    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16823        String idxStr = "";
16824        int idx = 1;
16825        // Fall back to default value of idx=1 if prefix is not
16826        // part of oldCodePath
16827        if (oldCodePath != null) {
16828            String subStr = oldCodePath;
16829            // Drop the suffix right away
16830            if (suffix != null && subStr.endsWith(suffix)) {
16831                subStr = subStr.substring(0, subStr.length() - suffix.length());
16832            }
16833            // If oldCodePath already contains prefix find out the
16834            // ending index to either increment or decrement.
16835            int sidx = subStr.lastIndexOf(prefix);
16836            if (sidx != -1) {
16837                subStr = subStr.substring(sidx + prefix.length());
16838                if (subStr != null) {
16839                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16840                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16841                    }
16842                    try {
16843                        idx = Integer.parseInt(subStr);
16844                        if (idx <= 1) {
16845                            idx++;
16846                        } else {
16847                            idx--;
16848                        }
16849                    } catch(NumberFormatException e) {
16850                    }
16851                }
16852            }
16853        }
16854        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16855        return prefix + idxStr;
16856    }
16857
16858    private File getNextCodePath(File targetDir, String packageName) {
16859        File result;
16860        SecureRandom random = new SecureRandom();
16861        byte[] bytes = new byte[16];
16862        do {
16863            random.nextBytes(bytes);
16864            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16865            result = new File(targetDir, packageName + "-" + suffix);
16866        } while (result.exists());
16867        return result;
16868    }
16869
16870    // Utility method that returns the relative package path with respect
16871    // to the installation directory. Like say for /data/data/com.test-1.apk
16872    // string com.test-1 is returned.
16873    static String deriveCodePathName(String codePath) {
16874        if (codePath == null) {
16875            return null;
16876        }
16877        final File codeFile = new File(codePath);
16878        final String name = codeFile.getName();
16879        if (codeFile.isDirectory()) {
16880            return name;
16881        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16882            final int lastDot = name.lastIndexOf('.');
16883            return name.substring(0, lastDot);
16884        } else {
16885            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16886            return null;
16887        }
16888    }
16889
16890    static class PackageInstalledInfo {
16891        String name;
16892        int uid;
16893        // The set of users that originally had this package installed.
16894        int[] origUsers;
16895        // The set of users that now have this package installed.
16896        int[] newUsers;
16897        PackageParser.Package pkg;
16898        int returnCode;
16899        String returnMsg;
16900        PackageRemovedInfo removedInfo;
16901        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
16902
16903        public void setError(int code, String msg) {
16904            setReturnCode(code);
16905            setReturnMessage(msg);
16906            Slog.w(TAG, msg);
16907        }
16908
16909        public void setError(String msg, PackageParserException e) {
16910            setReturnCode(e.error);
16911            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16912            Slog.w(TAG, msg, e);
16913        }
16914
16915        public void setError(String msg, PackageManagerException e) {
16916            returnCode = e.error;
16917            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16918            Slog.w(TAG, msg, e);
16919        }
16920
16921        public void setReturnCode(int returnCode) {
16922            this.returnCode = returnCode;
16923            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16924            for (int i = 0; i < childCount; i++) {
16925                addedChildPackages.valueAt(i).returnCode = returnCode;
16926            }
16927        }
16928
16929        private void setReturnMessage(String returnMsg) {
16930            this.returnMsg = returnMsg;
16931            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16932            for (int i = 0; i < childCount; i++) {
16933                addedChildPackages.valueAt(i).returnMsg = returnMsg;
16934            }
16935        }
16936
16937        // In some error cases we want to convey more info back to the observer
16938        String origPackage;
16939        String origPermission;
16940    }
16941
16942    /*
16943     * Install a non-existing package.
16944     */
16945    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
16946            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
16947            PackageInstalledInfo res, int installReason) {
16948        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
16949
16950        // Remember this for later, in case we need to rollback this install
16951        String pkgName = pkg.packageName;
16952
16953        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
16954
16955        synchronized(mPackages) {
16956            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
16957            if (renamedPackage != null) {
16958                // A package with the same name is already installed, though
16959                // it has been renamed to an older name.  The package we
16960                // are trying to install should be installed as an update to
16961                // the existing one, but that has not been requested, so bail.
16962                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16963                        + " without first uninstalling package running as "
16964                        + renamedPackage);
16965                return;
16966            }
16967            if (mPackages.containsKey(pkgName)) {
16968                // Don't allow installation over an existing package with the same name.
16969                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16970                        + " without first uninstalling.");
16971                return;
16972            }
16973        }
16974
16975        try {
16976            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
16977                    System.currentTimeMillis(), user);
16978
16979            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
16980
16981            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16982                prepareAppDataAfterInstallLIF(newPackage);
16983
16984            } else {
16985                // Remove package from internal structures, but keep around any
16986                // data that might have already existed
16987                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
16988                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
16989            }
16990        } catch (PackageManagerException e) {
16991            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16992        }
16993
16994        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16995    }
16996
16997    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
16998        // Can't rotate keys during boot or if sharedUser.
16999        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
17000                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
17001            return false;
17002        }
17003        // app is using upgradeKeySets; make sure all are valid
17004        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17005        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
17006        for (int i = 0; i < upgradeKeySets.length; i++) {
17007            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
17008                Slog.wtf(TAG, "Package "
17009                         + (oldPs.name != null ? oldPs.name : "<null>")
17010                         + " contains upgrade-key-set reference to unknown key-set: "
17011                         + upgradeKeySets[i]
17012                         + " reverting to signatures check.");
17013                return false;
17014            }
17015        }
17016        return true;
17017    }
17018
17019    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
17020        // Upgrade keysets are being used.  Determine if new package has a superset of the
17021        // required keys.
17022        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
17023        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17024        for (int i = 0; i < upgradeKeySets.length; i++) {
17025            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
17026            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
17027                return true;
17028            }
17029        }
17030        return false;
17031    }
17032
17033    private static void updateDigest(MessageDigest digest, File file) throws IOException {
17034        try (DigestInputStream digestStream =
17035                new DigestInputStream(new FileInputStream(file), digest)) {
17036            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
17037        }
17038    }
17039
17040    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
17041            UserHandle user, String installerPackageName, PackageInstalledInfo res,
17042            int installReason) {
17043        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17044
17045        final PackageParser.Package oldPackage;
17046        final PackageSetting ps;
17047        final String pkgName = pkg.packageName;
17048        final int[] allUsers;
17049        final int[] installedUsers;
17050
17051        synchronized(mPackages) {
17052            oldPackage = mPackages.get(pkgName);
17053            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
17054
17055            // don't allow upgrade to target a release SDK from a pre-release SDK
17056            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
17057                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17058            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
17059                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17060            if (oldTargetsPreRelease
17061                    && !newTargetsPreRelease
17062                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
17063                Slog.w(TAG, "Can't install package targeting released sdk");
17064                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
17065                return;
17066            }
17067
17068            ps = mSettings.mPackages.get(pkgName);
17069
17070            // verify signatures are valid
17071            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17072                if (!checkUpgradeKeySetLP(ps, pkg)) {
17073                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17074                            "New package not signed by keys specified by upgrade-keysets: "
17075                                    + pkgName);
17076                    return;
17077                }
17078            } else {
17079                // default to original signature matching
17080                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17081                        != PackageManager.SIGNATURE_MATCH) {
17082                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17083                            "New package has a different signature: " + pkgName);
17084                    return;
17085                }
17086            }
17087
17088            // don't allow a system upgrade unless the upgrade hash matches
17089            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17090                byte[] digestBytes = null;
17091                try {
17092                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17093                    updateDigest(digest, new File(pkg.baseCodePath));
17094                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17095                        for (String path : pkg.splitCodePaths) {
17096                            updateDigest(digest, new File(path));
17097                        }
17098                    }
17099                    digestBytes = digest.digest();
17100                } catch (NoSuchAlgorithmException | IOException e) {
17101                    res.setError(INSTALL_FAILED_INVALID_APK,
17102                            "Could not compute hash: " + pkgName);
17103                    return;
17104                }
17105                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17106                    res.setError(INSTALL_FAILED_INVALID_APK,
17107                            "New package fails restrict-update check: " + pkgName);
17108                    return;
17109                }
17110                // retain upgrade restriction
17111                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17112            }
17113
17114            // Check for shared user id changes
17115            String invalidPackageName =
17116                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17117            if (invalidPackageName != null) {
17118                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17119                        "Package " + invalidPackageName + " tried to change user "
17120                                + oldPackage.mSharedUserId);
17121                return;
17122            }
17123
17124            // In case of rollback, remember per-user/profile install state
17125            allUsers = sUserManager.getUserIds();
17126            installedUsers = ps.queryInstalledUsers(allUsers, true);
17127
17128            // don't allow an upgrade from full to ephemeral
17129            if (isInstantApp) {
17130                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17131                    for (int currentUser : allUsers) {
17132                        if (!ps.getInstantApp(currentUser)) {
17133                            // can't downgrade from full to instant
17134                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17135                                    + " for user: " + currentUser);
17136                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17137                            return;
17138                        }
17139                    }
17140                } else if (!ps.getInstantApp(user.getIdentifier())) {
17141                    // can't downgrade from full to instant
17142                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17143                            + " for user: " + user.getIdentifier());
17144                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17145                    return;
17146                }
17147            }
17148        }
17149
17150        // Update what is removed
17151        res.removedInfo = new PackageRemovedInfo(this);
17152        res.removedInfo.uid = oldPackage.applicationInfo.uid;
17153        res.removedInfo.removedPackage = oldPackage.packageName;
17154        res.removedInfo.installerPackageName = ps.installerPackageName;
17155        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17156        res.removedInfo.isUpdate = true;
17157        res.removedInfo.origUsers = installedUsers;
17158        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17159        for (int i = 0; i < installedUsers.length; i++) {
17160            final int userId = installedUsers[i];
17161            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17162        }
17163
17164        final int childCount = (oldPackage.childPackages != null)
17165                ? oldPackage.childPackages.size() : 0;
17166        for (int i = 0; i < childCount; i++) {
17167            boolean childPackageUpdated = false;
17168            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17169            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17170            if (res.addedChildPackages != null) {
17171                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17172                if (childRes != null) {
17173                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17174                    childRes.removedInfo.removedPackage = childPkg.packageName;
17175                    if (childPs != null) {
17176                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17177                    }
17178                    childRes.removedInfo.isUpdate = true;
17179                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17180                    childPackageUpdated = true;
17181                }
17182            }
17183            if (!childPackageUpdated) {
17184                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17185                childRemovedRes.removedPackage = childPkg.packageName;
17186                if (childPs != null) {
17187                    childRemovedRes.installerPackageName = childPs.installerPackageName;
17188                }
17189                childRemovedRes.isUpdate = false;
17190                childRemovedRes.dataRemoved = true;
17191                synchronized (mPackages) {
17192                    if (childPs != null) {
17193                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17194                    }
17195                }
17196                if (res.removedInfo.removedChildPackages == null) {
17197                    res.removedInfo.removedChildPackages = new ArrayMap<>();
17198                }
17199                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17200            }
17201        }
17202
17203        boolean sysPkg = (isSystemApp(oldPackage));
17204        if (sysPkg) {
17205            // Set the system/privileged flags as needed
17206            final boolean privileged =
17207                    (oldPackage.applicationInfo.privateFlags
17208                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17209            final int systemPolicyFlags = policyFlags
17210                    | PackageParser.PARSE_IS_SYSTEM
17211                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
17212
17213            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17214                    user, allUsers, installerPackageName, res, installReason);
17215        } else {
17216            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17217                    user, allUsers, installerPackageName, res, installReason);
17218        }
17219    }
17220
17221    @Override
17222    public List<String> getPreviousCodePaths(String packageName) {
17223        final int callingUid = Binder.getCallingUid();
17224        final List<String> result = new ArrayList<>();
17225        if (getInstantAppPackageName(callingUid) != null) {
17226            return result;
17227        }
17228        final PackageSetting ps = mSettings.mPackages.get(packageName);
17229        if (ps != null
17230                && ps.oldCodePaths != null
17231                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17232            result.addAll(ps.oldCodePaths);
17233        }
17234        return result;
17235    }
17236
17237    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17238            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17239            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17240            int installReason) {
17241        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17242                + deletedPackage);
17243
17244        String pkgName = deletedPackage.packageName;
17245        boolean deletedPkg = true;
17246        boolean addedPkg = false;
17247        boolean updatedSettings = false;
17248        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17249        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17250                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17251
17252        final long origUpdateTime = (pkg.mExtras != null)
17253                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17254
17255        // First delete the existing package while retaining the data directory
17256        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17257                res.removedInfo, true, pkg)) {
17258            // If the existing package wasn't successfully deleted
17259            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17260            deletedPkg = false;
17261        } else {
17262            // Successfully deleted the old package; proceed with replace.
17263
17264            // If deleted package lived in a container, give users a chance to
17265            // relinquish resources before killing.
17266            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17267                if (DEBUG_INSTALL) {
17268                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17269                }
17270                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17271                final ArrayList<String> pkgList = new ArrayList<String>(1);
17272                pkgList.add(deletedPackage.applicationInfo.packageName);
17273                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17274            }
17275
17276            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17277                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17278            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17279
17280            try {
17281                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17282                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17283                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17284                        installReason);
17285
17286                // Update the in-memory copy of the previous code paths.
17287                PackageSetting ps = mSettings.mPackages.get(pkgName);
17288                if (!killApp) {
17289                    if (ps.oldCodePaths == null) {
17290                        ps.oldCodePaths = new ArraySet<>();
17291                    }
17292                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17293                    if (deletedPackage.splitCodePaths != null) {
17294                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17295                    }
17296                } else {
17297                    ps.oldCodePaths = null;
17298                }
17299                if (ps.childPackageNames != null) {
17300                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17301                        final String childPkgName = ps.childPackageNames.get(i);
17302                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17303                        childPs.oldCodePaths = ps.oldCodePaths;
17304                    }
17305                }
17306                // set instant app status, but, only if it's explicitly specified
17307                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17308                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17309                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17310                prepareAppDataAfterInstallLIF(newPackage);
17311                addedPkg = true;
17312                mDexManager.notifyPackageUpdated(newPackage.packageName,
17313                        newPackage.baseCodePath, newPackage.splitCodePaths);
17314            } catch (PackageManagerException e) {
17315                res.setError("Package couldn't be installed in " + pkg.codePath, e);
17316            }
17317        }
17318
17319        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17320            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17321
17322            // Revert all internal state mutations and added folders for the failed install
17323            if (addedPkg) {
17324                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17325                        res.removedInfo, true, null);
17326            }
17327
17328            // Restore the old package
17329            if (deletedPkg) {
17330                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17331                File restoreFile = new File(deletedPackage.codePath);
17332                // Parse old package
17333                boolean oldExternal = isExternal(deletedPackage);
17334                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
17335                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17336                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17337                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17338                try {
17339                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17340                            null);
17341                } catch (PackageManagerException e) {
17342                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17343                            + e.getMessage());
17344                    return;
17345                }
17346
17347                synchronized (mPackages) {
17348                    // Ensure the installer package name up to date
17349                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17350
17351                    // Update permissions for restored package
17352                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17353
17354                    mSettings.writeLPr();
17355                }
17356
17357                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17358            }
17359        } else {
17360            synchronized (mPackages) {
17361                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17362                if (ps != null) {
17363                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17364                    if (res.removedInfo.removedChildPackages != null) {
17365                        final int childCount = res.removedInfo.removedChildPackages.size();
17366                        // Iterate in reverse as we may modify the collection
17367                        for (int i = childCount - 1; i >= 0; i--) {
17368                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17369                            if (res.addedChildPackages.containsKey(childPackageName)) {
17370                                res.removedInfo.removedChildPackages.removeAt(i);
17371                            } else {
17372                                PackageRemovedInfo childInfo = res.removedInfo
17373                                        .removedChildPackages.valueAt(i);
17374                                childInfo.removedForAllUsers = mPackages.get(
17375                                        childInfo.removedPackage) == null;
17376                            }
17377                        }
17378                    }
17379                }
17380            }
17381        }
17382    }
17383
17384    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
17385            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17386            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17387            int installReason) {
17388        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
17389                + ", old=" + deletedPackage);
17390
17391        final boolean disabledSystem;
17392
17393        // Remove existing system package
17394        removePackageLI(deletedPackage, true);
17395
17396        synchronized (mPackages) {
17397            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
17398        }
17399        if (!disabledSystem) {
17400            // We didn't need to disable the .apk as a current system package,
17401            // which means we are replacing another update that is already
17402            // installed.  We need to make sure to delete the older one's .apk.
17403            res.removedInfo.args = createInstallArgsForExisting(0,
17404                    deletedPackage.applicationInfo.getCodePath(),
17405                    deletedPackage.applicationInfo.getResourcePath(),
17406                    getAppDexInstructionSets(deletedPackage.applicationInfo));
17407        } else {
17408            res.removedInfo.args = null;
17409        }
17410
17411        // Successfully disabled the old package. Now proceed with re-installation
17412        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17413                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17414        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17415
17416        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17417        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
17418                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
17419
17420        PackageParser.Package newPackage = null;
17421        try {
17422            // Add the package to the internal data structures
17423            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
17424
17425            // Set the update and install times
17426            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
17427            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
17428                    System.currentTimeMillis());
17429
17430            // Update the package dynamic state if succeeded
17431            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17432                // Now that the install succeeded make sure we remove data
17433                // directories for any child package the update removed.
17434                final int deletedChildCount = (deletedPackage.childPackages != null)
17435                        ? deletedPackage.childPackages.size() : 0;
17436                final int newChildCount = (newPackage.childPackages != null)
17437                        ? newPackage.childPackages.size() : 0;
17438                for (int i = 0; i < deletedChildCount; i++) {
17439                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
17440                    boolean childPackageDeleted = true;
17441                    for (int j = 0; j < newChildCount; j++) {
17442                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
17443                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
17444                            childPackageDeleted = false;
17445                            break;
17446                        }
17447                    }
17448                    if (childPackageDeleted) {
17449                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
17450                                deletedChildPkg.packageName);
17451                        if (ps != null && res.removedInfo.removedChildPackages != null) {
17452                            PackageRemovedInfo removedChildRes = res.removedInfo
17453                                    .removedChildPackages.get(deletedChildPkg.packageName);
17454                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
17455                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
17456                        }
17457                    }
17458                }
17459
17460                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17461                        installReason);
17462                prepareAppDataAfterInstallLIF(newPackage);
17463
17464                mDexManager.notifyPackageUpdated(newPackage.packageName,
17465                            newPackage.baseCodePath, newPackage.splitCodePaths);
17466            }
17467        } catch (PackageManagerException e) {
17468            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
17469            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17470        }
17471
17472        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17473            // Re installation failed. Restore old information
17474            // Remove new pkg information
17475            if (newPackage != null) {
17476                removeInstalledPackageLI(newPackage, true);
17477            }
17478            // Add back the old system package
17479            try {
17480                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
17481            } catch (PackageManagerException e) {
17482                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
17483            }
17484
17485            synchronized (mPackages) {
17486                if (disabledSystem) {
17487                    enableSystemPackageLPw(deletedPackage);
17488                }
17489
17490                // Ensure the installer package name up to date
17491                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17492
17493                // Update permissions for restored package
17494                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17495
17496                mSettings.writeLPr();
17497            }
17498
17499            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
17500                    + " after failed upgrade");
17501        }
17502    }
17503
17504    /**
17505     * Checks whether the parent or any of the child packages have a change shared
17506     * user. For a package to be a valid update the shred users of the parent and
17507     * the children should match. We may later support changing child shared users.
17508     * @param oldPkg The updated package.
17509     * @param newPkg The update package.
17510     * @return The shared user that change between the versions.
17511     */
17512    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
17513            PackageParser.Package newPkg) {
17514        // Check parent shared user
17515        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
17516            return newPkg.packageName;
17517        }
17518        // Check child shared users
17519        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17520        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
17521        for (int i = 0; i < newChildCount; i++) {
17522            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
17523            // If this child was present, did it have the same shared user?
17524            for (int j = 0; j < oldChildCount; j++) {
17525                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
17526                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
17527                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
17528                    return newChildPkg.packageName;
17529                }
17530            }
17531        }
17532        return null;
17533    }
17534
17535    private void removeNativeBinariesLI(PackageSetting ps) {
17536        // Remove the lib path for the parent package
17537        if (ps != null) {
17538            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
17539            // Remove the lib path for the child packages
17540            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17541            for (int i = 0; i < childCount; i++) {
17542                PackageSetting childPs = null;
17543                synchronized (mPackages) {
17544                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17545                }
17546                if (childPs != null) {
17547                    NativeLibraryHelper.removeNativeBinariesLI(childPs
17548                            .legacyNativeLibraryPathString);
17549                }
17550            }
17551        }
17552    }
17553
17554    private void enableSystemPackageLPw(PackageParser.Package pkg) {
17555        // Enable the parent package
17556        mSettings.enableSystemPackageLPw(pkg.packageName);
17557        // Enable the child packages
17558        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17559        for (int i = 0; i < childCount; i++) {
17560            PackageParser.Package childPkg = pkg.childPackages.get(i);
17561            mSettings.enableSystemPackageLPw(childPkg.packageName);
17562        }
17563    }
17564
17565    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
17566            PackageParser.Package newPkg) {
17567        // Disable the parent package (parent always replaced)
17568        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
17569        // Disable the child packages
17570        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17571        for (int i = 0; i < childCount; i++) {
17572            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
17573            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
17574            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
17575        }
17576        return disabled;
17577    }
17578
17579    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
17580            String installerPackageName) {
17581        // Enable the parent package
17582        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
17583        // Enable the child packages
17584        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17585        for (int i = 0; i < childCount; i++) {
17586            PackageParser.Package childPkg = pkg.childPackages.get(i);
17587            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
17588        }
17589    }
17590
17591    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
17592        // Collect all used permissions in the UID
17593        ArraySet<String> usedPermissions = new ArraySet<>();
17594        final int packageCount = su.packages.size();
17595        for (int i = 0; i < packageCount; i++) {
17596            PackageSetting ps = su.packages.valueAt(i);
17597            if (ps.pkg == null) {
17598                continue;
17599            }
17600            final int requestedPermCount = ps.pkg.requestedPermissions.size();
17601            for (int j = 0; j < requestedPermCount; j++) {
17602                String permission = ps.pkg.requestedPermissions.get(j);
17603                BasePermission bp = mSettings.mPermissions.get(permission);
17604                if (bp != null) {
17605                    usedPermissions.add(permission);
17606                }
17607            }
17608        }
17609
17610        PermissionsState permissionsState = su.getPermissionsState();
17611        // Prune install permissions
17612        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
17613        final int installPermCount = installPermStates.size();
17614        for (int i = installPermCount - 1; i >= 0;  i--) {
17615            PermissionState permissionState = installPermStates.get(i);
17616            if (!usedPermissions.contains(permissionState.getName())) {
17617                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17618                if (bp != null) {
17619                    permissionsState.revokeInstallPermission(bp);
17620                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
17621                            PackageManager.MASK_PERMISSION_FLAGS, 0);
17622                }
17623            }
17624        }
17625
17626        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
17627
17628        // Prune runtime permissions
17629        for (int userId : allUserIds) {
17630            List<PermissionState> runtimePermStates = permissionsState
17631                    .getRuntimePermissionStates(userId);
17632            final int runtimePermCount = runtimePermStates.size();
17633            for (int i = runtimePermCount - 1; i >= 0; i--) {
17634                PermissionState permissionState = runtimePermStates.get(i);
17635                if (!usedPermissions.contains(permissionState.getName())) {
17636                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17637                    if (bp != null) {
17638                        permissionsState.revokeRuntimePermission(bp, userId);
17639                        permissionsState.updatePermissionFlags(bp, userId,
17640                                PackageManager.MASK_PERMISSION_FLAGS, 0);
17641                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
17642                                runtimePermissionChangedUserIds, userId);
17643                    }
17644                }
17645            }
17646        }
17647
17648        return runtimePermissionChangedUserIds;
17649    }
17650
17651    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
17652            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
17653        // Update the parent package setting
17654        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
17655                res, user, installReason);
17656        // Update the child packages setting
17657        final int childCount = (newPackage.childPackages != null)
17658                ? newPackage.childPackages.size() : 0;
17659        for (int i = 0; i < childCount; i++) {
17660            PackageParser.Package childPackage = newPackage.childPackages.get(i);
17661            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
17662            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
17663                    childRes.origUsers, childRes, user, installReason);
17664        }
17665    }
17666
17667    private void updateSettingsInternalLI(PackageParser.Package newPackage,
17668            String installerPackageName, int[] allUsers, int[] installedForUsers,
17669            PackageInstalledInfo res, UserHandle user, int installReason) {
17670        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
17671
17672        String pkgName = newPackage.packageName;
17673        synchronized (mPackages) {
17674            //write settings. the installStatus will be incomplete at this stage.
17675            //note that the new package setting would have already been
17676            //added to mPackages. It hasn't been persisted yet.
17677            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
17678            // TODO: Remove this write? It's also written at the end of this method
17679            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17680            mSettings.writeLPr();
17681            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17682        }
17683
17684        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
17685        synchronized (mPackages) {
17686            updatePermissionsLPw(newPackage.packageName, newPackage,
17687                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
17688                            ? UPDATE_PERMISSIONS_ALL : 0));
17689            // For system-bundled packages, we assume that installing an upgraded version
17690            // of the package implies that the user actually wants to run that new code,
17691            // so we enable the package.
17692            PackageSetting ps = mSettings.mPackages.get(pkgName);
17693            final int userId = user.getIdentifier();
17694            if (ps != null) {
17695                if (isSystemApp(newPackage)) {
17696                    if (DEBUG_INSTALL) {
17697                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
17698                    }
17699                    // Enable system package for requested users
17700                    if (res.origUsers != null) {
17701                        for (int origUserId : res.origUsers) {
17702                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
17703                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
17704                                        origUserId, installerPackageName);
17705                            }
17706                        }
17707                    }
17708                    // Also convey the prior install/uninstall state
17709                    if (allUsers != null && installedForUsers != null) {
17710                        for (int currentUserId : allUsers) {
17711                            final boolean installed = ArrayUtils.contains(
17712                                    installedForUsers, currentUserId);
17713                            if (DEBUG_INSTALL) {
17714                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
17715                            }
17716                            ps.setInstalled(installed, currentUserId);
17717                        }
17718                        // these install state changes will be persisted in the
17719                        // upcoming call to mSettings.writeLPr().
17720                    }
17721                }
17722                // It's implied that when a user requests installation, they want the app to be
17723                // installed and enabled.
17724                if (userId != UserHandle.USER_ALL) {
17725                    ps.setInstalled(true, userId);
17726                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
17727                }
17728
17729                // When replacing an existing package, preserve the original install reason for all
17730                // users that had the package installed before.
17731                final Set<Integer> previousUserIds = new ArraySet<>();
17732                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
17733                    final int installReasonCount = res.removedInfo.installReasons.size();
17734                    for (int i = 0; i < installReasonCount; i++) {
17735                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
17736                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
17737                        ps.setInstallReason(previousInstallReason, previousUserId);
17738                        previousUserIds.add(previousUserId);
17739                    }
17740                }
17741
17742                // Set install reason for users that are having the package newly installed.
17743                if (userId == UserHandle.USER_ALL) {
17744                    for (int currentUserId : sUserManager.getUserIds()) {
17745                        if (!previousUserIds.contains(currentUserId)) {
17746                            ps.setInstallReason(installReason, currentUserId);
17747                        }
17748                    }
17749                } else if (!previousUserIds.contains(userId)) {
17750                    ps.setInstallReason(installReason, userId);
17751                }
17752                mSettings.writeKernelMappingLPr(ps);
17753            }
17754            res.name = pkgName;
17755            res.uid = newPackage.applicationInfo.uid;
17756            res.pkg = newPackage;
17757            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
17758            mSettings.setInstallerPackageName(pkgName, installerPackageName);
17759            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17760            //to update install status
17761            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17762            mSettings.writeLPr();
17763            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17764        }
17765
17766        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17767    }
17768
17769    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
17770        try {
17771            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
17772            installPackageLI(args, res);
17773        } finally {
17774            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17775        }
17776    }
17777
17778    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
17779        final int installFlags = args.installFlags;
17780        final String installerPackageName = args.installerPackageName;
17781        final String volumeUuid = args.volumeUuid;
17782        final File tmpPackageFile = new File(args.getCodePath());
17783        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
17784        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
17785                || (args.volumeUuid != null));
17786        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
17787        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
17788        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
17789        boolean replace = false;
17790        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
17791        if (args.move != null) {
17792            // moving a complete application; perform an initial scan on the new install location
17793            scanFlags |= SCAN_INITIAL;
17794        }
17795        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
17796            scanFlags |= SCAN_DONT_KILL_APP;
17797        }
17798        if (instantApp) {
17799            scanFlags |= SCAN_AS_INSTANT_APP;
17800        }
17801        if (fullApp) {
17802            scanFlags |= SCAN_AS_FULL_APP;
17803        }
17804
17805        // Result object to be returned
17806        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17807
17808        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
17809
17810        // Sanity check
17811        if (instantApp && (forwardLocked || onExternal)) {
17812            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
17813                    + " external=" + onExternal);
17814            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17815            return;
17816        }
17817
17818        // Retrieve PackageSettings and parse package
17819        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
17820                | PackageParser.PARSE_ENFORCE_CODE
17821                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
17822                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
17823                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
17824                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
17825        PackageParser pp = new PackageParser();
17826        pp.setSeparateProcesses(mSeparateProcesses);
17827        pp.setDisplayMetrics(mMetrics);
17828        pp.setCallback(mPackageParserCallback);
17829
17830        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
17831        final PackageParser.Package pkg;
17832        try {
17833            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
17834        } catch (PackageParserException e) {
17835            res.setError("Failed parse during installPackageLI", e);
17836            return;
17837        } finally {
17838            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17839        }
17840
17841        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
17842        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
17843            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
17844            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17845                    "Instant app package must target O");
17846            return;
17847        }
17848        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
17849            Slog.w(TAG, "Instant app package " + pkg.packageName
17850                    + " does not target targetSandboxVersion 2");
17851            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17852                    "Instant app package must use targetSanboxVersion 2");
17853            return;
17854        }
17855
17856        if (pkg.applicationInfo.isStaticSharedLibrary()) {
17857            // Static shared libraries have synthetic package names
17858            renameStaticSharedLibraryPackage(pkg);
17859
17860            // No static shared libs on external storage
17861            if (onExternal) {
17862                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
17863                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17864                        "Packages declaring static-shared libs cannot be updated");
17865                return;
17866            }
17867        }
17868
17869        // If we are installing a clustered package add results for the children
17870        if (pkg.childPackages != null) {
17871            synchronized (mPackages) {
17872                final int childCount = pkg.childPackages.size();
17873                for (int i = 0; i < childCount; i++) {
17874                    PackageParser.Package childPkg = pkg.childPackages.get(i);
17875                    PackageInstalledInfo childRes = new PackageInstalledInfo();
17876                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17877                    childRes.pkg = childPkg;
17878                    childRes.name = childPkg.packageName;
17879                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17880                    if (childPs != null) {
17881                        childRes.origUsers = childPs.queryInstalledUsers(
17882                                sUserManager.getUserIds(), true);
17883                    }
17884                    if ((mPackages.containsKey(childPkg.packageName))) {
17885                        childRes.removedInfo = new PackageRemovedInfo(this);
17886                        childRes.removedInfo.removedPackage = childPkg.packageName;
17887                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17888                    }
17889                    if (res.addedChildPackages == null) {
17890                        res.addedChildPackages = new ArrayMap<>();
17891                    }
17892                    res.addedChildPackages.put(childPkg.packageName, childRes);
17893                }
17894            }
17895        }
17896
17897        // If package doesn't declare API override, mark that we have an install
17898        // time CPU ABI override.
17899        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
17900            pkg.cpuAbiOverride = args.abiOverride;
17901        }
17902
17903        String pkgName = res.name = pkg.packageName;
17904        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
17905            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
17906                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
17907                return;
17908            }
17909        }
17910
17911        try {
17912            // either use what we've been given or parse directly from the APK
17913            if (args.certificates != null) {
17914                try {
17915                    PackageParser.populateCertificates(pkg, args.certificates);
17916                } catch (PackageParserException e) {
17917                    // there was something wrong with the certificates we were given;
17918                    // try to pull them from the APK
17919                    PackageParser.collectCertificates(pkg, parseFlags);
17920                }
17921            } else {
17922                PackageParser.collectCertificates(pkg, parseFlags);
17923            }
17924        } catch (PackageParserException e) {
17925            res.setError("Failed collect during installPackageLI", e);
17926            return;
17927        }
17928
17929        // Get rid of all references to package scan path via parser.
17930        pp = null;
17931        String oldCodePath = null;
17932        boolean systemApp = false;
17933        synchronized (mPackages) {
17934            // Check if installing already existing package
17935            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
17936                String oldName = mSettings.getRenamedPackageLPr(pkgName);
17937                if (pkg.mOriginalPackages != null
17938                        && pkg.mOriginalPackages.contains(oldName)
17939                        && mPackages.containsKey(oldName)) {
17940                    // This package is derived from an original package,
17941                    // and this device has been updating from that original
17942                    // name.  We must continue using the original name, so
17943                    // rename the new package here.
17944                    pkg.setPackageName(oldName);
17945                    pkgName = pkg.packageName;
17946                    replace = true;
17947                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
17948                            + oldName + " pkgName=" + pkgName);
17949                } else if (mPackages.containsKey(pkgName)) {
17950                    // This package, under its official name, already exists
17951                    // on the device; we should replace it.
17952                    replace = true;
17953                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
17954                }
17955
17956                // Child packages are installed through the parent package
17957                if (pkg.parentPackage != null) {
17958                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17959                            "Package " + pkg.packageName + " is child of package "
17960                                    + pkg.parentPackage.parentPackage + ". Child packages "
17961                                    + "can be updated only through the parent package.");
17962                    return;
17963                }
17964
17965                if (replace) {
17966                    // Prevent apps opting out from runtime permissions
17967                    PackageParser.Package oldPackage = mPackages.get(pkgName);
17968                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
17969                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
17970                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
17971                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
17972                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
17973                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
17974                                        + " doesn't support runtime permissions but the old"
17975                                        + " target SDK " + oldTargetSdk + " does.");
17976                        return;
17977                    }
17978                    // Prevent apps from downgrading their targetSandbox.
17979                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
17980                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
17981                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
17982                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17983                                "Package " + pkg.packageName + " new target sandbox "
17984                                + newTargetSandbox + " is incompatible with the previous value of"
17985                                + oldTargetSandbox + ".");
17986                        return;
17987                    }
17988
17989                    // Prevent installing of child packages
17990                    if (oldPackage.parentPackage != null) {
17991                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17992                                "Package " + pkg.packageName + " is child of package "
17993                                        + oldPackage.parentPackage + ". Child packages "
17994                                        + "can be updated only through the parent package.");
17995                        return;
17996                    }
17997                }
17998            }
17999
18000            PackageSetting ps = mSettings.mPackages.get(pkgName);
18001            if (ps != null) {
18002                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
18003
18004                // Static shared libs have same package with different versions where
18005                // we internally use a synthetic package name to allow multiple versions
18006                // of the same package, therefore we need to compare signatures against
18007                // the package setting for the latest library version.
18008                PackageSetting signatureCheckPs = ps;
18009                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18010                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
18011                    if (libraryEntry != null) {
18012                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
18013                    }
18014                }
18015
18016                // Quick sanity check that we're signed correctly if updating;
18017                // we'll check this again later when scanning, but we want to
18018                // bail early here before tripping over redefined permissions.
18019                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
18020                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
18021                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
18022                                + pkg.packageName + " upgrade keys do not match the "
18023                                + "previously installed version");
18024                        return;
18025                    }
18026                } else {
18027                    try {
18028                        verifySignaturesLP(signatureCheckPs, pkg);
18029                    } catch (PackageManagerException e) {
18030                        res.setError(e.error, e.getMessage());
18031                        return;
18032                    }
18033                }
18034
18035                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
18036                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
18037                    systemApp = (ps.pkg.applicationInfo.flags &
18038                            ApplicationInfo.FLAG_SYSTEM) != 0;
18039                }
18040                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18041            }
18042
18043            int N = pkg.permissions.size();
18044            for (int i = N-1; i >= 0; i--) {
18045                PackageParser.Permission perm = pkg.permissions.get(i);
18046                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
18047
18048                // Don't allow anyone but the system to define ephemeral permissions.
18049                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
18050                        && !systemApp) {
18051                    Slog.w(TAG, "Non-System package " + pkg.packageName
18052                            + " attempting to delcare ephemeral permission "
18053                            + perm.info.name + "; Removing ephemeral.");
18054                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
18055                }
18056                // Check whether the newly-scanned package wants to define an already-defined perm
18057                if (bp != null) {
18058                    // If the defining package is signed with our cert, it's okay.  This
18059                    // also includes the "updating the same package" case, of course.
18060                    // "updating same package" could also involve key-rotation.
18061                    final boolean sigsOk;
18062                    if (bp.sourcePackage.equals(pkg.packageName)
18063                            && (bp.packageSetting instanceof PackageSetting)
18064                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
18065                                    scanFlags))) {
18066                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
18067                    } else {
18068                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
18069                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18070                    }
18071                    if (!sigsOk) {
18072                        // If the owning package is the system itself, we log but allow
18073                        // install to proceed; we fail the install on all other permission
18074                        // redefinitions.
18075                        if (!bp.sourcePackage.equals("android")) {
18076                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18077                                    + pkg.packageName + " attempting to redeclare permission "
18078                                    + perm.info.name + " already owned by " + bp.sourcePackage);
18079                            res.origPermission = perm.info.name;
18080                            res.origPackage = bp.sourcePackage;
18081                            return;
18082                        } else {
18083                            Slog.w(TAG, "Package " + pkg.packageName
18084                                    + " attempting to redeclare system permission "
18085                                    + perm.info.name + "; ignoring new declaration");
18086                            pkg.permissions.remove(i);
18087                        }
18088                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18089                        // Prevent apps to change protection level to dangerous from any other
18090                        // type as this would allow a privilege escalation where an app adds a
18091                        // normal/signature permission in other app's group and later redefines
18092                        // it as dangerous leading to the group auto-grant.
18093                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18094                                == PermissionInfo.PROTECTION_DANGEROUS) {
18095                            if (bp != null && !bp.isRuntime()) {
18096                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18097                                        + "non-runtime permission " + perm.info.name
18098                                        + " to runtime; keeping old protection level");
18099                                perm.info.protectionLevel = bp.protectionLevel;
18100                            }
18101                        }
18102                    }
18103                }
18104            }
18105        }
18106
18107        if (systemApp) {
18108            if (onExternal) {
18109                // Abort update; system app can't be replaced with app on sdcard
18110                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18111                        "Cannot install updates to system apps on sdcard");
18112                return;
18113            } else if (instantApp) {
18114                // Abort update; system app can't be replaced with an instant app
18115                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18116                        "Cannot update a system app with an instant app");
18117                return;
18118            }
18119        }
18120
18121        if (args.move != null) {
18122            // We did an in-place move, so dex is ready to roll
18123            scanFlags |= SCAN_NO_DEX;
18124            scanFlags |= SCAN_MOVE;
18125
18126            synchronized (mPackages) {
18127                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18128                if (ps == null) {
18129                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18130                            "Missing settings for moved package " + pkgName);
18131                }
18132
18133                // We moved the entire application as-is, so bring over the
18134                // previously derived ABI information.
18135                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18136                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18137            }
18138
18139        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18140            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18141            scanFlags |= SCAN_NO_DEX;
18142
18143            try {
18144                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18145                    args.abiOverride : pkg.cpuAbiOverride);
18146                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18147                        true /*extractLibs*/, mAppLib32InstallDir);
18148            } catch (PackageManagerException pme) {
18149                Slog.e(TAG, "Error deriving application ABI", pme);
18150                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18151                return;
18152            }
18153
18154            // Shared libraries for the package need to be updated.
18155            synchronized (mPackages) {
18156                try {
18157                    updateSharedLibrariesLPr(pkg, null);
18158                } catch (PackageManagerException e) {
18159                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18160                }
18161            }
18162
18163            // dexopt can take some time to complete, so, for instant apps, we skip this
18164            // step during installation. Instead, we'll take extra time the first time the
18165            // instant app starts. It's preferred to do it this way to provide continuous
18166            // progress to the user instead of mysteriously blocking somewhere in the
18167            // middle of running an instant app. The default behaviour can be overridden
18168            // via gservices.
18169            if (!instantApp || Global.getInt(
18170                        mContext.getContentResolver(), Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0) {
18171                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18172                // Do not run PackageDexOptimizer through the local performDexOpt
18173                // method because `pkg` may not be in `mPackages` yet.
18174                //
18175                // Also, don't fail application installs if the dexopt step fails.
18176                mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18177                        null /* instructionSets */, false /* checkProfiles */,
18178                        getCompilerFilterForReason(REASON_INSTALL),
18179                        getOrCreateCompilerPackageStats(pkg),
18180                        mDexManager.isUsedByOtherApps(pkg.packageName),
18181                        true /* bootComplete */);
18182                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18183            }
18184
18185            // Notify BackgroundDexOptService that the package has been changed.
18186            // If this is an update of a package which used to fail to compile,
18187            // BDOS will remove it from its blacklist.
18188            // TODO: Layering violation
18189            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18190        }
18191
18192        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18193            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18194            return;
18195        }
18196
18197        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18198
18199        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18200                "installPackageLI")) {
18201            if (replace) {
18202                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18203                    // Static libs have a synthetic package name containing the version
18204                    // and cannot be updated as an update would get a new package name,
18205                    // unless this is the exact same version code which is useful for
18206                    // development.
18207                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18208                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18209                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18210                                + "static-shared libs cannot be updated");
18211                        return;
18212                    }
18213                }
18214                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18215                        installerPackageName, res, args.installReason);
18216            } else {
18217                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18218                        args.user, installerPackageName, volumeUuid, res, args.installReason);
18219            }
18220        }
18221
18222        synchronized (mPackages) {
18223            final PackageSetting ps = mSettings.mPackages.get(pkgName);
18224            if (ps != null) {
18225                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18226                ps.setUpdateAvailable(false /*updateAvailable*/);
18227            }
18228
18229            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18230            for (int i = 0; i < childCount; i++) {
18231                PackageParser.Package childPkg = pkg.childPackages.get(i);
18232                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18233                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18234                if (childPs != null) {
18235                    childRes.newUsers = childPs.queryInstalledUsers(
18236                            sUserManager.getUserIds(), true);
18237                }
18238            }
18239
18240            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18241                updateSequenceNumberLP(ps, res.newUsers);
18242                updateInstantAppInstallerLocked(pkgName);
18243            }
18244        }
18245    }
18246
18247    private void startIntentFilterVerifications(int userId, boolean replacing,
18248            PackageParser.Package pkg) {
18249        if (mIntentFilterVerifierComponent == null) {
18250            Slog.w(TAG, "No IntentFilter verification will not be done as "
18251                    + "there is no IntentFilterVerifier available!");
18252            return;
18253        }
18254
18255        final int verifierUid = getPackageUid(
18256                mIntentFilterVerifierComponent.getPackageName(),
18257                MATCH_DEBUG_TRIAGED_MISSING,
18258                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18259
18260        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18261        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18262        mHandler.sendMessage(msg);
18263
18264        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18265        for (int i = 0; i < childCount; i++) {
18266            PackageParser.Package childPkg = pkg.childPackages.get(i);
18267            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18268            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18269            mHandler.sendMessage(msg);
18270        }
18271    }
18272
18273    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18274            PackageParser.Package pkg) {
18275        int size = pkg.activities.size();
18276        if (size == 0) {
18277            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18278                    "No activity, so no need to verify any IntentFilter!");
18279            return;
18280        }
18281
18282        final boolean hasDomainURLs = hasDomainURLs(pkg);
18283        if (!hasDomainURLs) {
18284            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18285                    "No domain URLs, so no need to verify any IntentFilter!");
18286            return;
18287        }
18288
18289        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18290                + " if any IntentFilter from the " + size
18291                + " Activities needs verification ...");
18292
18293        int count = 0;
18294        final String packageName = pkg.packageName;
18295
18296        synchronized (mPackages) {
18297            // If this is a new install and we see that we've already run verification for this
18298            // package, we have nothing to do: it means the state was restored from backup.
18299            if (!replacing) {
18300                IntentFilterVerificationInfo ivi =
18301                        mSettings.getIntentFilterVerificationLPr(packageName);
18302                if (ivi != null) {
18303                    if (DEBUG_DOMAIN_VERIFICATION) {
18304                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
18305                                + ivi.getStatusString());
18306                    }
18307                    return;
18308                }
18309            }
18310
18311            // If any filters need to be verified, then all need to be.
18312            boolean needToVerify = false;
18313            for (PackageParser.Activity a : pkg.activities) {
18314                for (ActivityIntentInfo filter : a.intents) {
18315                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18316                        if (DEBUG_DOMAIN_VERIFICATION) {
18317                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18318                        }
18319                        needToVerify = true;
18320                        break;
18321                    }
18322                }
18323            }
18324
18325            if (needToVerify) {
18326                final int verificationId = mIntentFilterVerificationToken++;
18327                for (PackageParser.Activity a : pkg.activities) {
18328                    for (ActivityIntentInfo filter : a.intents) {
18329                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
18330                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18331                                    "Verification needed for IntentFilter:" + filter.toString());
18332                            mIntentFilterVerifier.addOneIntentFilterVerification(
18333                                    verifierUid, userId, verificationId, filter, packageName);
18334                            count++;
18335                        }
18336                    }
18337                }
18338            }
18339        }
18340
18341        if (count > 0) {
18342            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
18343                    + " IntentFilter verification" + (count > 1 ? "s" : "")
18344                    +  " for userId:" + userId);
18345            mIntentFilterVerifier.startVerifications(userId);
18346        } else {
18347            if (DEBUG_DOMAIN_VERIFICATION) {
18348                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
18349            }
18350        }
18351    }
18352
18353    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
18354        final ComponentName cn  = filter.activity.getComponentName();
18355        final String packageName = cn.getPackageName();
18356
18357        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
18358                packageName);
18359        if (ivi == null) {
18360            return true;
18361        }
18362        int status = ivi.getStatus();
18363        switch (status) {
18364            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
18365            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
18366                return true;
18367
18368            default:
18369                // Nothing to do
18370                return false;
18371        }
18372    }
18373
18374    private static boolean isMultiArch(ApplicationInfo info) {
18375        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
18376    }
18377
18378    private static boolean isExternal(PackageParser.Package pkg) {
18379        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18380    }
18381
18382    private static boolean isExternal(PackageSetting ps) {
18383        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18384    }
18385
18386    private static boolean isSystemApp(PackageParser.Package pkg) {
18387        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
18388    }
18389
18390    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
18391        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
18392    }
18393
18394    private static boolean hasDomainURLs(PackageParser.Package pkg) {
18395        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
18396    }
18397
18398    private static boolean isSystemApp(PackageSetting ps) {
18399        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
18400    }
18401
18402    private static boolean isUpdatedSystemApp(PackageSetting ps) {
18403        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
18404    }
18405
18406    private int packageFlagsToInstallFlags(PackageSetting ps) {
18407        int installFlags = 0;
18408        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
18409            // This existing package was an external ASEC install when we have
18410            // the external flag without a UUID
18411            installFlags |= PackageManager.INSTALL_EXTERNAL;
18412        }
18413        if (ps.isForwardLocked()) {
18414            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
18415        }
18416        return installFlags;
18417    }
18418
18419    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
18420        if (isExternal(pkg)) {
18421            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18422                return StorageManager.UUID_PRIMARY_PHYSICAL;
18423            } else {
18424                return pkg.volumeUuid;
18425            }
18426        } else {
18427            return StorageManager.UUID_PRIVATE_INTERNAL;
18428        }
18429    }
18430
18431    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
18432        if (isExternal(pkg)) {
18433            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18434                return mSettings.getExternalVersion();
18435            } else {
18436                return mSettings.findOrCreateVersion(pkg.volumeUuid);
18437            }
18438        } else {
18439            return mSettings.getInternalVersion();
18440        }
18441    }
18442
18443    private void deleteTempPackageFiles() {
18444        final FilenameFilter filter = new FilenameFilter() {
18445            public boolean accept(File dir, String name) {
18446                return name.startsWith("vmdl") && name.endsWith(".tmp");
18447            }
18448        };
18449        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
18450            file.delete();
18451        }
18452    }
18453
18454    @Override
18455    public void deletePackageAsUser(String packageName, int versionCode,
18456            IPackageDeleteObserver observer, int userId, int flags) {
18457        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
18458                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
18459    }
18460
18461    @Override
18462    public void deletePackageVersioned(VersionedPackage versionedPackage,
18463            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
18464        final int callingUid = Binder.getCallingUid();
18465        mContext.enforceCallingOrSelfPermission(
18466                android.Manifest.permission.DELETE_PACKAGES, null);
18467        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
18468        Preconditions.checkNotNull(versionedPackage);
18469        Preconditions.checkNotNull(observer);
18470        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
18471                PackageManager.VERSION_CODE_HIGHEST,
18472                Integer.MAX_VALUE, "versionCode must be >= -1");
18473
18474        final String packageName = versionedPackage.getPackageName();
18475        final int versionCode = versionedPackage.getVersionCode();
18476        final String internalPackageName;
18477        synchronized (mPackages) {
18478            // Normalize package name to handle renamed packages and static libs
18479            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
18480                    versionedPackage.getVersionCode());
18481        }
18482
18483        final int uid = Binder.getCallingUid();
18484        if (!isOrphaned(internalPackageName)
18485                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
18486            try {
18487                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
18488                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
18489                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
18490                observer.onUserActionRequired(intent);
18491            } catch (RemoteException re) {
18492            }
18493            return;
18494        }
18495        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
18496        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
18497        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
18498            mContext.enforceCallingOrSelfPermission(
18499                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
18500                    "deletePackage for user " + userId);
18501        }
18502
18503        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
18504            try {
18505                observer.onPackageDeleted(packageName,
18506                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
18507            } catch (RemoteException re) {
18508            }
18509            return;
18510        }
18511
18512        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
18513            try {
18514                observer.onPackageDeleted(packageName,
18515                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
18516            } catch (RemoteException re) {
18517            }
18518            return;
18519        }
18520
18521        if (DEBUG_REMOVE) {
18522            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
18523                    + " deleteAllUsers: " + deleteAllUsers + " version="
18524                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
18525                    ? "VERSION_CODE_HIGHEST" : versionCode));
18526        }
18527        // Queue up an async operation since the package deletion may take a little while.
18528        mHandler.post(new Runnable() {
18529            public void run() {
18530                mHandler.removeCallbacks(this);
18531                int returnCode;
18532                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
18533                boolean doDeletePackage = true;
18534                if (ps != null) {
18535                    final boolean targetIsInstantApp =
18536                            ps.getInstantApp(UserHandle.getUserId(callingUid));
18537                    doDeletePackage = !targetIsInstantApp
18538                            || canViewInstantApps;
18539                }
18540                if (doDeletePackage) {
18541                    if (!deleteAllUsers) {
18542                        returnCode = deletePackageX(internalPackageName, versionCode,
18543                                userId, deleteFlags);
18544                    } else {
18545                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
18546                                internalPackageName, users);
18547                        // If nobody is blocking uninstall, proceed with delete for all users
18548                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
18549                            returnCode = deletePackageX(internalPackageName, versionCode,
18550                                    userId, deleteFlags);
18551                        } else {
18552                            // Otherwise uninstall individually for users with blockUninstalls=false
18553                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
18554                            for (int userId : users) {
18555                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
18556                                    returnCode = deletePackageX(internalPackageName, versionCode,
18557                                            userId, userFlags);
18558                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
18559                                        Slog.w(TAG, "Package delete failed for user " + userId
18560                                                + ", returnCode " + returnCode);
18561                                    }
18562                                }
18563                            }
18564                            // The app has only been marked uninstalled for certain users.
18565                            // We still need to report that delete was blocked
18566                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
18567                        }
18568                    }
18569                } else {
18570                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18571                }
18572                try {
18573                    observer.onPackageDeleted(packageName, returnCode, null);
18574                } catch (RemoteException e) {
18575                    Log.i(TAG, "Observer no longer exists.");
18576                } //end catch
18577            } //end run
18578        });
18579    }
18580
18581    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
18582        if (pkg.staticSharedLibName != null) {
18583            return pkg.manifestPackageName;
18584        }
18585        return pkg.packageName;
18586    }
18587
18588    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
18589        // Handle renamed packages
18590        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
18591        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
18592
18593        // Is this a static library?
18594        SparseArray<SharedLibraryEntry> versionedLib =
18595                mStaticLibsByDeclaringPackage.get(packageName);
18596        if (versionedLib == null || versionedLib.size() <= 0) {
18597            return packageName;
18598        }
18599
18600        // Figure out which lib versions the caller can see
18601        SparseIntArray versionsCallerCanSee = null;
18602        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
18603        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
18604                && callingAppId != Process.ROOT_UID) {
18605            versionsCallerCanSee = new SparseIntArray();
18606            String libName = versionedLib.valueAt(0).info.getName();
18607            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
18608            if (uidPackages != null) {
18609                for (String uidPackage : uidPackages) {
18610                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
18611                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
18612                    if (libIdx >= 0) {
18613                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
18614                        versionsCallerCanSee.append(libVersion, libVersion);
18615                    }
18616                }
18617            }
18618        }
18619
18620        // Caller can see nothing - done
18621        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
18622            return packageName;
18623        }
18624
18625        // Find the version the caller can see and the app version code
18626        SharedLibraryEntry highestVersion = null;
18627        final int versionCount = versionedLib.size();
18628        for (int i = 0; i < versionCount; i++) {
18629            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
18630            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
18631                    libEntry.info.getVersion()) < 0) {
18632                continue;
18633            }
18634            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
18635            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
18636                if (libVersionCode == versionCode) {
18637                    return libEntry.apk;
18638                }
18639            } else if (highestVersion == null) {
18640                highestVersion = libEntry;
18641            } else if (libVersionCode  > highestVersion.info
18642                    .getDeclaringPackage().getVersionCode()) {
18643                highestVersion = libEntry;
18644            }
18645        }
18646
18647        if (highestVersion != null) {
18648            return highestVersion.apk;
18649        }
18650
18651        return packageName;
18652    }
18653
18654    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
18655        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
18656              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
18657            return true;
18658        }
18659        final int callingUserId = UserHandle.getUserId(callingUid);
18660        // If the caller installed the pkgName, then allow it to silently uninstall.
18661        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
18662            return true;
18663        }
18664
18665        // Allow package verifier to silently uninstall.
18666        if (mRequiredVerifierPackage != null &&
18667                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
18668            return true;
18669        }
18670
18671        // Allow package uninstaller to silently uninstall.
18672        if (mRequiredUninstallerPackage != null &&
18673                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
18674            return true;
18675        }
18676
18677        // Allow storage manager to silently uninstall.
18678        if (mStorageManagerPackage != null &&
18679                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
18680            return true;
18681        }
18682
18683        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
18684        // uninstall for device owner provisioning.
18685        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
18686                == PERMISSION_GRANTED) {
18687            return true;
18688        }
18689
18690        return false;
18691    }
18692
18693    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
18694        int[] result = EMPTY_INT_ARRAY;
18695        for (int userId : userIds) {
18696            if (getBlockUninstallForUser(packageName, userId)) {
18697                result = ArrayUtils.appendInt(result, userId);
18698            }
18699        }
18700        return result;
18701    }
18702
18703    @Override
18704    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
18705        final int callingUid = Binder.getCallingUid();
18706        if (getInstantAppPackageName(callingUid) != null
18707                && !isCallerSameApp(packageName, callingUid)) {
18708            return false;
18709        }
18710        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
18711    }
18712
18713    private boolean isPackageDeviceAdmin(String packageName, int userId) {
18714        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
18715                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
18716        try {
18717            if (dpm != null) {
18718                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
18719                        /* callingUserOnly =*/ false);
18720                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
18721                        : deviceOwnerComponentName.getPackageName();
18722                // Does the package contains the device owner?
18723                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
18724                // this check is probably not needed, since DO should be registered as a device
18725                // admin on some user too. (Original bug for this: b/17657954)
18726                if (packageName.equals(deviceOwnerPackageName)) {
18727                    return true;
18728                }
18729                // Does it contain a device admin for any user?
18730                int[] users;
18731                if (userId == UserHandle.USER_ALL) {
18732                    users = sUserManager.getUserIds();
18733                } else {
18734                    users = new int[]{userId};
18735                }
18736                for (int i = 0; i < users.length; ++i) {
18737                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
18738                        return true;
18739                    }
18740                }
18741            }
18742        } catch (RemoteException e) {
18743        }
18744        return false;
18745    }
18746
18747    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
18748        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
18749    }
18750
18751    /**
18752     *  This method is an internal method that could be get invoked either
18753     *  to delete an installed package or to clean up a failed installation.
18754     *  After deleting an installed package, a broadcast is sent to notify any
18755     *  listeners that the package has been removed. For cleaning up a failed
18756     *  installation, the broadcast is not necessary since the package's
18757     *  installation wouldn't have sent the initial broadcast either
18758     *  The key steps in deleting a package are
18759     *  deleting the package information in internal structures like mPackages,
18760     *  deleting the packages base directories through installd
18761     *  updating mSettings to reflect current status
18762     *  persisting settings for later use
18763     *  sending a broadcast if necessary
18764     */
18765    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
18766        final PackageRemovedInfo info = new PackageRemovedInfo(this);
18767        final boolean res;
18768
18769        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
18770                ? UserHandle.USER_ALL : userId;
18771
18772        if (isPackageDeviceAdmin(packageName, removeUser)) {
18773            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
18774            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
18775        }
18776
18777        PackageSetting uninstalledPs = null;
18778        PackageParser.Package pkg = null;
18779
18780        // for the uninstall-updates case and restricted profiles, remember the per-
18781        // user handle installed state
18782        int[] allUsers;
18783        synchronized (mPackages) {
18784            uninstalledPs = mSettings.mPackages.get(packageName);
18785            if (uninstalledPs == null) {
18786                Slog.w(TAG, "Not removing non-existent package " + packageName);
18787                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18788            }
18789
18790            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18791                    && uninstalledPs.versionCode != versionCode) {
18792                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18793                        + uninstalledPs.versionCode + " != " + versionCode);
18794                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18795            }
18796
18797            // Static shared libs can be declared by any package, so let us not
18798            // allow removing a package if it provides a lib others depend on.
18799            pkg = mPackages.get(packageName);
18800
18801            allUsers = sUserManager.getUserIds();
18802
18803            if (pkg != null && pkg.staticSharedLibName != null) {
18804                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18805                        pkg.staticSharedLibVersion);
18806                if (libEntry != null) {
18807                    for (int currUserId : allUsers) {
18808                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
18809                            continue;
18810                        }
18811                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18812                                libEntry.info, 0, currUserId);
18813                        if (!ArrayUtils.isEmpty(libClientPackages)) {
18814                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18815                                    + " hosting lib " + libEntry.info.getName() + " version "
18816                                    + libEntry.info.getVersion() + " used by " + libClientPackages
18817                                    + " for user " + currUserId);
18818                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18819                        }
18820                    }
18821                }
18822            }
18823
18824            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18825        }
18826
18827        final int freezeUser;
18828        if (isUpdatedSystemApp(uninstalledPs)
18829                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18830            // We're downgrading a system app, which will apply to all users, so
18831            // freeze them all during the downgrade
18832            freezeUser = UserHandle.USER_ALL;
18833        } else {
18834            freezeUser = removeUser;
18835        }
18836
18837        synchronized (mInstallLock) {
18838            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18839            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18840                    deleteFlags, "deletePackageX")) {
18841                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18842                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
18843            }
18844            synchronized (mPackages) {
18845                if (res) {
18846                    if (pkg != null) {
18847                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18848                    }
18849                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
18850                    updateInstantAppInstallerLocked(packageName);
18851                }
18852            }
18853        }
18854
18855        if (res) {
18856            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18857            info.sendPackageRemovedBroadcasts(killApp);
18858            info.sendSystemPackageUpdatedBroadcasts();
18859            info.sendSystemPackageAppearedBroadcasts();
18860        }
18861        // Force a gc here.
18862        Runtime.getRuntime().gc();
18863        // Delete the resources here after sending the broadcast to let
18864        // other processes clean up before deleting resources.
18865        if (info.args != null) {
18866            synchronized (mInstallLock) {
18867                info.args.doPostDeleteLI(true);
18868            }
18869        }
18870
18871        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18872    }
18873
18874    static class PackageRemovedInfo {
18875        final PackageSender packageSender;
18876        String removedPackage;
18877        String installerPackageName;
18878        int uid = -1;
18879        int removedAppId = -1;
18880        int[] origUsers;
18881        int[] removedUsers = null;
18882        int[] broadcastUsers = null;
18883        SparseArray<Integer> installReasons;
18884        boolean isRemovedPackageSystemUpdate = false;
18885        boolean isUpdate;
18886        boolean dataRemoved;
18887        boolean removedForAllUsers;
18888        boolean isStaticSharedLib;
18889        // Clean up resources deleted packages.
18890        InstallArgs args = null;
18891        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18892        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18893
18894        PackageRemovedInfo(PackageSender packageSender) {
18895            this.packageSender = packageSender;
18896        }
18897
18898        void sendPackageRemovedBroadcasts(boolean killApp) {
18899            sendPackageRemovedBroadcastInternal(killApp);
18900            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18901            for (int i = 0; i < childCount; i++) {
18902                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18903                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18904            }
18905        }
18906
18907        void sendSystemPackageUpdatedBroadcasts() {
18908            if (isRemovedPackageSystemUpdate) {
18909                sendSystemPackageUpdatedBroadcastsInternal();
18910                final int childCount = (removedChildPackages != null)
18911                        ? removedChildPackages.size() : 0;
18912                for (int i = 0; i < childCount; i++) {
18913                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18914                    if (childInfo.isRemovedPackageSystemUpdate) {
18915                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18916                    }
18917                }
18918            }
18919        }
18920
18921        void sendSystemPackageAppearedBroadcasts() {
18922            final int packageCount = (appearedChildPackages != null)
18923                    ? appearedChildPackages.size() : 0;
18924            for (int i = 0; i < packageCount; i++) {
18925                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18926                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18927                    true, UserHandle.getAppId(installedInfo.uid),
18928                    installedInfo.newUsers);
18929            }
18930        }
18931
18932        private void sendSystemPackageUpdatedBroadcastsInternal() {
18933            Bundle extras = new Bundle(2);
18934            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18935            extras.putBoolean(Intent.EXTRA_REPLACING, true);
18936            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18937                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18938            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18939                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18940            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
18941                null, null, 0, removedPackage, null, null);
18942            if (installerPackageName != null) {
18943                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18944                        removedPackage, extras, 0 /*flags*/,
18945                        installerPackageName, null, null);
18946                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18947                        removedPackage, extras, 0 /*flags*/,
18948                        installerPackageName, null, null);
18949            }
18950        }
18951
18952        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
18953            // Don't send static shared library removal broadcasts as these
18954            // libs are visible only the the apps that depend on them an one
18955            // cannot remove the library if it has a dependency.
18956            if (isStaticSharedLib) {
18957                return;
18958            }
18959            Bundle extras = new Bundle(2);
18960            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
18961            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18962            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18963            if (isUpdate || isRemovedPackageSystemUpdate) {
18964                extras.putBoolean(Intent.EXTRA_REPLACING, true);
18965            }
18966            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18967            if (removedPackage != null) {
18968                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18969                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
18970                if (installerPackageName != null) {
18971                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18972                            removedPackage, extras, 0 /*flags*/,
18973                            installerPackageName, null, broadcastUsers);
18974                }
18975                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18976                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18977                        removedPackage, extras,
18978                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18979                        null, null, broadcastUsers);
18980                }
18981            }
18982            if (removedAppId >= 0) {
18983                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
18984                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18985                    null, null, broadcastUsers);
18986            }
18987        }
18988
18989        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18990            removedUsers = userIds;
18991            if (removedUsers == null) {
18992                broadcastUsers = null;
18993                return;
18994            }
18995
18996            broadcastUsers = EMPTY_INT_ARRAY;
18997            for (int i = userIds.length - 1; i >= 0; --i) {
18998                final int userId = userIds[i];
18999                if (deletedPackageSetting.getInstantApp(userId)) {
19000                    continue;
19001                }
19002                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
19003            }
19004        }
19005    }
19006
19007    /*
19008     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
19009     * flag is not set, the data directory is removed as well.
19010     * make sure this flag is set for partially installed apps. If not its meaningless to
19011     * delete a partially installed application.
19012     */
19013    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
19014            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
19015        String packageName = ps.name;
19016        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
19017        // Retrieve object to delete permissions for shared user later on
19018        final PackageParser.Package deletedPkg;
19019        final PackageSetting deletedPs;
19020        // reader
19021        synchronized (mPackages) {
19022            deletedPkg = mPackages.get(packageName);
19023            deletedPs = mSettings.mPackages.get(packageName);
19024            if (outInfo != null) {
19025                outInfo.removedPackage = packageName;
19026                outInfo.installerPackageName = ps.installerPackageName;
19027                outInfo.isStaticSharedLib = deletedPkg != null
19028                        && deletedPkg.staticSharedLibName != null;
19029                outInfo.populateUsers(deletedPs == null ? null
19030                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
19031            }
19032        }
19033
19034        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
19035
19036        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
19037            final PackageParser.Package resolvedPkg;
19038            if (deletedPkg != null) {
19039                resolvedPkg = deletedPkg;
19040            } else {
19041                // We don't have a parsed package when it lives on an ejected
19042                // adopted storage device, so fake something together
19043                resolvedPkg = new PackageParser.Package(ps.name);
19044                resolvedPkg.setVolumeUuid(ps.volumeUuid);
19045            }
19046            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
19047                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19048            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
19049            if (outInfo != null) {
19050                outInfo.dataRemoved = true;
19051            }
19052            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
19053        }
19054
19055        int removedAppId = -1;
19056
19057        // writer
19058        synchronized (mPackages) {
19059            boolean installedStateChanged = false;
19060            if (deletedPs != null) {
19061                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
19062                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
19063                    clearDefaultBrowserIfNeeded(packageName);
19064                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
19065                    removedAppId = mSettings.removePackageLPw(packageName);
19066                    if (outInfo != null) {
19067                        outInfo.removedAppId = removedAppId;
19068                    }
19069                    updatePermissionsLPw(deletedPs.name, null, 0);
19070                    if (deletedPs.sharedUser != null) {
19071                        // Remove permissions associated with package. Since runtime
19072                        // permissions are per user we have to kill the removed package
19073                        // or packages running under the shared user of the removed
19074                        // package if revoking the permissions requested only by the removed
19075                        // package is successful and this causes a change in gids.
19076                        for (int userId : UserManagerService.getInstance().getUserIds()) {
19077                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19078                                    userId);
19079                            if (userIdToKill == UserHandle.USER_ALL
19080                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
19081                                // If gids changed for this user, kill all affected packages.
19082                                mHandler.post(new Runnable() {
19083                                    @Override
19084                                    public void run() {
19085                                        // This has to happen with no lock held.
19086                                        killApplication(deletedPs.name, deletedPs.appId,
19087                                                KILL_APP_REASON_GIDS_CHANGED);
19088                                    }
19089                                });
19090                                break;
19091                            }
19092                        }
19093                    }
19094                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19095                }
19096                // make sure to preserve per-user disabled state if this removal was just
19097                // a downgrade of a system app to the factory package
19098                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19099                    if (DEBUG_REMOVE) {
19100                        Slog.d(TAG, "Propagating install state across downgrade");
19101                    }
19102                    for (int userId : allUserHandles) {
19103                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19104                        if (DEBUG_REMOVE) {
19105                            Slog.d(TAG, "    user " + userId + " => " + installed);
19106                        }
19107                        if (installed != ps.getInstalled(userId)) {
19108                            installedStateChanged = true;
19109                        }
19110                        ps.setInstalled(installed, userId);
19111                    }
19112                }
19113            }
19114            // can downgrade to reader
19115            if (writeSettings) {
19116                // Save settings now
19117                mSettings.writeLPr();
19118            }
19119            if (installedStateChanged) {
19120                mSettings.writeKernelMappingLPr(ps);
19121            }
19122        }
19123        if (removedAppId != -1) {
19124            // A user ID was deleted here. Go through all users and remove it
19125            // from KeyStore.
19126            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19127        }
19128    }
19129
19130    static boolean locationIsPrivileged(File path) {
19131        try {
19132            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19133                    .getCanonicalPath();
19134            return path.getCanonicalPath().startsWith(privilegedAppDir);
19135        } catch (IOException e) {
19136            Slog.e(TAG, "Unable to access code path " + path);
19137        }
19138        return false;
19139    }
19140
19141    /*
19142     * Tries to delete system package.
19143     */
19144    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19145            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19146            boolean writeSettings) {
19147        if (deletedPs.parentPackageName != null) {
19148            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19149            return false;
19150        }
19151
19152        final boolean applyUserRestrictions
19153                = (allUserHandles != null) && (outInfo.origUsers != null);
19154        final PackageSetting disabledPs;
19155        // Confirm if the system package has been updated
19156        // An updated system app can be deleted. This will also have to restore
19157        // the system pkg from system partition
19158        // reader
19159        synchronized (mPackages) {
19160            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19161        }
19162
19163        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19164                + " disabledPs=" + disabledPs);
19165
19166        if (disabledPs == null) {
19167            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19168            return false;
19169        } else if (DEBUG_REMOVE) {
19170            Slog.d(TAG, "Deleting system pkg from data partition");
19171        }
19172
19173        if (DEBUG_REMOVE) {
19174            if (applyUserRestrictions) {
19175                Slog.d(TAG, "Remembering install states:");
19176                for (int userId : allUserHandles) {
19177                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19178                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
19179                }
19180            }
19181        }
19182
19183        // Delete the updated package
19184        outInfo.isRemovedPackageSystemUpdate = true;
19185        if (outInfo.removedChildPackages != null) {
19186            final int childCount = (deletedPs.childPackageNames != null)
19187                    ? deletedPs.childPackageNames.size() : 0;
19188            for (int i = 0; i < childCount; i++) {
19189                String childPackageName = deletedPs.childPackageNames.get(i);
19190                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19191                        .contains(childPackageName)) {
19192                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19193                            childPackageName);
19194                    if (childInfo != null) {
19195                        childInfo.isRemovedPackageSystemUpdate = true;
19196                    }
19197                }
19198            }
19199        }
19200
19201        if (disabledPs.versionCode < deletedPs.versionCode) {
19202            // Delete data for downgrades
19203            flags &= ~PackageManager.DELETE_KEEP_DATA;
19204        } else {
19205            // Preserve data by setting flag
19206            flags |= PackageManager.DELETE_KEEP_DATA;
19207        }
19208
19209        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19210                outInfo, writeSettings, disabledPs.pkg);
19211        if (!ret) {
19212            return false;
19213        }
19214
19215        // writer
19216        synchronized (mPackages) {
19217            // Reinstate the old system package
19218            enableSystemPackageLPw(disabledPs.pkg);
19219            // Remove any native libraries from the upgraded package.
19220            removeNativeBinariesLI(deletedPs);
19221        }
19222
19223        // Install the system package
19224        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19225        int parseFlags = mDefParseFlags
19226                | PackageParser.PARSE_MUST_BE_APK
19227                | PackageParser.PARSE_IS_SYSTEM
19228                | PackageParser.PARSE_IS_SYSTEM_DIR;
19229        if (locationIsPrivileged(disabledPs.codePath)) {
19230            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19231        }
19232
19233        final PackageParser.Package newPkg;
19234        try {
19235            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
19236                0 /* currentTime */, null);
19237        } catch (PackageManagerException e) {
19238            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19239                    + e.getMessage());
19240            return false;
19241        }
19242
19243        try {
19244            // update shared libraries for the newly re-installed system package
19245            updateSharedLibrariesLPr(newPkg, null);
19246        } catch (PackageManagerException e) {
19247            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19248        }
19249
19250        prepareAppDataAfterInstallLIF(newPkg);
19251
19252        // writer
19253        synchronized (mPackages) {
19254            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19255
19256            // Propagate the permissions state as we do not want to drop on the floor
19257            // runtime permissions. The update permissions method below will take
19258            // care of removing obsolete permissions and grant install permissions.
19259            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
19260            updatePermissionsLPw(newPkg.packageName, newPkg,
19261                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19262
19263            if (applyUserRestrictions) {
19264                boolean installedStateChanged = false;
19265                if (DEBUG_REMOVE) {
19266                    Slog.d(TAG, "Propagating install state across reinstall");
19267                }
19268                for (int userId : allUserHandles) {
19269                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19270                    if (DEBUG_REMOVE) {
19271                        Slog.d(TAG, "    user " + userId + " => " + installed);
19272                    }
19273                    if (installed != ps.getInstalled(userId)) {
19274                        installedStateChanged = true;
19275                    }
19276                    ps.setInstalled(installed, userId);
19277
19278                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19279                }
19280                // Regardless of writeSettings we need to ensure that this restriction
19281                // state propagation is persisted
19282                mSettings.writeAllUsersPackageRestrictionsLPr();
19283                if (installedStateChanged) {
19284                    mSettings.writeKernelMappingLPr(ps);
19285                }
19286            }
19287            // can downgrade to reader here
19288            if (writeSettings) {
19289                mSettings.writeLPr();
19290            }
19291        }
19292        return true;
19293    }
19294
19295    private boolean deleteInstalledPackageLIF(PackageSetting ps,
19296            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19297            PackageRemovedInfo outInfo, boolean writeSettings,
19298            PackageParser.Package replacingPackage) {
19299        synchronized (mPackages) {
19300            if (outInfo != null) {
19301                outInfo.uid = ps.appId;
19302            }
19303
19304            if (outInfo != null && outInfo.removedChildPackages != null) {
19305                final int childCount = (ps.childPackageNames != null)
19306                        ? ps.childPackageNames.size() : 0;
19307                for (int i = 0; i < childCount; i++) {
19308                    String childPackageName = ps.childPackageNames.get(i);
19309                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
19310                    if (childPs == null) {
19311                        return false;
19312                    }
19313                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19314                            childPackageName);
19315                    if (childInfo != null) {
19316                        childInfo.uid = childPs.appId;
19317                    }
19318                }
19319            }
19320        }
19321
19322        // Delete package data from internal structures and also remove data if flag is set
19323        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
19324
19325        // Delete the child packages data
19326        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
19327        for (int i = 0; i < childCount; i++) {
19328            PackageSetting childPs;
19329            synchronized (mPackages) {
19330                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
19331            }
19332            if (childPs != null) {
19333                PackageRemovedInfo childOutInfo = (outInfo != null
19334                        && outInfo.removedChildPackages != null)
19335                        ? outInfo.removedChildPackages.get(childPs.name) : null;
19336                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
19337                        && (replacingPackage != null
19338                        && !replacingPackage.hasChildPackage(childPs.name))
19339                        ? flags & ~DELETE_KEEP_DATA : flags;
19340                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
19341                        deleteFlags, writeSettings);
19342            }
19343        }
19344
19345        // Delete application code and resources only for parent packages
19346        if (ps.parentPackageName == null) {
19347            if (deleteCodeAndResources && (outInfo != null)) {
19348                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
19349                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
19350                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
19351            }
19352        }
19353
19354        return true;
19355    }
19356
19357    @Override
19358    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
19359            int userId) {
19360        mContext.enforceCallingOrSelfPermission(
19361                android.Manifest.permission.DELETE_PACKAGES, null);
19362        synchronized (mPackages) {
19363            // Cannot block uninstall of static shared libs as they are
19364            // considered a part of the using app (emulating static linking).
19365            // Also static libs are installed always on internal storage.
19366            PackageParser.Package pkg = mPackages.get(packageName);
19367            if (pkg != null && pkg.staticSharedLibName != null) {
19368                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
19369                        + " providing static shared library: " + pkg.staticSharedLibName);
19370                return false;
19371            }
19372            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
19373            mSettings.writePackageRestrictionsLPr(userId);
19374        }
19375        return true;
19376    }
19377
19378    @Override
19379    public boolean getBlockUninstallForUser(String packageName, int userId) {
19380        synchronized (mPackages) {
19381            final PackageSetting ps = mSettings.mPackages.get(packageName);
19382            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
19383                return false;
19384            }
19385            return mSettings.getBlockUninstallLPr(userId, packageName);
19386        }
19387    }
19388
19389    @Override
19390    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
19391        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
19392        synchronized (mPackages) {
19393            PackageSetting ps = mSettings.mPackages.get(packageName);
19394            if (ps == null) {
19395                Log.w(TAG, "Package doesn't exist: " + packageName);
19396                return false;
19397            }
19398            if (systemUserApp) {
19399                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19400            } else {
19401                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19402            }
19403            mSettings.writeLPr();
19404        }
19405        return true;
19406    }
19407
19408    /*
19409     * This method handles package deletion in general
19410     */
19411    private boolean deletePackageLIF(String packageName, UserHandle user,
19412            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
19413            PackageRemovedInfo outInfo, boolean writeSettings,
19414            PackageParser.Package replacingPackage) {
19415        if (packageName == null) {
19416            Slog.w(TAG, "Attempt to delete null packageName.");
19417            return false;
19418        }
19419
19420        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
19421
19422        PackageSetting ps;
19423        synchronized (mPackages) {
19424            ps = mSettings.mPackages.get(packageName);
19425            if (ps == null) {
19426                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19427                return false;
19428            }
19429
19430            if (ps.parentPackageName != null && (!isSystemApp(ps)
19431                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
19432                if (DEBUG_REMOVE) {
19433                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
19434                            + ((user == null) ? UserHandle.USER_ALL : user));
19435                }
19436                final int removedUserId = (user != null) ? user.getIdentifier()
19437                        : UserHandle.USER_ALL;
19438                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
19439                    return false;
19440                }
19441                markPackageUninstalledForUserLPw(ps, user);
19442                scheduleWritePackageRestrictionsLocked(user);
19443                return true;
19444            }
19445        }
19446
19447        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
19448                && user.getIdentifier() != UserHandle.USER_ALL)) {
19449            // The caller is asking that the package only be deleted for a single
19450            // user.  To do this, we just mark its uninstalled state and delete
19451            // its data. If this is a system app, we only allow this to happen if
19452            // they have set the special DELETE_SYSTEM_APP which requests different
19453            // semantics than normal for uninstalling system apps.
19454            markPackageUninstalledForUserLPw(ps, user);
19455
19456            if (!isSystemApp(ps)) {
19457                // Do not uninstall the APK if an app should be cached
19458                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
19459                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
19460                    // Other user still have this package installed, so all
19461                    // we need to do is clear this user's data and save that
19462                    // it is uninstalled.
19463                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
19464                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19465                        return false;
19466                    }
19467                    scheduleWritePackageRestrictionsLocked(user);
19468                    return true;
19469                } else {
19470                    // We need to set it back to 'installed' so the uninstall
19471                    // broadcasts will be sent correctly.
19472                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
19473                    ps.setInstalled(true, user.getIdentifier());
19474                    mSettings.writeKernelMappingLPr(ps);
19475                }
19476            } else {
19477                // This is a system app, so we assume that the
19478                // other users still have this package installed, so all
19479                // we need to do is clear this user's data and save that
19480                // it is uninstalled.
19481                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
19482                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19483                    return false;
19484                }
19485                scheduleWritePackageRestrictionsLocked(user);
19486                return true;
19487            }
19488        }
19489
19490        // If we are deleting a composite package for all users, keep track
19491        // of result for each child.
19492        if (ps.childPackageNames != null && outInfo != null) {
19493            synchronized (mPackages) {
19494                final int childCount = ps.childPackageNames.size();
19495                outInfo.removedChildPackages = new ArrayMap<>(childCount);
19496                for (int i = 0; i < childCount; i++) {
19497                    String childPackageName = ps.childPackageNames.get(i);
19498                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
19499                    childInfo.removedPackage = childPackageName;
19500                    childInfo.installerPackageName = ps.installerPackageName;
19501                    outInfo.removedChildPackages.put(childPackageName, childInfo);
19502                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19503                    if (childPs != null) {
19504                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
19505                    }
19506                }
19507            }
19508        }
19509
19510        boolean ret = false;
19511        if (isSystemApp(ps)) {
19512            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
19513            // When an updated system application is deleted we delete the existing resources
19514            // as well and fall back to existing code in system partition
19515            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
19516        } else {
19517            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
19518            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
19519                    outInfo, writeSettings, replacingPackage);
19520        }
19521
19522        // Take a note whether we deleted the package for all users
19523        if (outInfo != null) {
19524            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
19525            if (outInfo.removedChildPackages != null) {
19526                synchronized (mPackages) {
19527                    final int childCount = outInfo.removedChildPackages.size();
19528                    for (int i = 0; i < childCount; i++) {
19529                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
19530                        if (childInfo != null) {
19531                            childInfo.removedForAllUsers = mPackages.get(
19532                                    childInfo.removedPackage) == null;
19533                        }
19534                    }
19535                }
19536            }
19537            // If we uninstalled an update to a system app there may be some
19538            // child packages that appeared as they are declared in the system
19539            // app but were not declared in the update.
19540            if (isSystemApp(ps)) {
19541                synchronized (mPackages) {
19542                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
19543                    final int childCount = (updatedPs.childPackageNames != null)
19544                            ? updatedPs.childPackageNames.size() : 0;
19545                    for (int i = 0; i < childCount; i++) {
19546                        String childPackageName = updatedPs.childPackageNames.get(i);
19547                        if (outInfo.removedChildPackages == null
19548                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
19549                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19550                            if (childPs == null) {
19551                                continue;
19552                            }
19553                            PackageInstalledInfo installRes = new PackageInstalledInfo();
19554                            installRes.name = childPackageName;
19555                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
19556                            installRes.pkg = mPackages.get(childPackageName);
19557                            installRes.uid = childPs.pkg.applicationInfo.uid;
19558                            if (outInfo.appearedChildPackages == null) {
19559                                outInfo.appearedChildPackages = new ArrayMap<>();
19560                            }
19561                            outInfo.appearedChildPackages.put(childPackageName, installRes);
19562                        }
19563                    }
19564                }
19565            }
19566        }
19567
19568        return ret;
19569    }
19570
19571    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
19572        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
19573                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
19574        for (int nextUserId : userIds) {
19575            if (DEBUG_REMOVE) {
19576                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
19577            }
19578            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
19579                    false /*installed*/,
19580                    true /*stopped*/,
19581                    true /*notLaunched*/,
19582                    false /*hidden*/,
19583                    false /*suspended*/,
19584                    false /*instantApp*/,
19585                    null /*lastDisableAppCaller*/,
19586                    null /*enabledComponents*/,
19587                    null /*disabledComponents*/,
19588                    ps.readUserState(nextUserId).domainVerificationStatus,
19589                    0, PackageManager.INSTALL_REASON_UNKNOWN);
19590        }
19591        mSettings.writeKernelMappingLPr(ps);
19592    }
19593
19594    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
19595            PackageRemovedInfo outInfo) {
19596        final PackageParser.Package pkg;
19597        synchronized (mPackages) {
19598            pkg = mPackages.get(ps.name);
19599        }
19600
19601        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
19602                : new int[] {userId};
19603        for (int nextUserId : userIds) {
19604            if (DEBUG_REMOVE) {
19605                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
19606                        + nextUserId);
19607            }
19608
19609            destroyAppDataLIF(pkg, userId,
19610                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19611            destroyAppProfilesLIF(pkg, userId);
19612            clearDefaultBrowserIfNeededForUser(ps.name, userId);
19613            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
19614            schedulePackageCleaning(ps.name, nextUserId, false);
19615            synchronized (mPackages) {
19616                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
19617                    scheduleWritePackageRestrictionsLocked(nextUserId);
19618                }
19619                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
19620            }
19621        }
19622
19623        if (outInfo != null) {
19624            outInfo.removedPackage = ps.name;
19625            outInfo.installerPackageName = ps.installerPackageName;
19626            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
19627            outInfo.removedAppId = ps.appId;
19628            outInfo.removedUsers = userIds;
19629            outInfo.broadcastUsers = userIds;
19630        }
19631
19632        return true;
19633    }
19634
19635    private final class ClearStorageConnection implements ServiceConnection {
19636        IMediaContainerService mContainerService;
19637
19638        @Override
19639        public void onServiceConnected(ComponentName name, IBinder service) {
19640            synchronized (this) {
19641                mContainerService = IMediaContainerService.Stub
19642                        .asInterface(Binder.allowBlocking(service));
19643                notifyAll();
19644            }
19645        }
19646
19647        @Override
19648        public void onServiceDisconnected(ComponentName name) {
19649        }
19650    }
19651
19652    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
19653        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
19654
19655        final boolean mounted;
19656        if (Environment.isExternalStorageEmulated()) {
19657            mounted = true;
19658        } else {
19659            final String status = Environment.getExternalStorageState();
19660
19661            mounted = status.equals(Environment.MEDIA_MOUNTED)
19662                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
19663        }
19664
19665        if (!mounted) {
19666            return;
19667        }
19668
19669        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
19670        int[] users;
19671        if (userId == UserHandle.USER_ALL) {
19672            users = sUserManager.getUserIds();
19673        } else {
19674            users = new int[] { userId };
19675        }
19676        final ClearStorageConnection conn = new ClearStorageConnection();
19677        if (mContext.bindServiceAsUser(
19678                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
19679            try {
19680                for (int curUser : users) {
19681                    long timeout = SystemClock.uptimeMillis() + 5000;
19682                    synchronized (conn) {
19683                        long now;
19684                        while (conn.mContainerService == null &&
19685                                (now = SystemClock.uptimeMillis()) < timeout) {
19686                            try {
19687                                conn.wait(timeout - now);
19688                            } catch (InterruptedException e) {
19689                            }
19690                        }
19691                    }
19692                    if (conn.mContainerService == null) {
19693                        return;
19694                    }
19695
19696                    final UserEnvironment userEnv = new UserEnvironment(curUser);
19697                    clearDirectory(conn.mContainerService,
19698                            userEnv.buildExternalStorageAppCacheDirs(packageName));
19699                    if (allData) {
19700                        clearDirectory(conn.mContainerService,
19701                                userEnv.buildExternalStorageAppDataDirs(packageName));
19702                        clearDirectory(conn.mContainerService,
19703                                userEnv.buildExternalStorageAppMediaDirs(packageName));
19704                    }
19705                }
19706            } finally {
19707                mContext.unbindService(conn);
19708            }
19709        }
19710    }
19711
19712    @Override
19713    public void clearApplicationProfileData(String packageName) {
19714        enforceSystemOrRoot("Only the system can clear all profile data");
19715
19716        final PackageParser.Package pkg;
19717        synchronized (mPackages) {
19718            pkg = mPackages.get(packageName);
19719        }
19720
19721        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19722            synchronized (mInstallLock) {
19723                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19724            }
19725        }
19726    }
19727
19728    @Override
19729    public void clearApplicationUserData(final String packageName,
19730            final IPackageDataObserver observer, final int userId) {
19731        mContext.enforceCallingOrSelfPermission(
19732                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19733
19734        final int callingUid = Binder.getCallingUid();
19735        enforceCrossUserPermission(callingUid, userId,
19736                true /* requireFullPermission */, false /* checkShell */, "clear application data");
19737
19738        final PackageSetting ps = mSettings.getPackageLPr(packageName);
19739        if (ps != null && filterAppAccessLPr(ps, callingUid, userId)) {
19740            return;
19741        }
19742        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19743            throw new SecurityException("Cannot clear data for a protected package: "
19744                    + packageName);
19745        }
19746        // Queue up an async operation since the package deletion may take a little while.
19747        mHandler.post(new Runnable() {
19748            public void run() {
19749                mHandler.removeCallbacks(this);
19750                final boolean succeeded;
19751                try (PackageFreezer freezer = freezePackage(packageName,
19752                        "clearApplicationUserData")) {
19753                    synchronized (mInstallLock) {
19754                        succeeded = clearApplicationUserDataLIF(packageName, userId);
19755                    }
19756                    clearExternalStorageDataSync(packageName, userId, true);
19757                    synchronized (mPackages) {
19758                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19759                                packageName, userId);
19760                    }
19761                }
19762                if (succeeded) {
19763                    // invoke DeviceStorageMonitor's update method to clear any notifications
19764                    DeviceStorageMonitorInternal dsm = LocalServices
19765                            .getService(DeviceStorageMonitorInternal.class);
19766                    if (dsm != null) {
19767                        dsm.checkMemory();
19768                    }
19769                }
19770                if(observer != null) {
19771                    try {
19772                        observer.onRemoveCompleted(packageName, succeeded);
19773                    } catch (RemoteException e) {
19774                        Log.i(TAG, "Observer no longer exists.");
19775                    }
19776                } //end if observer
19777            } //end run
19778        });
19779    }
19780
19781    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19782        if (packageName == null) {
19783            Slog.w(TAG, "Attempt to delete null packageName.");
19784            return false;
19785        }
19786
19787        // Try finding details about the requested package
19788        PackageParser.Package pkg;
19789        synchronized (mPackages) {
19790            pkg = mPackages.get(packageName);
19791            if (pkg == null) {
19792                final PackageSetting ps = mSettings.mPackages.get(packageName);
19793                if (ps != null) {
19794                    pkg = ps.pkg;
19795                }
19796            }
19797
19798            if (pkg == null) {
19799                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19800                return false;
19801            }
19802
19803            PackageSetting ps = (PackageSetting) pkg.mExtras;
19804            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19805        }
19806
19807        clearAppDataLIF(pkg, userId,
19808                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19809
19810        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19811        removeKeystoreDataIfNeeded(userId, appId);
19812
19813        UserManagerInternal umInternal = getUserManagerInternal();
19814        final int flags;
19815        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19816            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19817        } else if (umInternal.isUserRunning(userId)) {
19818            flags = StorageManager.FLAG_STORAGE_DE;
19819        } else {
19820            flags = 0;
19821        }
19822        prepareAppDataContentsLIF(pkg, userId, flags);
19823
19824        return true;
19825    }
19826
19827    /**
19828     * Reverts user permission state changes (permissions and flags) in
19829     * all packages for a given user.
19830     *
19831     * @param userId The device user for which to do a reset.
19832     */
19833    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19834        final int packageCount = mPackages.size();
19835        for (int i = 0; i < packageCount; i++) {
19836            PackageParser.Package pkg = mPackages.valueAt(i);
19837            PackageSetting ps = (PackageSetting) pkg.mExtras;
19838            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19839        }
19840    }
19841
19842    private void resetNetworkPolicies(int userId) {
19843        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19844    }
19845
19846    /**
19847     * Reverts user permission state changes (permissions and flags).
19848     *
19849     * @param ps The package for which to reset.
19850     * @param userId The device user for which to do a reset.
19851     */
19852    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19853            final PackageSetting ps, final int userId) {
19854        if (ps.pkg == null) {
19855            return;
19856        }
19857
19858        // These are flags that can change base on user actions.
19859        final int userSettableMask = FLAG_PERMISSION_USER_SET
19860                | FLAG_PERMISSION_USER_FIXED
19861                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19862                | FLAG_PERMISSION_REVIEW_REQUIRED;
19863
19864        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19865                | FLAG_PERMISSION_POLICY_FIXED;
19866
19867        boolean writeInstallPermissions = false;
19868        boolean writeRuntimePermissions = false;
19869
19870        final int permissionCount = ps.pkg.requestedPermissions.size();
19871        for (int i = 0; i < permissionCount; i++) {
19872            String permission = ps.pkg.requestedPermissions.get(i);
19873
19874            BasePermission bp = mSettings.mPermissions.get(permission);
19875            if (bp == null) {
19876                continue;
19877            }
19878
19879            // If shared user we just reset the state to which only this app contributed.
19880            if (ps.sharedUser != null) {
19881                boolean used = false;
19882                final int packageCount = ps.sharedUser.packages.size();
19883                for (int j = 0; j < packageCount; j++) {
19884                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19885                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19886                            && pkg.pkg.requestedPermissions.contains(permission)) {
19887                        used = true;
19888                        break;
19889                    }
19890                }
19891                if (used) {
19892                    continue;
19893                }
19894            }
19895
19896            PermissionsState permissionsState = ps.getPermissionsState();
19897
19898            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
19899
19900            // Always clear the user settable flags.
19901            final boolean hasInstallState = permissionsState.getInstallPermissionState(
19902                    bp.name) != null;
19903            // If permission review is enabled and this is a legacy app, mark the
19904            // permission as requiring a review as this is the initial state.
19905            int flags = 0;
19906            if (mPermissionReviewRequired
19907                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19908                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19909            }
19910            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19911                if (hasInstallState) {
19912                    writeInstallPermissions = true;
19913                } else {
19914                    writeRuntimePermissions = true;
19915                }
19916            }
19917
19918            // Below is only runtime permission handling.
19919            if (!bp.isRuntime()) {
19920                continue;
19921            }
19922
19923            // Never clobber system or policy.
19924            if ((oldFlags & policyOrSystemFlags) != 0) {
19925                continue;
19926            }
19927
19928            // If this permission was granted by default, make sure it is.
19929            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19930                if (permissionsState.grantRuntimePermission(bp, userId)
19931                        != PERMISSION_OPERATION_FAILURE) {
19932                    writeRuntimePermissions = true;
19933                }
19934            // If permission review is enabled the permissions for a legacy apps
19935            // are represented as constantly granted runtime ones, so don't revoke.
19936            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19937                // Otherwise, reset the permission.
19938                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19939                switch (revokeResult) {
19940                    case PERMISSION_OPERATION_SUCCESS:
19941                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19942                        writeRuntimePermissions = true;
19943                        final int appId = ps.appId;
19944                        mHandler.post(new Runnable() {
19945                            @Override
19946                            public void run() {
19947                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19948                            }
19949                        });
19950                    } break;
19951                }
19952            }
19953        }
19954
19955        // Synchronously write as we are taking permissions away.
19956        if (writeRuntimePermissions) {
19957            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19958        }
19959
19960        // Synchronously write as we are taking permissions away.
19961        if (writeInstallPermissions) {
19962            mSettings.writeLPr();
19963        }
19964    }
19965
19966    /**
19967     * Remove entries from the keystore daemon. Will only remove it if the
19968     * {@code appId} is valid.
19969     */
19970    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19971        if (appId < 0) {
19972            return;
19973        }
19974
19975        final KeyStore keyStore = KeyStore.getInstance();
19976        if (keyStore != null) {
19977            if (userId == UserHandle.USER_ALL) {
19978                for (final int individual : sUserManager.getUserIds()) {
19979                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19980                }
19981            } else {
19982                keyStore.clearUid(UserHandle.getUid(userId, appId));
19983            }
19984        } else {
19985            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19986        }
19987    }
19988
19989    @Override
19990    public void deleteApplicationCacheFiles(final String packageName,
19991            final IPackageDataObserver observer) {
19992        final int userId = UserHandle.getCallingUserId();
19993        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19994    }
19995
19996    @Override
19997    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19998            final IPackageDataObserver observer) {
19999        final int callingUid = Binder.getCallingUid();
20000        mContext.enforceCallingOrSelfPermission(
20001                android.Manifest.permission.DELETE_CACHE_FILES, null);
20002        enforceCrossUserPermission(callingUid, userId,
20003                /* requireFullPermission= */ true, /* checkShell= */ false,
20004                "delete application cache files");
20005        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
20006                android.Manifest.permission.ACCESS_INSTANT_APPS);
20007
20008        final PackageParser.Package pkg;
20009        synchronized (mPackages) {
20010            pkg = mPackages.get(packageName);
20011        }
20012
20013        // Queue up an async operation since the package deletion may take a little while.
20014        mHandler.post(new Runnable() {
20015            public void run() {
20016                final PackageSetting ps = (PackageSetting) pkg.mExtras;
20017                boolean doClearData = true;
20018                if (ps != null) {
20019                    final boolean targetIsInstantApp =
20020                            ps.getInstantApp(UserHandle.getUserId(callingUid));
20021                    doClearData = !targetIsInstantApp
20022                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
20023                }
20024                if (doClearData) {
20025                    synchronized (mInstallLock) {
20026                        final int flags = StorageManager.FLAG_STORAGE_DE
20027                                | StorageManager.FLAG_STORAGE_CE;
20028                        // We're only clearing cache files, so we don't care if the
20029                        // app is unfrozen and still able to run
20030                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
20031                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20032                    }
20033                    clearExternalStorageDataSync(packageName, userId, false);
20034                }
20035                if (observer != null) {
20036                    try {
20037                        observer.onRemoveCompleted(packageName, true);
20038                    } catch (RemoteException e) {
20039                        Log.i(TAG, "Observer no longer exists.");
20040                    }
20041                }
20042            }
20043        });
20044    }
20045
20046    @Override
20047    public void getPackageSizeInfo(final String packageName, int userHandle,
20048            final IPackageStatsObserver observer) {
20049        throw new UnsupportedOperationException(
20050                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
20051    }
20052
20053    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
20054        final PackageSetting ps;
20055        synchronized (mPackages) {
20056            ps = mSettings.mPackages.get(packageName);
20057            if (ps == null) {
20058                Slog.w(TAG, "Failed to find settings for " + packageName);
20059                return false;
20060            }
20061        }
20062
20063        final String[] packageNames = { packageName };
20064        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
20065        final String[] codePaths = { ps.codePathString };
20066
20067        try {
20068            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20069                    ps.appId, ceDataInodes, codePaths, stats);
20070
20071            // For now, ignore code size of packages on system partition
20072            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20073                stats.codeSize = 0;
20074            }
20075
20076            // External clients expect these to be tracked separately
20077            stats.dataSize -= stats.cacheSize;
20078
20079        } catch (InstallerException e) {
20080            Slog.w(TAG, String.valueOf(e));
20081            return false;
20082        }
20083
20084        return true;
20085    }
20086
20087    private int getUidTargetSdkVersionLockedLPr(int uid) {
20088        Object obj = mSettings.getUserIdLPr(uid);
20089        if (obj instanceof SharedUserSetting) {
20090            final SharedUserSetting sus = (SharedUserSetting) obj;
20091            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20092            final Iterator<PackageSetting> it = sus.packages.iterator();
20093            while (it.hasNext()) {
20094                final PackageSetting ps = it.next();
20095                if (ps.pkg != null) {
20096                    int v = ps.pkg.applicationInfo.targetSdkVersion;
20097                    if (v < vers) vers = v;
20098                }
20099            }
20100            return vers;
20101        } else if (obj instanceof PackageSetting) {
20102            final PackageSetting ps = (PackageSetting) obj;
20103            if (ps.pkg != null) {
20104                return ps.pkg.applicationInfo.targetSdkVersion;
20105            }
20106        }
20107        return Build.VERSION_CODES.CUR_DEVELOPMENT;
20108    }
20109
20110    @Override
20111    public void addPreferredActivity(IntentFilter filter, int match,
20112            ComponentName[] set, ComponentName activity, int userId) {
20113        addPreferredActivityInternal(filter, match, set, activity, true, userId,
20114                "Adding preferred");
20115    }
20116
20117    private void addPreferredActivityInternal(IntentFilter filter, int match,
20118            ComponentName[] set, ComponentName activity, boolean always, int userId,
20119            String opname) {
20120        // writer
20121        int callingUid = Binder.getCallingUid();
20122        enforceCrossUserPermission(callingUid, userId,
20123                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20124        if (filter.countActions() == 0) {
20125            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20126            return;
20127        }
20128        synchronized (mPackages) {
20129            if (mContext.checkCallingOrSelfPermission(
20130                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20131                    != PackageManager.PERMISSION_GRANTED) {
20132                if (getUidTargetSdkVersionLockedLPr(callingUid)
20133                        < Build.VERSION_CODES.FROYO) {
20134                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20135                            + callingUid);
20136                    return;
20137                }
20138                mContext.enforceCallingOrSelfPermission(
20139                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20140            }
20141
20142            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20143            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20144                    + userId + ":");
20145            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20146            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20147            scheduleWritePackageRestrictionsLocked(userId);
20148            postPreferredActivityChangedBroadcast(userId);
20149        }
20150    }
20151
20152    private void postPreferredActivityChangedBroadcast(int userId) {
20153        mHandler.post(() -> {
20154            final IActivityManager am = ActivityManager.getService();
20155            if (am == null) {
20156                return;
20157            }
20158
20159            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20160            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20161            try {
20162                am.broadcastIntent(null, intent, null, null,
20163                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
20164                        null, false, false, userId);
20165            } catch (RemoteException e) {
20166            }
20167        });
20168    }
20169
20170    @Override
20171    public void replacePreferredActivity(IntentFilter filter, int match,
20172            ComponentName[] set, ComponentName activity, int userId) {
20173        if (filter.countActions() != 1) {
20174            throw new IllegalArgumentException(
20175                    "replacePreferredActivity expects filter to have only 1 action.");
20176        }
20177        if (filter.countDataAuthorities() != 0
20178                || filter.countDataPaths() != 0
20179                || filter.countDataSchemes() > 1
20180                || filter.countDataTypes() != 0) {
20181            throw new IllegalArgumentException(
20182                    "replacePreferredActivity expects filter to have no data authorities, " +
20183                    "paths, or types; and at most one scheme.");
20184        }
20185
20186        final int callingUid = Binder.getCallingUid();
20187        enforceCrossUserPermission(callingUid, userId,
20188                true /* requireFullPermission */, false /* checkShell */,
20189                "replace preferred activity");
20190        synchronized (mPackages) {
20191            if (mContext.checkCallingOrSelfPermission(
20192                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20193                    != PackageManager.PERMISSION_GRANTED) {
20194                if (getUidTargetSdkVersionLockedLPr(callingUid)
20195                        < Build.VERSION_CODES.FROYO) {
20196                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20197                            + Binder.getCallingUid());
20198                    return;
20199                }
20200                mContext.enforceCallingOrSelfPermission(
20201                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20202            }
20203
20204            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20205            if (pir != null) {
20206                // Get all of the existing entries that exactly match this filter.
20207                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20208                if (existing != null && existing.size() == 1) {
20209                    PreferredActivity cur = existing.get(0);
20210                    if (DEBUG_PREFERRED) {
20211                        Slog.i(TAG, "Checking replace of preferred:");
20212                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20213                        if (!cur.mPref.mAlways) {
20214                            Slog.i(TAG, "  -- CUR; not mAlways!");
20215                        } else {
20216                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
20217                            Slog.i(TAG, "  -- CUR: mSet="
20218                                    + Arrays.toString(cur.mPref.mSetComponents));
20219                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
20220                            Slog.i(TAG, "  -- NEW: mMatch="
20221                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
20222                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
20223                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
20224                        }
20225                    }
20226                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20227                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20228                            && cur.mPref.sameSet(set)) {
20229                        // Setting the preferred activity to what it happens to be already
20230                        if (DEBUG_PREFERRED) {
20231                            Slog.i(TAG, "Replacing with same preferred activity "
20232                                    + cur.mPref.mShortComponent + " for user "
20233                                    + userId + ":");
20234                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20235                        }
20236                        return;
20237                    }
20238                }
20239
20240                if (existing != null) {
20241                    if (DEBUG_PREFERRED) {
20242                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
20243                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20244                    }
20245                    for (int i = 0; i < existing.size(); i++) {
20246                        PreferredActivity pa = existing.get(i);
20247                        if (DEBUG_PREFERRED) {
20248                            Slog.i(TAG, "Removing existing preferred activity "
20249                                    + pa.mPref.mComponent + ":");
20250                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
20251                        }
20252                        pir.removeFilter(pa);
20253                    }
20254                }
20255            }
20256            addPreferredActivityInternal(filter, match, set, activity, true, userId,
20257                    "Replacing preferred");
20258        }
20259    }
20260
20261    @Override
20262    public void clearPackagePreferredActivities(String packageName) {
20263        final int callingUid = Binder.getCallingUid();
20264        if (getInstantAppPackageName(callingUid) != null) {
20265            return;
20266        }
20267        // writer
20268        synchronized (mPackages) {
20269            PackageParser.Package pkg = mPackages.get(packageName);
20270            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20271                if (mContext.checkCallingOrSelfPermission(
20272                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20273                        != PackageManager.PERMISSION_GRANTED) {
20274                    if (getUidTargetSdkVersionLockedLPr(callingUid)
20275                            < Build.VERSION_CODES.FROYO) {
20276                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20277                                + callingUid);
20278                        return;
20279                    }
20280                    mContext.enforceCallingOrSelfPermission(
20281                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20282                }
20283            }
20284            final PackageSetting ps = mSettings.getPackageLPr(packageName);
20285            if (ps != null
20286                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20287                return;
20288            }
20289            int user = UserHandle.getCallingUserId();
20290            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20291                scheduleWritePackageRestrictionsLocked(user);
20292            }
20293        }
20294    }
20295
20296    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20297    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
20298        ArrayList<PreferredActivity> removed = null;
20299        boolean changed = false;
20300        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20301            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
20302            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20303            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
20304                continue;
20305            }
20306            Iterator<PreferredActivity> it = pir.filterIterator();
20307            while (it.hasNext()) {
20308                PreferredActivity pa = it.next();
20309                // Mark entry for removal only if it matches the package name
20310                // and the entry is of type "always".
20311                if (packageName == null ||
20312                        (pa.mPref.mComponent.getPackageName().equals(packageName)
20313                                && pa.mPref.mAlways)) {
20314                    if (removed == null) {
20315                        removed = new ArrayList<PreferredActivity>();
20316                    }
20317                    removed.add(pa);
20318                }
20319            }
20320            if (removed != null) {
20321                for (int j=0; j<removed.size(); j++) {
20322                    PreferredActivity pa = removed.get(j);
20323                    pir.removeFilter(pa);
20324                }
20325                changed = true;
20326            }
20327        }
20328        if (changed) {
20329            postPreferredActivityChangedBroadcast(userId);
20330        }
20331        return changed;
20332    }
20333
20334    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20335    private void clearIntentFilterVerificationsLPw(int userId) {
20336        final int packageCount = mPackages.size();
20337        for (int i = 0; i < packageCount; i++) {
20338            PackageParser.Package pkg = mPackages.valueAt(i);
20339            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
20340        }
20341    }
20342
20343    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20344    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
20345        if (userId == UserHandle.USER_ALL) {
20346            if (mSettings.removeIntentFilterVerificationLPw(packageName,
20347                    sUserManager.getUserIds())) {
20348                for (int oneUserId : sUserManager.getUserIds()) {
20349                    scheduleWritePackageRestrictionsLocked(oneUserId);
20350                }
20351            }
20352        } else {
20353            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
20354                scheduleWritePackageRestrictionsLocked(userId);
20355            }
20356        }
20357    }
20358
20359    /** Clears state for all users, and touches intent filter verification policy */
20360    void clearDefaultBrowserIfNeeded(String packageName) {
20361        for (int oneUserId : sUserManager.getUserIds()) {
20362            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
20363        }
20364    }
20365
20366    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
20367        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
20368        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
20369            if (packageName.equals(defaultBrowserPackageName)) {
20370                setDefaultBrowserPackageName(null, userId);
20371            }
20372        }
20373    }
20374
20375    @Override
20376    public void resetApplicationPreferences(int userId) {
20377        mContext.enforceCallingOrSelfPermission(
20378                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20379        final long identity = Binder.clearCallingIdentity();
20380        // writer
20381        try {
20382            synchronized (mPackages) {
20383                clearPackagePreferredActivitiesLPw(null, userId);
20384                mSettings.applyDefaultPreferredAppsLPw(this, userId);
20385                // TODO: We have to reset the default SMS and Phone. This requires
20386                // significant refactoring to keep all default apps in the package
20387                // manager (cleaner but more work) or have the services provide
20388                // callbacks to the package manager to request a default app reset.
20389                applyFactoryDefaultBrowserLPw(userId);
20390                clearIntentFilterVerificationsLPw(userId);
20391                primeDomainVerificationsLPw(userId);
20392                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
20393                scheduleWritePackageRestrictionsLocked(userId);
20394            }
20395            resetNetworkPolicies(userId);
20396        } finally {
20397            Binder.restoreCallingIdentity(identity);
20398        }
20399    }
20400
20401    @Override
20402    public int getPreferredActivities(List<IntentFilter> outFilters,
20403            List<ComponentName> outActivities, String packageName) {
20404        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20405            return 0;
20406        }
20407        int num = 0;
20408        final int userId = UserHandle.getCallingUserId();
20409        // reader
20410        synchronized (mPackages) {
20411            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20412            if (pir != null) {
20413                final Iterator<PreferredActivity> it = pir.filterIterator();
20414                while (it.hasNext()) {
20415                    final PreferredActivity pa = it.next();
20416                    if (packageName == null
20417                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
20418                                    && pa.mPref.mAlways)) {
20419                        if (outFilters != null) {
20420                            outFilters.add(new IntentFilter(pa));
20421                        }
20422                        if (outActivities != null) {
20423                            outActivities.add(pa.mPref.mComponent);
20424                        }
20425                    }
20426                }
20427            }
20428        }
20429
20430        return num;
20431    }
20432
20433    @Override
20434    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
20435            int userId) {
20436        int callingUid = Binder.getCallingUid();
20437        if (callingUid != Process.SYSTEM_UID) {
20438            throw new SecurityException(
20439                    "addPersistentPreferredActivity can only be run by the system");
20440        }
20441        if (filter.countActions() == 0) {
20442            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20443            return;
20444        }
20445        synchronized (mPackages) {
20446            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
20447                    ":");
20448            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20449            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
20450                    new PersistentPreferredActivity(filter, activity));
20451            scheduleWritePackageRestrictionsLocked(userId);
20452            postPreferredActivityChangedBroadcast(userId);
20453        }
20454    }
20455
20456    @Override
20457    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
20458        int callingUid = Binder.getCallingUid();
20459        if (callingUid != Process.SYSTEM_UID) {
20460            throw new SecurityException(
20461                    "clearPackagePersistentPreferredActivities can only be run by the system");
20462        }
20463        ArrayList<PersistentPreferredActivity> removed = null;
20464        boolean changed = false;
20465        synchronized (mPackages) {
20466            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
20467                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
20468                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
20469                        .valueAt(i);
20470                if (userId != thisUserId) {
20471                    continue;
20472                }
20473                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
20474                while (it.hasNext()) {
20475                    PersistentPreferredActivity ppa = it.next();
20476                    // Mark entry for removal only if it matches the package name.
20477                    if (ppa.mComponent.getPackageName().equals(packageName)) {
20478                        if (removed == null) {
20479                            removed = new ArrayList<PersistentPreferredActivity>();
20480                        }
20481                        removed.add(ppa);
20482                    }
20483                }
20484                if (removed != null) {
20485                    for (int j=0; j<removed.size(); j++) {
20486                        PersistentPreferredActivity ppa = removed.get(j);
20487                        ppir.removeFilter(ppa);
20488                    }
20489                    changed = true;
20490                }
20491            }
20492
20493            if (changed) {
20494                scheduleWritePackageRestrictionsLocked(userId);
20495                postPreferredActivityChangedBroadcast(userId);
20496            }
20497        }
20498    }
20499
20500    /**
20501     * Common machinery for picking apart a restored XML blob and passing
20502     * it to a caller-supplied functor to be applied to the running system.
20503     */
20504    private void restoreFromXml(XmlPullParser parser, int userId,
20505            String expectedStartTag, BlobXmlRestorer functor)
20506            throws IOException, XmlPullParserException {
20507        int type;
20508        while ((type = parser.next()) != XmlPullParser.START_TAG
20509                && type != XmlPullParser.END_DOCUMENT) {
20510        }
20511        if (type != XmlPullParser.START_TAG) {
20512            // oops didn't find a start tag?!
20513            if (DEBUG_BACKUP) {
20514                Slog.e(TAG, "Didn't find start tag during restore");
20515            }
20516            return;
20517        }
20518Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
20519        // this is supposed to be TAG_PREFERRED_BACKUP
20520        if (!expectedStartTag.equals(parser.getName())) {
20521            if (DEBUG_BACKUP) {
20522                Slog.e(TAG, "Found unexpected tag " + parser.getName());
20523            }
20524            return;
20525        }
20526
20527        // skip interfering stuff, then we're aligned with the backing implementation
20528        while ((type = parser.next()) == XmlPullParser.TEXT) { }
20529Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
20530        functor.apply(parser, userId);
20531    }
20532
20533    private interface BlobXmlRestorer {
20534        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
20535    }
20536
20537    /**
20538     * Non-Binder method, support for the backup/restore mechanism: write the
20539     * full set of preferred activities in its canonical XML format.  Returns the
20540     * XML output as a byte array, or null if there is none.
20541     */
20542    @Override
20543    public byte[] getPreferredActivityBackup(int userId) {
20544        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20545            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
20546        }
20547
20548        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20549        try {
20550            final XmlSerializer serializer = new FastXmlSerializer();
20551            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20552            serializer.startDocument(null, true);
20553            serializer.startTag(null, TAG_PREFERRED_BACKUP);
20554
20555            synchronized (mPackages) {
20556                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
20557            }
20558
20559            serializer.endTag(null, TAG_PREFERRED_BACKUP);
20560            serializer.endDocument();
20561            serializer.flush();
20562        } catch (Exception e) {
20563            if (DEBUG_BACKUP) {
20564                Slog.e(TAG, "Unable to write preferred activities for backup", e);
20565            }
20566            return null;
20567        }
20568
20569        return dataStream.toByteArray();
20570    }
20571
20572    @Override
20573    public void restorePreferredActivities(byte[] backup, int userId) {
20574        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20575            throw new SecurityException("Only the system may call restorePreferredActivities()");
20576        }
20577
20578        try {
20579            final XmlPullParser parser = Xml.newPullParser();
20580            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20581            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
20582                    new BlobXmlRestorer() {
20583                        @Override
20584                        public void apply(XmlPullParser parser, int userId)
20585                                throws XmlPullParserException, IOException {
20586                            synchronized (mPackages) {
20587                                mSettings.readPreferredActivitiesLPw(parser, userId);
20588                            }
20589                        }
20590                    } );
20591        } catch (Exception e) {
20592            if (DEBUG_BACKUP) {
20593                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20594            }
20595        }
20596    }
20597
20598    /**
20599     * Non-Binder method, support for the backup/restore mechanism: write the
20600     * default browser (etc) settings in its canonical XML format.  Returns the default
20601     * browser XML representation as a byte array, or null if there is none.
20602     */
20603    @Override
20604    public byte[] getDefaultAppsBackup(int userId) {
20605        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20606            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
20607        }
20608
20609        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20610        try {
20611            final XmlSerializer serializer = new FastXmlSerializer();
20612            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20613            serializer.startDocument(null, true);
20614            serializer.startTag(null, TAG_DEFAULT_APPS);
20615
20616            synchronized (mPackages) {
20617                mSettings.writeDefaultAppsLPr(serializer, userId);
20618            }
20619
20620            serializer.endTag(null, TAG_DEFAULT_APPS);
20621            serializer.endDocument();
20622            serializer.flush();
20623        } catch (Exception e) {
20624            if (DEBUG_BACKUP) {
20625                Slog.e(TAG, "Unable to write default apps for backup", e);
20626            }
20627            return null;
20628        }
20629
20630        return dataStream.toByteArray();
20631    }
20632
20633    @Override
20634    public void restoreDefaultApps(byte[] backup, int userId) {
20635        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20636            throw new SecurityException("Only the system may call restoreDefaultApps()");
20637        }
20638
20639        try {
20640            final XmlPullParser parser = Xml.newPullParser();
20641            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20642            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
20643                    new BlobXmlRestorer() {
20644                        @Override
20645                        public void apply(XmlPullParser parser, int userId)
20646                                throws XmlPullParserException, IOException {
20647                            synchronized (mPackages) {
20648                                mSettings.readDefaultAppsLPw(parser, userId);
20649                            }
20650                        }
20651                    } );
20652        } catch (Exception e) {
20653            if (DEBUG_BACKUP) {
20654                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
20655            }
20656        }
20657    }
20658
20659    @Override
20660    public byte[] getIntentFilterVerificationBackup(int userId) {
20661        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20662            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
20663        }
20664
20665        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20666        try {
20667            final XmlSerializer serializer = new FastXmlSerializer();
20668            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20669            serializer.startDocument(null, true);
20670            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
20671
20672            synchronized (mPackages) {
20673                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20674            }
20675
20676            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
20677            serializer.endDocument();
20678            serializer.flush();
20679        } catch (Exception e) {
20680            if (DEBUG_BACKUP) {
20681                Slog.e(TAG, "Unable to write default apps for backup", e);
20682            }
20683            return null;
20684        }
20685
20686        return dataStream.toByteArray();
20687    }
20688
20689    @Override
20690    public void restoreIntentFilterVerification(byte[] backup, int userId) {
20691        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20692            throw new SecurityException("Only the system may call restorePreferredActivities()");
20693        }
20694
20695        try {
20696            final XmlPullParser parser = Xml.newPullParser();
20697            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20698            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20699                    new BlobXmlRestorer() {
20700                        @Override
20701                        public void apply(XmlPullParser parser, int userId)
20702                                throws XmlPullParserException, IOException {
20703                            synchronized (mPackages) {
20704                                mSettings.readAllDomainVerificationsLPr(parser, userId);
20705                                mSettings.writeLPr();
20706                            }
20707                        }
20708                    } );
20709        } catch (Exception e) {
20710            if (DEBUG_BACKUP) {
20711                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20712            }
20713        }
20714    }
20715
20716    @Override
20717    public byte[] getPermissionGrantBackup(int userId) {
20718        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20719            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20720        }
20721
20722        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20723        try {
20724            final XmlSerializer serializer = new FastXmlSerializer();
20725            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20726            serializer.startDocument(null, true);
20727            serializer.startTag(null, TAG_PERMISSION_BACKUP);
20728
20729            synchronized (mPackages) {
20730                serializeRuntimePermissionGrantsLPr(serializer, userId);
20731            }
20732
20733            serializer.endTag(null, TAG_PERMISSION_BACKUP);
20734            serializer.endDocument();
20735            serializer.flush();
20736        } catch (Exception e) {
20737            if (DEBUG_BACKUP) {
20738                Slog.e(TAG, "Unable to write default apps for backup", e);
20739            }
20740            return null;
20741        }
20742
20743        return dataStream.toByteArray();
20744    }
20745
20746    @Override
20747    public void restorePermissionGrants(byte[] backup, int userId) {
20748        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20749            throw new SecurityException("Only the system may call restorePermissionGrants()");
20750        }
20751
20752        try {
20753            final XmlPullParser parser = Xml.newPullParser();
20754            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20755            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20756                    new BlobXmlRestorer() {
20757                        @Override
20758                        public void apply(XmlPullParser parser, int userId)
20759                                throws XmlPullParserException, IOException {
20760                            synchronized (mPackages) {
20761                                processRestoredPermissionGrantsLPr(parser, userId);
20762                            }
20763                        }
20764                    } );
20765        } catch (Exception e) {
20766            if (DEBUG_BACKUP) {
20767                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20768            }
20769        }
20770    }
20771
20772    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20773            throws IOException {
20774        serializer.startTag(null, TAG_ALL_GRANTS);
20775
20776        final int N = mSettings.mPackages.size();
20777        for (int i = 0; i < N; i++) {
20778            final PackageSetting ps = mSettings.mPackages.valueAt(i);
20779            boolean pkgGrantsKnown = false;
20780
20781            PermissionsState packagePerms = ps.getPermissionsState();
20782
20783            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20784                final int grantFlags = state.getFlags();
20785                // only look at grants that are not system/policy fixed
20786                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20787                    final boolean isGranted = state.isGranted();
20788                    // And only back up the user-twiddled state bits
20789                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20790                        final String packageName = mSettings.mPackages.keyAt(i);
20791                        if (!pkgGrantsKnown) {
20792                            serializer.startTag(null, TAG_GRANT);
20793                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20794                            pkgGrantsKnown = true;
20795                        }
20796
20797                        final boolean userSet =
20798                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20799                        final boolean userFixed =
20800                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20801                        final boolean revoke =
20802                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20803
20804                        serializer.startTag(null, TAG_PERMISSION);
20805                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20806                        if (isGranted) {
20807                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20808                        }
20809                        if (userSet) {
20810                            serializer.attribute(null, ATTR_USER_SET, "true");
20811                        }
20812                        if (userFixed) {
20813                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20814                        }
20815                        if (revoke) {
20816                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20817                        }
20818                        serializer.endTag(null, TAG_PERMISSION);
20819                    }
20820                }
20821            }
20822
20823            if (pkgGrantsKnown) {
20824                serializer.endTag(null, TAG_GRANT);
20825            }
20826        }
20827
20828        serializer.endTag(null, TAG_ALL_GRANTS);
20829    }
20830
20831    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20832            throws XmlPullParserException, IOException {
20833        String pkgName = null;
20834        int outerDepth = parser.getDepth();
20835        int type;
20836        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20837                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20838            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20839                continue;
20840            }
20841
20842            final String tagName = parser.getName();
20843            if (tagName.equals(TAG_GRANT)) {
20844                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20845                if (DEBUG_BACKUP) {
20846                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20847                }
20848            } else if (tagName.equals(TAG_PERMISSION)) {
20849
20850                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20851                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20852
20853                int newFlagSet = 0;
20854                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20855                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20856                }
20857                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20858                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20859                }
20860                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20861                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20862                }
20863                if (DEBUG_BACKUP) {
20864                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
20865                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
20866                }
20867                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20868                if (ps != null) {
20869                    // Already installed so we apply the grant immediately
20870                    if (DEBUG_BACKUP) {
20871                        Slog.v(TAG, "        + already installed; applying");
20872                    }
20873                    PermissionsState perms = ps.getPermissionsState();
20874                    BasePermission bp = mSettings.mPermissions.get(permName);
20875                    if (bp != null) {
20876                        if (isGranted) {
20877                            perms.grantRuntimePermission(bp, userId);
20878                        }
20879                        if (newFlagSet != 0) {
20880                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20881                        }
20882                    }
20883                } else {
20884                    // Need to wait for post-restore install to apply the grant
20885                    if (DEBUG_BACKUP) {
20886                        Slog.v(TAG, "        - not yet installed; saving for later");
20887                    }
20888                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20889                            isGranted, newFlagSet, userId);
20890                }
20891            } else {
20892                PackageManagerService.reportSettingsProblem(Log.WARN,
20893                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20894                XmlUtils.skipCurrentTag(parser);
20895            }
20896        }
20897
20898        scheduleWriteSettingsLocked();
20899        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20900    }
20901
20902    @Override
20903    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20904            int sourceUserId, int targetUserId, int flags) {
20905        mContext.enforceCallingOrSelfPermission(
20906                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20907        int callingUid = Binder.getCallingUid();
20908        enforceOwnerRights(ownerPackage, callingUid);
20909        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20910        if (intentFilter.countActions() == 0) {
20911            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20912            return;
20913        }
20914        synchronized (mPackages) {
20915            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20916                    ownerPackage, targetUserId, flags);
20917            CrossProfileIntentResolver resolver =
20918                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20919            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20920            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20921            if (existing != null) {
20922                int size = existing.size();
20923                for (int i = 0; i < size; i++) {
20924                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20925                        return;
20926                    }
20927                }
20928            }
20929            resolver.addFilter(newFilter);
20930            scheduleWritePackageRestrictionsLocked(sourceUserId);
20931        }
20932    }
20933
20934    @Override
20935    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20936        mContext.enforceCallingOrSelfPermission(
20937                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20938        final int callingUid = Binder.getCallingUid();
20939        enforceOwnerRights(ownerPackage, callingUid);
20940        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20941        synchronized (mPackages) {
20942            CrossProfileIntentResolver resolver =
20943                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20944            ArraySet<CrossProfileIntentFilter> set =
20945                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20946            for (CrossProfileIntentFilter filter : set) {
20947                if (filter.getOwnerPackage().equals(ownerPackage)) {
20948                    resolver.removeFilter(filter);
20949                }
20950            }
20951            scheduleWritePackageRestrictionsLocked(sourceUserId);
20952        }
20953    }
20954
20955    // Enforcing that callingUid is owning pkg on userId
20956    private void enforceOwnerRights(String pkg, int callingUid) {
20957        // The system owns everything.
20958        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20959            return;
20960        }
20961        final int callingUserId = UserHandle.getUserId(callingUid);
20962        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20963        if (pi == null) {
20964            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20965                    + callingUserId);
20966        }
20967        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20968            throw new SecurityException("Calling uid " + callingUid
20969                    + " does not own package " + pkg);
20970        }
20971    }
20972
20973    @Override
20974    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20975        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20976            return null;
20977        }
20978        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20979    }
20980
20981    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
20982        UserManagerService ums = UserManagerService.getInstance();
20983        if (ums != null) {
20984            final UserInfo parent = ums.getProfileParent(userId);
20985            final int launcherUid = (parent != null) ? parent.id : userId;
20986            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
20987            if (launcherComponent != null) {
20988                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20989                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20990                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20991                        .setPackage(launcherComponent.getPackageName());
20992                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
20993            }
20994        }
20995    }
20996
20997    /**
20998     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20999     * then reports the most likely home activity or null if there are more than one.
21000     */
21001    private ComponentName getDefaultHomeActivity(int userId) {
21002        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
21003        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
21004        if (cn != null) {
21005            return cn;
21006        }
21007
21008        // Find the launcher with the highest priority and return that component if there are no
21009        // other home activity with the same priority.
21010        int lastPriority = Integer.MIN_VALUE;
21011        ComponentName lastComponent = null;
21012        final int size = allHomeCandidates.size();
21013        for (int i = 0; i < size; i++) {
21014            final ResolveInfo ri = allHomeCandidates.get(i);
21015            if (ri.priority > lastPriority) {
21016                lastComponent = ri.activityInfo.getComponentName();
21017                lastPriority = ri.priority;
21018            } else if (ri.priority == lastPriority) {
21019                // Two components found with same priority.
21020                lastComponent = null;
21021            }
21022        }
21023        return lastComponent;
21024    }
21025
21026    private Intent getHomeIntent() {
21027        Intent intent = new Intent(Intent.ACTION_MAIN);
21028        intent.addCategory(Intent.CATEGORY_HOME);
21029        intent.addCategory(Intent.CATEGORY_DEFAULT);
21030        return intent;
21031    }
21032
21033    private IntentFilter getHomeFilter() {
21034        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
21035        filter.addCategory(Intent.CATEGORY_HOME);
21036        filter.addCategory(Intent.CATEGORY_DEFAULT);
21037        return filter;
21038    }
21039
21040    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21041            int userId) {
21042        Intent intent  = getHomeIntent();
21043        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
21044                PackageManager.GET_META_DATA, userId);
21045        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
21046                true, false, false, userId);
21047
21048        allHomeCandidates.clear();
21049        if (list != null) {
21050            for (ResolveInfo ri : list) {
21051                allHomeCandidates.add(ri);
21052            }
21053        }
21054        return (preferred == null || preferred.activityInfo == null)
21055                ? null
21056                : new ComponentName(preferred.activityInfo.packageName,
21057                        preferred.activityInfo.name);
21058    }
21059
21060    @Override
21061    public void setHomeActivity(ComponentName comp, int userId) {
21062        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21063            return;
21064        }
21065        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21066        getHomeActivitiesAsUser(homeActivities, userId);
21067
21068        boolean found = false;
21069
21070        final int size = homeActivities.size();
21071        final ComponentName[] set = new ComponentName[size];
21072        for (int i = 0; i < size; i++) {
21073            final ResolveInfo candidate = homeActivities.get(i);
21074            final ActivityInfo info = candidate.activityInfo;
21075            final ComponentName activityName = new ComponentName(info.packageName, info.name);
21076            set[i] = activityName;
21077            if (!found && activityName.equals(comp)) {
21078                found = true;
21079            }
21080        }
21081        if (!found) {
21082            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21083                    + userId);
21084        }
21085        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21086                set, comp, userId);
21087    }
21088
21089    private @Nullable String getSetupWizardPackageName() {
21090        final Intent intent = new Intent(Intent.ACTION_MAIN);
21091        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21092
21093        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21094                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21095                        | MATCH_DISABLED_COMPONENTS,
21096                UserHandle.myUserId());
21097        if (matches.size() == 1) {
21098            return matches.get(0).getComponentInfo().packageName;
21099        } else {
21100            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21101                    + ": matches=" + matches);
21102            return null;
21103        }
21104    }
21105
21106    private @Nullable String getStorageManagerPackageName() {
21107        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21108
21109        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21110                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21111                        | MATCH_DISABLED_COMPONENTS,
21112                UserHandle.myUserId());
21113        if (matches.size() == 1) {
21114            return matches.get(0).getComponentInfo().packageName;
21115        } else {
21116            Slog.e(TAG, "There should probably be exactly one storage manager; found "
21117                    + matches.size() + ": matches=" + matches);
21118            return null;
21119        }
21120    }
21121
21122    @Override
21123    public void setApplicationEnabledSetting(String appPackageName,
21124            int newState, int flags, int userId, String callingPackage) {
21125        if (!sUserManager.exists(userId)) return;
21126        if (callingPackage == null) {
21127            callingPackage = Integer.toString(Binder.getCallingUid());
21128        }
21129        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21130    }
21131
21132    @Override
21133    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21134        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21135        synchronized (mPackages) {
21136            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21137            if (pkgSetting != null) {
21138                pkgSetting.setUpdateAvailable(updateAvailable);
21139            }
21140        }
21141    }
21142
21143    @Override
21144    public void setComponentEnabledSetting(ComponentName componentName,
21145            int newState, int flags, int userId) {
21146        if (!sUserManager.exists(userId)) return;
21147        setEnabledSetting(componentName.getPackageName(),
21148                componentName.getClassName(), newState, flags, userId, null);
21149    }
21150
21151    private void setEnabledSetting(final String packageName, String className, int newState,
21152            final int flags, int userId, String callingPackage) {
21153        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21154              || newState == COMPONENT_ENABLED_STATE_ENABLED
21155              || newState == COMPONENT_ENABLED_STATE_DISABLED
21156              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21157              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21158            throw new IllegalArgumentException("Invalid new component state: "
21159                    + newState);
21160        }
21161        PackageSetting pkgSetting;
21162        final int callingUid = Binder.getCallingUid();
21163        final int permission;
21164        if (callingUid == Process.SYSTEM_UID) {
21165            permission = PackageManager.PERMISSION_GRANTED;
21166        } else {
21167            permission = mContext.checkCallingOrSelfPermission(
21168                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21169        }
21170        enforceCrossUserPermission(callingUid, userId,
21171                false /* requireFullPermission */, true /* checkShell */, "set enabled");
21172        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21173        boolean sendNow = false;
21174        boolean isApp = (className == null);
21175        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21176        String componentName = isApp ? packageName : className;
21177        int packageUid = -1;
21178        ArrayList<String> components;
21179
21180        // reader
21181        synchronized (mPackages) {
21182            pkgSetting = mSettings.mPackages.get(packageName);
21183            if (pkgSetting == null) {
21184                if (!isCallerInstantApp) {
21185                    if (className == null) {
21186                        throw new IllegalArgumentException("Unknown package: " + packageName);
21187                    }
21188                    throw new IllegalArgumentException(
21189                            "Unknown component: " + packageName + "/" + className);
21190                } else {
21191                    // throw SecurityException to prevent leaking package information
21192                    throw new SecurityException(
21193                            "Attempt to change component state; "
21194                            + "pid=" + Binder.getCallingPid()
21195                            + ", uid=" + callingUid
21196                            + (className == null
21197                                    ? ", package=" + packageName
21198                                    : ", component=" + packageName + "/" + className));
21199                }
21200            }
21201        }
21202
21203        // Limit who can change which apps
21204        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21205            // Don't allow apps that don't have permission to modify other apps
21206            if (!allowedByPermission
21207                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21208                throw new SecurityException(
21209                        "Attempt to change component state; "
21210                        + "pid=" + Binder.getCallingPid()
21211                        + ", uid=" + callingUid
21212                        + (className == null
21213                                ? ", package=" + packageName
21214                                : ", component=" + packageName + "/" + className));
21215            }
21216            // Don't allow changing protected packages.
21217            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21218                throw new SecurityException("Cannot disable a protected package: " + packageName);
21219            }
21220        }
21221
21222        synchronized (mPackages) {
21223            if (callingUid == Process.SHELL_UID
21224                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21225                // Shell can only change whole packages between ENABLED and DISABLED_USER states
21226                // unless it is a test package.
21227                int oldState = pkgSetting.getEnabled(userId);
21228                if (className == null
21229                    &&
21230                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21231                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21232                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21233                    &&
21234                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21235                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
21236                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21237                    // ok
21238                } else {
21239                    throw new SecurityException(
21240                            "Shell cannot change component state for " + packageName + "/"
21241                            + className + " to " + newState);
21242                }
21243            }
21244            if (className == null) {
21245                // We're dealing with an application/package level state change
21246                if (pkgSetting.getEnabled(userId) == newState) {
21247                    // Nothing to do
21248                    return;
21249                }
21250                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21251                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
21252                    // Don't care about who enables an app.
21253                    callingPackage = null;
21254                }
21255                pkgSetting.setEnabled(newState, userId, callingPackage);
21256                // pkgSetting.pkg.mSetEnabled = newState;
21257            } else {
21258                // We're dealing with a component level state change
21259                // First, verify that this is a valid class name.
21260                PackageParser.Package pkg = pkgSetting.pkg;
21261                if (pkg == null || !pkg.hasComponentClassName(className)) {
21262                    if (pkg != null &&
21263                            pkg.applicationInfo.targetSdkVersion >=
21264                                    Build.VERSION_CODES.JELLY_BEAN) {
21265                        throw new IllegalArgumentException("Component class " + className
21266                                + " does not exist in " + packageName);
21267                    } else {
21268                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
21269                                + className + " does not exist in " + packageName);
21270                    }
21271                }
21272                switch (newState) {
21273                case COMPONENT_ENABLED_STATE_ENABLED:
21274                    if (!pkgSetting.enableComponentLPw(className, userId)) {
21275                        return;
21276                    }
21277                    break;
21278                case COMPONENT_ENABLED_STATE_DISABLED:
21279                    if (!pkgSetting.disableComponentLPw(className, userId)) {
21280                        return;
21281                    }
21282                    break;
21283                case COMPONENT_ENABLED_STATE_DEFAULT:
21284                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
21285                        return;
21286                    }
21287                    break;
21288                default:
21289                    Slog.e(TAG, "Invalid new component state: " + newState);
21290                    return;
21291                }
21292            }
21293            scheduleWritePackageRestrictionsLocked(userId);
21294            updateSequenceNumberLP(pkgSetting, new int[] { userId });
21295            final long callingId = Binder.clearCallingIdentity();
21296            try {
21297                updateInstantAppInstallerLocked(packageName);
21298            } finally {
21299                Binder.restoreCallingIdentity(callingId);
21300            }
21301            components = mPendingBroadcasts.get(userId, packageName);
21302            final boolean newPackage = components == null;
21303            if (newPackage) {
21304                components = new ArrayList<String>();
21305            }
21306            if (!components.contains(componentName)) {
21307                components.add(componentName);
21308            }
21309            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
21310                sendNow = true;
21311                // Purge entry from pending broadcast list if another one exists already
21312                // since we are sending one right away.
21313                mPendingBroadcasts.remove(userId, packageName);
21314            } else {
21315                if (newPackage) {
21316                    mPendingBroadcasts.put(userId, packageName, components);
21317                }
21318                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
21319                    // Schedule a message
21320                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
21321                }
21322            }
21323        }
21324
21325        long callingId = Binder.clearCallingIdentity();
21326        try {
21327            if (sendNow) {
21328                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
21329                sendPackageChangedBroadcast(packageName,
21330                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
21331            }
21332        } finally {
21333            Binder.restoreCallingIdentity(callingId);
21334        }
21335    }
21336
21337    @Override
21338    public void flushPackageRestrictionsAsUser(int userId) {
21339        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21340            return;
21341        }
21342        if (!sUserManager.exists(userId)) {
21343            return;
21344        }
21345        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
21346                false /* checkShell */, "flushPackageRestrictions");
21347        synchronized (mPackages) {
21348            mSettings.writePackageRestrictionsLPr(userId);
21349            mDirtyUsers.remove(userId);
21350            if (mDirtyUsers.isEmpty()) {
21351                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
21352            }
21353        }
21354    }
21355
21356    private void sendPackageChangedBroadcast(String packageName,
21357            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
21358        if (DEBUG_INSTALL)
21359            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
21360                    + componentNames);
21361        Bundle extras = new Bundle(4);
21362        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
21363        String nameList[] = new String[componentNames.size()];
21364        componentNames.toArray(nameList);
21365        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
21366        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
21367        extras.putInt(Intent.EXTRA_UID, packageUid);
21368        // If this is not reporting a change of the overall package, then only send it
21369        // to registered receivers.  We don't want to launch a swath of apps for every
21370        // little component state change.
21371        final int flags = !componentNames.contains(packageName)
21372                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
21373        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
21374                new int[] {UserHandle.getUserId(packageUid)});
21375    }
21376
21377    @Override
21378    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
21379        if (!sUserManager.exists(userId)) return;
21380        final int callingUid = Binder.getCallingUid();
21381        if (getInstantAppPackageName(callingUid) != null) {
21382            return;
21383        }
21384        final int permission = mContext.checkCallingOrSelfPermission(
21385                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21386        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21387        enforceCrossUserPermission(callingUid, userId,
21388                true /* requireFullPermission */, true /* checkShell */, "stop package");
21389        // writer
21390        synchronized (mPackages) {
21391            final PackageSetting ps = mSettings.mPackages.get(packageName);
21392            if (!filterAppAccessLPr(ps, callingUid, userId)
21393                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
21394                            allowedByPermission, callingUid, userId)) {
21395                scheduleWritePackageRestrictionsLocked(userId);
21396            }
21397        }
21398    }
21399
21400    @Override
21401    public String getInstallerPackageName(String packageName) {
21402        final int callingUid = Binder.getCallingUid();
21403        if (getInstantAppPackageName(callingUid) != null) {
21404            return null;
21405        }
21406        // reader
21407        synchronized (mPackages) {
21408            final PackageSetting ps = mSettings.mPackages.get(packageName);
21409            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
21410                return null;
21411            }
21412            return mSettings.getInstallerPackageNameLPr(packageName);
21413        }
21414    }
21415
21416    public boolean isOrphaned(String packageName) {
21417        // reader
21418        synchronized (mPackages) {
21419            return mSettings.isOrphaned(packageName);
21420        }
21421    }
21422
21423    @Override
21424    public int getApplicationEnabledSetting(String packageName, int userId) {
21425        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21426        int callingUid = Binder.getCallingUid();
21427        enforceCrossUserPermission(callingUid, userId,
21428                false /* requireFullPermission */, false /* checkShell */, "get enabled");
21429        // reader
21430        synchronized (mPackages) {
21431            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
21432                return COMPONENT_ENABLED_STATE_DISABLED;
21433            }
21434            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
21435        }
21436    }
21437
21438    @Override
21439    public int getComponentEnabledSetting(ComponentName component, int userId) {
21440        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21441        int callingUid = Binder.getCallingUid();
21442        enforceCrossUserPermission(callingUid, userId,
21443                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
21444        synchronized (mPackages) {
21445            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
21446                    component, TYPE_UNKNOWN, userId)) {
21447                return COMPONENT_ENABLED_STATE_DISABLED;
21448            }
21449            return mSettings.getComponentEnabledSettingLPr(component, userId);
21450        }
21451    }
21452
21453    @Override
21454    public void enterSafeMode() {
21455        enforceSystemOrRoot("Only the system can request entering safe mode");
21456
21457        if (!mSystemReady) {
21458            mSafeMode = true;
21459        }
21460    }
21461
21462    @Override
21463    public void systemReady() {
21464        enforceSystemOrRoot("Only the system can claim the system is ready");
21465
21466        mSystemReady = true;
21467        final ContentResolver resolver = mContext.getContentResolver();
21468        ContentObserver co = new ContentObserver(mHandler) {
21469            @Override
21470            public void onChange(boolean selfChange) {
21471                mEphemeralAppsDisabled =
21472                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
21473                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
21474            }
21475        };
21476        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21477                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
21478                false, co, UserHandle.USER_SYSTEM);
21479        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21480                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
21481        co.onChange(true);
21482
21483        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
21484        // disabled after already being started.
21485        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
21486                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
21487
21488        // Read the compatibilty setting when the system is ready.
21489        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
21490                mContext.getContentResolver(),
21491                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
21492        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
21493        if (DEBUG_SETTINGS) {
21494            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
21495        }
21496
21497        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
21498
21499        synchronized (mPackages) {
21500            // Verify that all of the preferred activity components actually
21501            // exist.  It is possible for applications to be updated and at
21502            // that point remove a previously declared activity component that
21503            // had been set as a preferred activity.  We try to clean this up
21504            // the next time we encounter that preferred activity, but it is
21505            // possible for the user flow to never be able to return to that
21506            // situation so here we do a sanity check to make sure we haven't
21507            // left any junk around.
21508            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21509            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21510                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21511                removed.clear();
21512                for (PreferredActivity pa : pir.filterSet()) {
21513                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21514                        removed.add(pa);
21515                    }
21516                }
21517                if (removed.size() > 0) {
21518                    for (int r=0; r<removed.size(); r++) {
21519                        PreferredActivity pa = removed.get(r);
21520                        Slog.w(TAG, "Removing dangling preferred activity: "
21521                                + pa.mPref.mComponent);
21522                        pir.removeFilter(pa);
21523                    }
21524                    mSettings.writePackageRestrictionsLPr(
21525                            mSettings.mPreferredActivities.keyAt(i));
21526                }
21527            }
21528
21529            for (int userId : UserManagerService.getInstance().getUserIds()) {
21530                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21531                    grantPermissionsUserIds = ArrayUtils.appendInt(
21532                            grantPermissionsUserIds, userId);
21533                }
21534            }
21535        }
21536        sUserManager.systemReady();
21537
21538        // If we upgraded grant all default permissions before kicking off.
21539        for (int userId : grantPermissionsUserIds) {
21540            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21541        }
21542
21543        // If we did not grant default permissions, we preload from this the
21544        // default permission exceptions lazily to ensure we don't hit the
21545        // disk on a new user creation.
21546        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21547            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21548        }
21549
21550        // Kick off any messages waiting for system ready
21551        if (mPostSystemReadyMessages != null) {
21552            for (Message msg : mPostSystemReadyMessages) {
21553                msg.sendToTarget();
21554            }
21555            mPostSystemReadyMessages = null;
21556        }
21557
21558        // Watch for external volumes that come and go over time
21559        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21560        storage.registerListener(mStorageListener);
21561
21562        mInstallerService.systemReady();
21563        mPackageDexOptimizer.systemReady();
21564
21565        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21566                StorageManagerInternal.class);
21567        StorageManagerInternal.addExternalStoragePolicy(
21568                new StorageManagerInternal.ExternalStorageMountPolicy() {
21569            @Override
21570            public int getMountMode(int uid, String packageName) {
21571                if (Process.isIsolated(uid)) {
21572                    return Zygote.MOUNT_EXTERNAL_NONE;
21573                }
21574                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
21575                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21576                }
21577                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21578                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21579                }
21580                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21581                    return Zygote.MOUNT_EXTERNAL_READ;
21582                }
21583                return Zygote.MOUNT_EXTERNAL_WRITE;
21584            }
21585
21586            @Override
21587            public boolean hasExternalStorage(int uid, String packageName) {
21588                return true;
21589            }
21590        });
21591
21592        // Now that we're mostly running, clean up stale users and apps
21593        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21594        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21595
21596        if (mPrivappPermissionsViolations != null) {
21597            Slog.wtf(TAG,"Signature|privileged permissions not in "
21598                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
21599            mPrivappPermissionsViolations = null;
21600        }
21601    }
21602
21603    public void waitForAppDataPrepared() {
21604        if (mPrepareAppDataFuture == null) {
21605            return;
21606        }
21607        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21608        mPrepareAppDataFuture = null;
21609    }
21610
21611    @Override
21612    public boolean isSafeMode() {
21613        // allow instant applications
21614        return mSafeMode;
21615    }
21616
21617    @Override
21618    public boolean hasSystemUidErrors() {
21619        // allow instant applications
21620        return mHasSystemUidErrors;
21621    }
21622
21623    static String arrayToString(int[] array) {
21624        StringBuffer buf = new StringBuffer(128);
21625        buf.append('[');
21626        if (array != null) {
21627            for (int i=0; i<array.length; i++) {
21628                if (i > 0) buf.append(", ");
21629                buf.append(array[i]);
21630            }
21631        }
21632        buf.append(']');
21633        return buf.toString();
21634    }
21635
21636    static class DumpState {
21637        public static final int DUMP_LIBS = 1 << 0;
21638        public static final int DUMP_FEATURES = 1 << 1;
21639        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
21640        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
21641        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
21642        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
21643        public static final int DUMP_PERMISSIONS = 1 << 6;
21644        public static final int DUMP_PACKAGES = 1 << 7;
21645        public static final int DUMP_SHARED_USERS = 1 << 8;
21646        public static final int DUMP_MESSAGES = 1 << 9;
21647        public static final int DUMP_PROVIDERS = 1 << 10;
21648        public static final int DUMP_VERIFIERS = 1 << 11;
21649        public static final int DUMP_PREFERRED = 1 << 12;
21650        public static final int DUMP_PREFERRED_XML = 1 << 13;
21651        public static final int DUMP_KEYSETS = 1 << 14;
21652        public static final int DUMP_VERSION = 1 << 15;
21653        public static final int DUMP_INSTALLS = 1 << 16;
21654        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
21655        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
21656        public static final int DUMP_FROZEN = 1 << 19;
21657        public static final int DUMP_DEXOPT = 1 << 20;
21658        public static final int DUMP_COMPILER_STATS = 1 << 21;
21659        public static final int DUMP_CHANGES = 1 << 22;
21660
21661        public static final int OPTION_SHOW_FILTERS = 1 << 0;
21662
21663        private int mTypes;
21664
21665        private int mOptions;
21666
21667        private boolean mTitlePrinted;
21668
21669        private SharedUserSetting mSharedUser;
21670
21671        public boolean isDumping(int type) {
21672            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
21673                return true;
21674            }
21675
21676            return (mTypes & type) != 0;
21677        }
21678
21679        public void setDump(int type) {
21680            mTypes |= type;
21681        }
21682
21683        public boolean isOptionEnabled(int option) {
21684            return (mOptions & option) != 0;
21685        }
21686
21687        public void setOptionEnabled(int option) {
21688            mOptions |= option;
21689        }
21690
21691        public boolean onTitlePrinted() {
21692            final boolean printed = mTitlePrinted;
21693            mTitlePrinted = true;
21694            return printed;
21695        }
21696
21697        public boolean getTitlePrinted() {
21698            return mTitlePrinted;
21699        }
21700
21701        public void setTitlePrinted(boolean enabled) {
21702            mTitlePrinted = enabled;
21703        }
21704
21705        public SharedUserSetting getSharedUser() {
21706            return mSharedUser;
21707        }
21708
21709        public void setSharedUser(SharedUserSetting user) {
21710            mSharedUser = user;
21711        }
21712    }
21713
21714    @Override
21715    public void onShellCommand(FileDescriptor in, FileDescriptor out,
21716            FileDescriptor err, String[] args, ShellCallback callback,
21717            ResultReceiver resultReceiver) {
21718        (new PackageManagerShellCommand(this)).exec(
21719                this, in, out, err, args, callback, resultReceiver);
21720    }
21721
21722    @Override
21723    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21724        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21725
21726        DumpState dumpState = new DumpState();
21727        boolean fullPreferred = false;
21728        boolean checkin = false;
21729
21730        String packageName = null;
21731        ArraySet<String> permissionNames = null;
21732
21733        int opti = 0;
21734        while (opti < args.length) {
21735            String opt = args[opti];
21736            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21737                break;
21738            }
21739            opti++;
21740
21741            if ("-a".equals(opt)) {
21742                // Right now we only know how to print all.
21743            } else if ("-h".equals(opt)) {
21744                pw.println("Package manager dump options:");
21745                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21746                pw.println("    --checkin: dump for a checkin");
21747                pw.println("    -f: print details of intent filters");
21748                pw.println("    -h: print this help");
21749                pw.println("  cmd may be one of:");
21750                pw.println("    l[ibraries]: list known shared libraries");
21751                pw.println("    f[eatures]: list device features");
21752                pw.println("    k[eysets]: print known keysets");
21753                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21754                pw.println("    perm[issions]: dump permissions");
21755                pw.println("    permission [name ...]: dump declaration and use of given permission");
21756                pw.println("    pref[erred]: print preferred package settings");
21757                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21758                pw.println("    prov[iders]: dump content providers");
21759                pw.println("    p[ackages]: dump installed packages");
21760                pw.println("    s[hared-users]: dump shared user IDs");
21761                pw.println("    m[essages]: print collected runtime messages");
21762                pw.println("    v[erifiers]: print package verifier info");
21763                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21764                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21765                pw.println("    version: print database version info");
21766                pw.println("    write: write current settings now");
21767                pw.println("    installs: details about install sessions");
21768                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21769                pw.println("    dexopt: dump dexopt state");
21770                pw.println("    compiler-stats: dump compiler statistics");
21771                pw.println("    enabled-overlays: dump list of enabled overlay packages");
21772                pw.println("    <package.name>: info about given package");
21773                return;
21774            } else if ("--checkin".equals(opt)) {
21775                checkin = true;
21776            } else if ("-f".equals(opt)) {
21777                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21778            } else if ("--proto".equals(opt)) {
21779                dumpProto(fd);
21780                return;
21781            } else {
21782                pw.println("Unknown argument: " + opt + "; use -h for help");
21783            }
21784        }
21785
21786        // Is the caller requesting to dump a particular piece of data?
21787        if (opti < args.length) {
21788            String cmd = args[opti];
21789            opti++;
21790            // Is this a package name?
21791            if ("android".equals(cmd) || cmd.contains(".")) {
21792                packageName = cmd;
21793                // When dumping a single package, we always dump all of its
21794                // filter information since the amount of data will be reasonable.
21795                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21796            } else if ("check-permission".equals(cmd)) {
21797                if (opti >= args.length) {
21798                    pw.println("Error: check-permission missing permission argument");
21799                    return;
21800                }
21801                String perm = args[opti];
21802                opti++;
21803                if (opti >= args.length) {
21804                    pw.println("Error: check-permission missing package argument");
21805                    return;
21806                }
21807
21808                String pkg = args[opti];
21809                opti++;
21810                int user = UserHandle.getUserId(Binder.getCallingUid());
21811                if (opti < args.length) {
21812                    try {
21813                        user = Integer.parseInt(args[opti]);
21814                    } catch (NumberFormatException e) {
21815                        pw.println("Error: check-permission user argument is not a number: "
21816                                + args[opti]);
21817                        return;
21818                    }
21819                }
21820
21821                // Normalize package name to handle renamed packages and static libs
21822                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21823
21824                pw.println(checkPermission(perm, pkg, user));
21825                return;
21826            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21827                dumpState.setDump(DumpState.DUMP_LIBS);
21828            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21829                dumpState.setDump(DumpState.DUMP_FEATURES);
21830            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21831                if (opti >= args.length) {
21832                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21833                            | DumpState.DUMP_SERVICE_RESOLVERS
21834                            | DumpState.DUMP_RECEIVER_RESOLVERS
21835                            | DumpState.DUMP_CONTENT_RESOLVERS);
21836                } else {
21837                    while (opti < args.length) {
21838                        String name = args[opti];
21839                        if ("a".equals(name) || "activity".equals(name)) {
21840                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21841                        } else if ("s".equals(name) || "service".equals(name)) {
21842                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21843                        } else if ("r".equals(name) || "receiver".equals(name)) {
21844                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21845                        } else if ("c".equals(name) || "content".equals(name)) {
21846                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21847                        } else {
21848                            pw.println("Error: unknown resolver table type: " + name);
21849                            return;
21850                        }
21851                        opti++;
21852                    }
21853                }
21854            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21855                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21856            } else if ("permission".equals(cmd)) {
21857                if (opti >= args.length) {
21858                    pw.println("Error: permission requires permission name");
21859                    return;
21860                }
21861                permissionNames = new ArraySet<>();
21862                while (opti < args.length) {
21863                    permissionNames.add(args[opti]);
21864                    opti++;
21865                }
21866                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21867                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21868            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21869                dumpState.setDump(DumpState.DUMP_PREFERRED);
21870            } else if ("preferred-xml".equals(cmd)) {
21871                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21872                if (opti < args.length && "--full".equals(args[opti])) {
21873                    fullPreferred = true;
21874                    opti++;
21875                }
21876            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21877                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21878            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21879                dumpState.setDump(DumpState.DUMP_PACKAGES);
21880            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21881                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21882            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21883                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21884            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21885                dumpState.setDump(DumpState.DUMP_MESSAGES);
21886            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21887                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21888            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21889                    || "intent-filter-verifiers".equals(cmd)) {
21890                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21891            } else if ("version".equals(cmd)) {
21892                dumpState.setDump(DumpState.DUMP_VERSION);
21893            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21894                dumpState.setDump(DumpState.DUMP_KEYSETS);
21895            } else if ("installs".equals(cmd)) {
21896                dumpState.setDump(DumpState.DUMP_INSTALLS);
21897            } else if ("frozen".equals(cmd)) {
21898                dumpState.setDump(DumpState.DUMP_FROZEN);
21899            } else if ("dexopt".equals(cmd)) {
21900                dumpState.setDump(DumpState.DUMP_DEXOPT);
21901            } else if ("compiler-stats".equals(cmd)) {
21902                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21903            } else if ("changes".equals(cmd)) {
21904                dumpState.setDump(DumpState.DUMP_CHANGES);
21905            } else if ("write".equals(cmd)) {
21906                synchronized (mPackages) {
21907                    mSettings.writeLPr();
21908                    pw.println("Settings written.");
21909                    return;
21910                }
21911            }
21912        }
21913
21914        if (checkin) {
21915            pw.println("vers,1");
21916        }
21917
21918        // reader
21919        synchronized (mPackages) {
21920            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21921                if (!checkin) {
21922                    if (dumpState.onTitlePrinted())
21923                        pw.println();
21924                    pw.println("Database versions:");
21925                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21926                }
21927            }
21928
21929            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21930                if (!checkin) {
21931                    if (dumpState.onTitlePrinted())
21932                        pw.println();
21933                    pw.println("Verifiers:");
21934                    pw.print("  Required: ");
21935                    pw.print(mRequiredVerifierPackage);
21936                    pw.print(" (uid=");
21937                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21938                            UserHandle.USER_SYSTEM));
21939                    pw.println(")");
21940                } else if (mRequiredVerifierPackage != null) {
21941                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21942                    pw.print(",");
21943                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21944                            UserHandle.USER_SYSTEM));
21945                }
21946            }
21947
21948            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21949                    packageName == null) {
21950                if (mIntentFilterVerifierComponent != null) {
21951                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21952                    if (!checkin) {
21953                        if (dumpState.onTitlePrinted())
21954                            pw.println();
21955                        pw.println("Intent Filter Verifier:");
21956                        pw.print("  Using: ");
21957                        pw.print(verifierPackageName);
21958                        pw.print(" (uid=");
21959                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21960                                UserHandle.USER_SYSTEM));
21961                        pw.println(")");
21962                    } else if (verifierPackageName != null) {
21963                        pw.print("ifv,"); pw.print(verifierPackageName);
21964                        pw.print(",");
21965                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21966                                UserHandle.USER_SYSTEM));
21967                    }
21968                } else {
21969                    pw.println();
21970                    pw.println("No Intent Filter Verifier available!");
21971                }
21972            }
21973
21974            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21975                boolean printedHeader = false;
21976                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21977                while (it.hasNext()) {
21978                    String libName = it.next();
21979                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21980                    if (versionedLib == null) {
21981                        continue;
21982                    }
21983                    final int versionCount = versionedLib.size();
21984                    for (int i = 0; i < versionCount; i++) {
21985                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21986                        if (!checkin) {
21987                            if (!printedHeader) {
21988                                if (dumpState.onTitlePrinted())
21989                                    pw.println();
21990                                pw.println("Libraries:");
21991                                printedHeader = true;
21992                            }
21993                            pw.print("  ");
21994                        } else {
21995                            pw.print("lib,");
21996                        }
21997                        pw.print(libEntry.info.getName());
21998                        if (libEntry.info.isStatic()) {
21999                            pw.print(" version=" + libEntry.info.getVersion());
22000                        }
22001                        if (!checkin) {
22002                            pw.print(" -> ");
22003                        }
22004                        if (libEntry.path != null) {
22005                            pw.print(" (jar) ");
22006                            pw.print(libEntry.path);
22007                        } else {
22008                            pw.print(" (apk) ");
22009                            pw.print(libEntry.apk);
22010                        }
22011                        pw.println();
22012                    }
22013                }
22014            }
22015
22016            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
22017                if (dumpState.onTitlePrinted())
22018                    pw.println();
22019                if (!checkin) {
22020                    pw.println("Features:");
22021                }
22022
22023                synchronized (mAvailableFeatures) {
22024                    for (FeatureInfo feat : mAvailableFeatures.values()) {
22025                        if (checkin) {
22026                            pw.print("feat,");
22027                            pw.print(feat.name);
22028                            pw.print(",");
22029                            pw.println(feat.version);
22030                        } else {
22031                            pw.print("  ");
22032                            pw.print(feat.name);
22033                            if (feat.version > 0) {
22034                                pw.print(" version=");
22035                                pw.print(feat.version);
22036                            }
22037                            pw.println();
22038                        }
22039                    }
22040                }
22041            }
22042
22043            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
22044                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
22045                        : "Activity Resolver Table:", "  ", packageName,
22046                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22047                    dumpState.setTitlePrinted(true);
22048                }
22049            }
22050            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
22051                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
22052                        : "Receiver Resolver Table:", "  ", packageName,
22053                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22054                    dumpState.setTitlePrinted(true);
22055                }
22056            }
22057            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
22058                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
22059                        : "Service Resolver Table:", "  ", packageName,
22060                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22061                    dumpState.setTitlePrinted(true);
22062                }
22063            }
22064            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
22065                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
22066                        : "Provider Resolver Table:", "  ", packageName,
22067                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22068                    dumpState.setTitlePrinted(true);
22069                }
22070            }
22071
22072            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22073                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22074                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22075                    int user = mSettings.mPreferredActivities.keyAt(i);
22076                    if (pir.dump(pw,
22077                            dumpState.getTitlePrinted()
22078                                ? "\nPreferred Activities User " + user + ":"
22079                                : "Preferred Activities User " + user + ":", "  ",
22080                            packageName, true, false)) {
22081                        dumpState.setTitlePrinted(true);
22082                    }
22083                }
22084            }
22085
22086            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22087                pw.flush();
22088                FileOutputStream fout = new FileOutputStream(fd);
22089                BufferedOutputStream str = new BufferedOutputStream(fout);
22090                XmlSerializer serializer = new FastXmlSerializer();
22091                try {
22092                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
22093                    serializer.startDocument(null, true);
22094                    serializer.setFeature(
22095                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22096                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22097                    serializer.endDocument();
22098                    serializer.flush();
22099                } catch (IllegalArgumentException e) {
22100                    pw.println("Failed writing: " + e);
22101                } catch (IllegalStateException e) {
22102                    pw.println("Failed writing: " + e);
22103                } catch (IOException e) {
22104                    pw.println("Failed writing: " + e);
22105                }
22106            }
22107
22108            if (!checkin
22109                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22110                    && packageName == null) {
22111                pw.println();
22112                int count = mSettings.mPackages.size();
22113                if (count == 0) {
22114                    pw.println("No applications!");
22115                    pw.println();
22116                } else {
22117                    final String prefix = "  ";
22118                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22119                    if (allPackageSettings.size() == 0) {
22120                        pw.println("No domain preferred apps!");
22121                        pw.println();
22122                    } else {
22123                        pw.println("App verification status:");
22124                        pw.println();
22125                        count = 0;
22126                        for (PackageSetting ps : allPackageSettings) {
22127                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22128                            if (ivi == null || ivi.getPackageName() == null) continue;
22129                            pw.println(prefix + "Package: " + ivi.getPackageName());
22130                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
22131                            pw.println(prefix + "Status:  " + ivi.getStatusString());
22132                            pw.println();
22133                            count++;
22134                        }
22135                        if (count == 0) {
22136                            pw.println(prefix + "No app verification established.");
22137                            pw.println();
22138                        }
22139                        for (int userId : sUserManager.getUserIds()) {
22140                            pw.println("App linkages for user " + userId + ":");
22141                            pw.println();
22142                            count = 0;
22143                            for (PackageSetting ps : allPackageSettings) {
22144                                final long status = ps.getDomainVerificationStatusForUser(userId);
22145                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22146                                        && !DEBUG_DOMAIN_VERIFICATION) {
22147                                    continue;
22148                                }
22149                                pw.println(prefix + "Package: " + ps.name);
22150                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22151                                String statusStr = IntentFilterVerificationInfo.
22152                                        getStatusStringFromValue(status);
22153                                pw.println(prefix + "Status:  " + statusStr);
22154                                pw.println();
22155                                count++;
22156                            }
22157                            if (count == 0) {
22158                                pw.println(prefix + "No configured app linkages.");
22159                                pw.println();
22160                            }
22161                        }
22162                    }
22163                }
22164            }
22165
22166            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22167                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22168                if (packageName == null && permissionNames == null) {
22169                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22170                        if (iperm == 0) {
22171                            if (dumpState.onTitlePrinted())
22172                                pw.println();
22173                            pw.println("AppOp Permissions:");
22174                        }
22175                        pw.print("  AppOp Permission ");
22176                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
22177                        pw.println(":");
22178                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
22179                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
22180                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
22181                        }
22182                    }
22183                }
22184            }
22185
22186            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
22187                boolean printedSomething = false;
22188                for (PackageParser.Provider p : mProviders.mProviders.values()) {
22189                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22190                        continue;
22191                    }
22192                    if (!printedSomething) {
22193                        if (dumpState.onTitlePrinted())
22194                            pw.println();
22195                        pw.println("Registered ContentProviders:");
22196                        printedSomething = true;
22197                    }
22198                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
22199                    pw.print("    "); pw.println(p.toString());
22200                }
22201                printedSomething = false;
22202                for (Map.Entry<String, PackageParser.Provider> entry :
22203                        mProvidersByAuthority.entrySet()) {
22204                    PackageParser.Provider p = entry.getValue();
22205                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22206                        continue;
22207                    }
22208                    if (!printedSomething) {
22209                        if (dumpState.onTitlePrinted())
22210                            pw.println();
22211                        pw.println("ContentProvider Authorities:");
22212                        printedSomething = true;
22213                    }
22214                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
22215                    pw.print("    "); pw.println(p.toString());
22216                    if (p.info != null && p.info.applicationInfo != null) {
22217                        final String appInfo = p.info.applicationInfo.toString();
22218                        pw.print("      applicationInfo="); pw.println(appInfo);
22219                    }
22220                }
22221            }
22222
22223            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
22224                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
22225            }
22226
22227            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
22228                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
22229            }
22230
22231            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
22232                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
22233            }
22234
22235            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
22236                if (dumpState.onTitlePrinted()) pw.println();
22237                pw.println("Package Changes:");
22238                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
22239                final int K = mChangedPackages.size();
22240                for (int i = 0; i < K; i++) {
22241                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
22242                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
22243                    final int N = changes.size();
22244                    if (N == 0) {
22245                        pw.print("    "); pw.println("No packages changed");
22246                    } else {
22247                        for (int j = 0; j < N; j++) {
22248                            final String pkgName = changes.valueAt(j);
22249                            final int sequenceNumber = changes.keyAt(j);
22250                            pw.print("    ");
22251                            pw.print("seq=");
22252                            pw.print(sequenceNumber);
22253                            pw.print(", package=");
22254                            pw.println(pkgName);
22255                        }
22256                    }
22257                }
22258            }
22259
22260            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
22261                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
22262            }
22263
22264            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
22265                // XXX should handle packageName != null by dumping only install data that
22266                // the given package is involved with.
22267                if (dumpState.onTitlePrinted()) pw.println();
22268
22269                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22270                ipw.println();
22271                ipw.println("Frozen packages:");
22272                ipw.increaseIndent();
22273                if (mFrozenPackages.size() == 0) {
22274                    ipw.println("(none)");
22275                } else {
22276                    for (int i = 0; i < mFrozenPackages.size(); i++) {
22277                        ipw.println(mFrozenPackages.valueAt(i));
22278                    }
22279                }
22280                ipw.decreaseIndent();
22281            }
22282
22283            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
22284                if (dumpState.onTitlePrinted()) pw.println();
22285                dumpDexoptStateLPr(pw, packageName);
22286            }
22287
22288            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
22289                if (dumpState.onTitlePrinted()) pw.println();
22290                dumpCompilerStatsLPr(pw, packageName);
22291            }
22292
22293            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
22294                if (dumpState.onTitlePrinted()) pw.println();
22295                mSettings.dumpReadMessagesLPr(pw, dumpState);
22296
22297                pw.println();
22298                pw.println("Package warning messages:");
22299                BufferedReader in = null;
22300                String line = null;
22301                try {
22302                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22303                    while ((line = in.readLine()) != null) {
22304                        if (line.contains("ignored: updated version")) continue;
22305                        pw.println(line);
22306                    }
22307                } catch (IOException ignored) {
22308                } finally {
22309                    IoUtils.closeQuietly(in);
22310                }
22311            }
22312
22313            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
22314                BufferedReader in = null;
22315                String line = null;
22316                try {
22317                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22318                    while ((line = in.readLine()) != null) {
22319                        if (line.contains("ignored: updated version")) continue;
22320                        pw.print("msg,");
22321                        pw.println(line);
22322                    }
22323                } catch (IOException ignored) {
22324                } finally {
22325                    IoUtils.closeQuietly(in);
22326                }
22327            }
22328        }
22329
22330        // PackageInstaller should be called outside of mPackages lock
22331        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
22332            // XXX should handle packageName != null by dumping only install data that
22333            // the given package is involved with.
22334            if (dumpState.onTitlePrinted()) pw.println();
22335            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
22336        }
22337    }
22338
22339    private void dumpProto(FileDescriptor fd) {
22340        final ProtoOutputStream proto = new ProtoOutputStream(fd);
22341
22342        synchronized (mPackages) {
22343            final long requiredVerifierPackageToken =
22344                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
22345            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
22346            proto.write(
22347                    PackageServiceDumpProto.PackageShortProto.UID,
22348                    getPackageUid(
22349                            mRequiredVerifierPackage,
22350                            MATCH_DEBUG_TRIAGED_MISSING,
22351                            UserHandle.USER_SYSTEM));
22352            proto.end(requiredVerifierPackageToken);
22353
22354            if (mIntentFilterVerifierComponent != null) {
22355                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22356                final long verifierPackageToken =
22357                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
22358                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
22359                proto.write(
22360                        PackageServiceDumpProto.PackageShortProto.UID,
22361                        getPackageUid(
22362                                verifierPackageName,
22363                                MATCH_DEBUG_TRIAGED_MISSING,
22364                                UserHandle.USER_SYSTEM));
22365                proto.end(verifierPackageToken);
22366            }
22367
22368            dumpSharedLibrariesProto(proto);
22369            dumpFeaturesProto(proto);
22370            mSettings.dumpPackagesProto(proto);
22371            mSettings.dumpSharedUsersProto(proto);
22372            dumpMessagesProto(proto);
22373        }
22374        proto.flush();
22375    }
22376
22377    private void dumpMessagesProto(ProtoOutputStream proto) {
22378        BufferedReader in = null;
22379        String line = null;
22380        try {
22381            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22382            while ((line = in.readLine()) != null) {
22383                if (line.contains("ignored: updated version")) continue;
22384                proto.write(PackageServiceDumpProto.MESSAGES, line);
22385            }
22386        } catch (IOException ignored) {
22387        } finally {
22388            IoUtils.closeQuietly(in);
22389        }
22390    }
22391
22392    private void dumpFeaturesProto(ProtoOutputStream proto) {
22393        synchronized (mAvailableFeatures) {
22394            final int count = mAvailableFeatures.size();
22395            for (int i = 0; i < count; i++) {
22396                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
22397                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
22398                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
22399                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
22400                proto.end(featureToken);
22401            }
22402        }
22403    }
22404
22405    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
22406        final int count = mSharedLibraries.size();
22407        for (int i = 0; i < count; i++) {
22408            final String libName = mSharedLibraries.keyAt(i);
22409            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22410            if (versionedLib == null) {
22411                continue;
22412            }
22413            final int versionCount = versionedLib.size();
22414            for (int j = 0; j < versionCount; j++) {
22415                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
22416                final long sharedLibraryToken =
22417                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
22418                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
22419                final boolean isJar = (libEntry.path != null);
22420                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
22421                if (isJar) {
22422                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
22423                } else {
22424                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
22425                }
22426                proto.end(sharedLibraryToken);
22427            }
22428        }
22429    }
22430
22431    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
22432        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22433        ipw.println();
22434        ipw.println("Dexopt state:");
22435        ipw.increaseIndent();
22436        Collection<PackageParser.Package> packages = null;
22437        if (packageName != null) {
22438            PackageParser.Package targetPackage = mPackages.get(packageName);
22439            if (targetPackage != null) {
22440                packages = Collections.singletonList(targetPackage);
22441            } else {
22442                ipw.println("Unable to find package: " + packageName);
22443                return;
22444            }
22445        } else {
22446            packages = mPackages.values();
22447        }
22448
22449        for (PackageParser.Package pkg : packages) {
22450            ipw.println("[" + pkg.packageName + "]");
22451            ipw.increaseIndent();
22452            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
22453            ipw.decreaseIndent();
22454        }
22455    }
22456
22457    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
22458        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22459        ipw.println();
22460        ipw.println("Compiler stats:");
22461        ipw.increaseIndent();
22462        Collection<PackageParser.Package> packages = null;
22463        if (packageName != null) {
22464            PackageParser.Package targetPackage = mPackages.get(packageName);
22465            if (targetPackage != null) {
22466                packages = Collections.singletonList(targetPackage);
22467            } else {
22468                ipw.println("Unable to find package: " + packageName);
22469                return;
22470            }
22471        } else {
22472            packages = mPackages.values();
22473        }
22474
22475        for (PackageParser.Package pkg : packages) {
22476            ipw.println("[" + pkg.packageName + "]");
22477            ipw.increaseIndent();
22478
22479            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
22480            if (stats == null) {
22481                ipw.println("(No recorded stats)");
22482            } else {
22483                stats.dump(ipw);
22484            }
22485            ipw.decreaseIndent();
22486        }
22487    }
22488
22489    private String dumpDomainString(String packageName) {
22490        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
22491                .getList();
22492        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
22493
22494        ArraySet<String> result = new ArraySet<>();
22495        if (iviList.size() > 0) {
22496            for (IntentFilterVerificationInfo ivi : iviList) {
22497                for (String host : ivi.getDomains()) {
22498                    result.add(host);
22499                }
22500            }
22501        }
22502        if (filters != null && filters.size() > 0) {
22503            for (IntentFilter filter : filters) {
22504                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
22505                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
22506                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
22507                    result.addAll(filter.getHostsList());
22508                }
22509            }
22510        }
22511
22512        StringBuilder sb = new StringBuilder(result.size() * 16);
22513        for (String domain : result) {
22514            if (sb.length() > 0) sb.append(" ");
22515            sb.append(domain);
22516        }
22517        return sb.toString();
22518    }
22519
22520    // ------- apps on sdcard specific code -------
22521    static final boolean DEBUG_SD_INSTALL = false;
22522
22523    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
22524
22525    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
22526
22527    private boolean mMediaMounted = false;
22528
22529    static String getEncryptKey() {
22530        try {
22531            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
22532                    SD_ENCRYPTION_KEYSTORE_NAME);
22533            if (sdEncKey == null) {
22534                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
22535                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
22536                if (sdEncKey == null) {
22537                    Slog.e(TAG, "Failed to create encryption keys");
22538                    return null;
22539                }
22540            }
22541            return sdEncKey;
22542        } catch (NoSuchAlgorithmException nsae) {
22543            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
22544            return null;
22545        } catch (IOException ioe) {
22546            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
22547            return null;
22548        }
22549    }
22550
22551    /*
22552     * Update media status on PackageManager.
22553     */
22554    @Override
22555    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
22556        enforceSystemOrRoot("Media status can only be updated by the system");
22557        // reader; this apparently protects mMediaMounted, but should probably
22558        // be a different lock in that case.
22559        synchronized (mPackages) {
22560            Log.i(TAG, "Updating external media status from "
22561                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
22562                    + (mediaStatus ? "mounted" : "unmounted"));
22563            if (DEBUG_SD_INSTALL)
22564                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
22565                        + ", mMediaMounted=" + mMediaMounted);
22566            if (mediaStatus == mMediaMounted) {
22567                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
22568                        : 0, -1);
22569                mHandler.sendMessage(msg);
22570                return;
22571            }
22572            mMediaMounted = mediaStatus;
22573        }
22574        // Queue up an async operation since the package installation may take a
22575        // little while.
22576        mHandler.post(new Runnable() {
22577            public void run() {
22578                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
22579            }
22580        });
22581    }
22582
22583    /**
22584     * Called by StorageManagerService when the initial ASECs to scan are available.
22585     * Should block until all the ASEC containers are finished being scanned.
22586     */
22587    public void scanAvailableAsecs() {
22588        updateExternalMediaStatusInner(true, false, false);
22589    }
22590
22591    /*
22592     * Collect information of applications on external media, map them against
22593     * existing containers and update information based on current mount status.
22594     * Please note that we always have to report status if reportStatus has been
22595     * set to true especially when unloading packages.
22596     */
22597    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
22598            boolean externalStorage) {
22599        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
22600        int[] uidArr = EmptyArray.INT;
22601
22602        final String[] list = PackageHelper.getSecureContainerList();
22603        if (ArrayUtils.isEmpty(list)) {
22604            Log.i(TAG, "No secure containers found");
22605        } else {
22606            // Process list of secure containers and categorize them
22607            // as active or stale based on their package internal state.
22608
22609            // reader
22610            synchronized (mPackages) {
22611                for (String cid : list) {
22612                    // Leave stages untouched for now; installer service owns them
22613                    if (PackageInstallerService.isStageName(cid)) continue;
22614
22615                    if (DEBUG_SD_INSTALL)
22616                        Log.i(TAG, "Processing container " + cid);
22617                    String pkgName = getAsecPackageName(cid);
22618                    if (pkgName == null) {
22619                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
22620                        continue;
22621                    }
22622                    if (DEBUG_SD_INSTALL)
22623                        Log.i(TAG, "Looking for pkg : " + pkgName);
22624
22625                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
22626                    if (ps == null) {
22627                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
22628                        continue;
22629                    }
22630
22631                    /*
22632                     * Skip packages that are not external if we're unmounting
22633                     * external storage.
22634                     */
22635                    if (externalStorage && !isMounted && !isExternal(ps)) {
22636                        continue;
22637                    }
22638
22639                    final AsecInstallArgs args = new AsecInstallArgs(cid,
22640                            getAppDexInstructionSets(ps), ps.isForwardLocked());
22641                    // The package status is changed only if the code path
22642                    // matches between settings and the container id.
22643                    if (ps.codePathString != null
22644                            && ps.codePathString.startsWith(args.getCodePath())) {
22645                        if (DEBUG_SD_INSTALL) {
22646                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
22647                                    + " at code path: " + ps.codePathString);
22648                        }
22649
22650                        // We do have a valid package installed on sdcard
22651                        processCids.put(args, ps.codePathString);
22652                        final int uid = ps.appId;
22653                        if (uid != -1) {
22654                            uidArr = ArrayUtils.appendInt(uidArr, uid);
22655                        }
22656                    } else {
22657                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
22658                                + ps.codePathString);
22659                    }
22660                }
22661            }
22662
22663            Arrays.sort(uidArr);
22664        }
22665
22666        // Process packages with valid entries.
22667        if (isMounted) {
22668            if (DEBUG_SD_INSTALL)
22669                Log.i(TAG, "Loading packages");
22670            loadMediaPackages(processCids, uidArr, externalStorage);
22671            startCleaningPackages();
22672            mInstallerService.onSecureContainersAvailable();
22673        } else {
22674            if (DEBUG_SD_INSTALL)
22675                Log.i(TAG, "Unloading packages");
22676            unloadMediaPackages(processCids, uidArr, reportStatus);
22677        }
22678    }
22679
22680    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22681            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
22682        final int size = infos.size();
22683        final String[] packageNames = new String[size];
22684        final int[] packageUids = new int[size];
22685        for (int i = 0; i < size; i++) {
22686            final ApplicationInfo info = infos.get(i);
22687            packageNames[i] = info.packageName;
22688            packageUids[i] = info.uid;
22689        }
22690        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
22691                finishedReceiver);
22692    }
22693
22694    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22695            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22696        sendResourcesChangedBroadcast(mediaStatus, replacing,
22697                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
22698    }
22699
22700    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22701            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22702        int size = pkgList.length;
22703        if (size > 0) {
22704            // Send broadcasts here
22705            Bundle extras = new Bundle();
22706            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
22707            if (uidArr != null) {
22708                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
22709            }
22710            if (replacing) {
22711                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
22712            }
22713            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
22714                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
22715            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
22716        }
22717    }
22718
22719   /*
22720     * Look at potentially valid container ids from processCids If package
22721     * information doesn't match the one on record or package scanning fails,
22722     * the cid is added to list of removeCids. We currently don't delete stale
22723     * containers.
22724     */
22725    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
22726            boolean externalStorage) {
22727        ArrayList<String> pkgList = new ArrayList<String>();
22728        Set<AsecInstallArgs> keys = processCids.keySet();
22729
22730        for (AsecInstallArgs args : keys) {
22731            String codePath = processCids.get(args);
22732            if (DEBUG_SD_INSTALL)
22733                Log.i(TAG, "Loading container : " + args.cid);
22734            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
22735            try {
22736                // Make sure there are no container errors first.
22737                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
22738                    Slog.e(TAG, "Failed to mount cid : " + args.cid
22739                            + " when installing from sdcard");
22740                    continue;
22741                }
22742                // Check code path here.
22743                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
22744                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
22745                            + " does not match one in settings " + codePath);
22746                    continue;
22747                }
22748                // Parse package
22749                int parseFlags = mDefParseFlags;
22750                if (args.isExternalAsec()) {
22751                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
22752                }
22753                if (args.isFwdLocked()) {
22754                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
22755                }
22756
22757                synchronized (mInstallLock) {
22758                    PackageParser.Package pkg = null;
22759                    try {
22760                        // Sadly we don't know the package name yet to freeze it
22761                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
22762                                SCAN_IGNORE_FROZEN, 0, null);
22763                    } catch (PackageManagerException e) {
22764                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
22765                    }
22766                    // Scan the package
22767                    if (pkg != null) {
22768                        /*
22769                         * TODO why is the lock being held? doPostInstall is
22770                         * called in other places without the lock. This needs
22771                         * to be straightened out.
22772                         */
22773                        // writer
22774                        synchronized (mPackages) {
22775                            retCode = PackageManager.INSTALL_SUCCEEDED;
22776                            pkgList.add(pkg.packageName);
22777                            // Post process args
22778                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
22779                                    pkg.applicationInfo.uid);
22780                        }
22781                    } else {
22782                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
22783                    }
22784                }
22785
22786            } finally {
22787                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
22788                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
22789                }
22790            }
22791        }
22792        // writer
22793        synchronized (mPackages) {
22794            // If the platform SDK has changed since the last time we booted,
22795            // we need to re-grant app permission to catch any new ones that
22796            // appear. This is really a hack, and means that apps can in some
22797            // cases get permissions that the user didn't initially explicitly
22798            // allow... it would be nice to have some better way to handle
22799            // this situation.
22800            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
22801                    : mSettings.getInternalVersion();
22802            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
22803                    : StorageManager.UUID_PRIVATE_INTERNAL;
22804
22805            int updateFlags = UPDATE_PERMISSIONS_ALL;
22806            if (ver.sdkVersion != mSdkVersion) {
22807                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22808                        + mSdkVersion + "; regranting permissions for external");
22809                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22810            }
22811            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
22812
22813            // Yay, everything is now upgraded
22814            ver.forceCurrent();
22815
22816            // can downgrade to reader
22817            // Persist settings
22818            mSettings.writeLPr();
22819        }
22820        // Send a broadcast to let everyone know we are done processing
22821        if (pkgList.size() > 0) {
22822            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
22823        }
22824    }
22825
22826   /*
22827     * Utility method to unload a list of specified containers
22828     */
22829    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
22830        // Just unmount all valid containers.
22831        for (AsecInstallArgs arg : cidArgs) {
22832            synchronized (mInstallLock) {
22833                arg.doPostDeleteLI(false);
22834           }
22835       }
22836   }
22837
22838    /*
22839     * Unload packages mounted on external media. This involves deleting package
22840     * data from internal structures, sending broadcasts about disabled packages,
22841     * gc'ing to free up references, unmounting all secure containers
22842     * corresponding to packages on external media, and posting a
22843     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
22844     * that we always have to post this message if status has been requested no
22845     * matter what.
22846     */
22847    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
22848            final boolean reportStatus) {
22849        if (DEBUG_SD_INSTALL)
22850            Log.i(TAG, "unloading media packages");
22851        ArrayList<String> pkgList = new ArrayList<String>();
22852        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
22853        final Set<AsecInstallArgs> keys = processCids.keySet();
22854        for (AsecInstallArgs args : keys) {
22855            String pkgName = args.getPackageName();
22856            if (DEBUG_SD_INSTALL)
22857                Log.i(TAG, "Trying to unload pkg : " + pkgName);
22858            // Delete package internally
22859            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22860            synchronized (mInstallLock) {
22861                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22862                final boolean res;
22863                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
22864                        "unloadMediaPackages")) {
22865                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
22866                            null);
22867                }
22868                if (res) {
22869                    pkgList.add(pkgName);
22870                } else {
22871                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
22872                    failedList.add(args);
22873                }
22874            }
22875        }
22876
22877        // reader
22878        synchronized (mPackages) {
22879            // We didn't update the settings after removing each package;
22880            // write them now for all packages.
22881            mSettings.writeLPr();
22882        }
22883
22884        // We have to absolutely send UPDATED_MEDIA_STATUS only
22885        // after confirming that all the receivers processed the ordered
22886        // broadcast when packages get disabled, force a gc to clean things up.
22887        // and unload all the containers.
22888        if (pkgList.size() > 0) {
22889            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
22890                    new IIntentReceiver.Stub() {
22891                public void performReceive(Intent intent, int resultCode, String data,
22892                        Bundle extras, boolean ordered, boolean sticky,
22893                        int sendingUser) throws RemoteException {
22894                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
22895                            reportStatus ? 1 : 0, 1, keys);
22896                    mHandler.sendMessage(msg);
22897                }
22898            });
22899        } else {
22900            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
22901                    keys);
22902            mHandler.sendMessage(msg);
22903        }
22904    }
22905
22906    private void loadPrivatePackages(final VolumeInfo vol) {
22907        mHandler.post(new Runnable() {
22908            @Override
22909            public void run() {
22910                loadPrivatePackagesInner(vol);
22911            }
22912        });
22913    }
22914
22915    private void loadPrivatePackagesInner(VolumeInfo vol) {
22916        final String volumeUuid = vol.fsUuid;
22917        if (TextUtils.isEmpty(volumeUuid)) {
22918            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
22919            return;
22920        }
22921
22922        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
22923        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
22924        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
22925
22926        final VersionInfo ver;
22927        final List<PackageSetting> packages;
22928        synchronized (mPackages) {
22929            ver = mSettings.findOrCreateVersion(volumeUuid);
22930            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22931        }
22932
22933        for (PackageSetting ps : packages) {
22934            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
22935            synchronized (mInstallLock) {
22936                final PackageParser.Package pkg;
22937                try {
22938                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
22939                    loaded.add(pkg.applicationInfo);
22940
22941                } catch (PackageManagerException e) {
22942                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
22943                }
22944
22945                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
22946                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
22947                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
22948                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
22949                }
22950            }
22951        }
22952
22953        // Reconcile app data for all started/unlocked users
22954        final StorageManager sm = mContext.getSystemService(StorageManager.class);
22955        final UserManager um = mContext.getSystemService(UserManager.class);
22956        UserManagerInternal umInternal = getUserManagerInternal();
22957        for (UserInfo user : um.getUsers()) {
22958            final int flags;
22959            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22960                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22961            } else if (umInternal.isUserRunning(user.id)) {
22962                flags = StorageManager.FLAG_STORAGE_DE;
22963            } else {
22964                continue;
22965            }
22966
22967            try {
22968                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
22969                synchronized (mInstallLock) {
22970                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
22971                }
22972            } catch (IllegalStateException e) {
22973                // Device was probably ejected, and we'll process that event momentarily
22974                Slog.w(TAG, "Failed to prepare storage: " + e);
22975            }
22976        }
22977
22978        synchronized (mPackages) {
22979            int updateFlags = UPDATE_PERMISSIONS_ALL;
22980            if (ver.sdkVersion != mSdkVersion) {
22981                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22982                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
22983                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22984            }
22985            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
22986
22987            // Yay, everything is now upgraded
22988            ver.forceCurrent();
22989
22990            mSettings.writeLPr();
22991        }
22992
22993        for (PackageFreezer freezer : freezers) {
22994            freezer.close();
22995        }
22996
22997        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
22998        sendResourcesChangedBroadcast(true, false, loaded, null);
22999    }
23000
23001    private void unloadPrivatePackages(final VolumeInfo vol) {
23002        mHandler.post(new Runnable() {
23003            @Override
23004            public void run() {
23005                unloadPrivatePackagesInner(vol);
23006            }
23007        });
23008    }
23009
23010    private void unloadPrivatePackagesInner(VolumeInfo vol) {
23011        final String volumeUuid = vol.fsUuid;
23012        if (TextUtils.isEmpty(volumeUuid)) {
23013            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
23014            return;
23015        }
23016
23017        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
23018        synchronized (mInstallLock) {
23019        synchronized (mPackages) {
23020            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
23021            for (PackageSetting ps : packages) {
23022                if (ps.pkg == null) continue;
23023
23024                final ApplicationInfo info = ps.pkg.applicationInfo;
23025                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23026                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23027
23028                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
23029                        "unloadPrivatePackagesInner")) {
23030                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
23031                            false, null)) {
23032                        unloaded.add(info);
23033                    } else {
23034                        Slog.w(TAG, "Failed to unload " + ps.codePath);
23035                    }
23036                }
23037
23038                // Try very hard to release any references to this package
23039                // so we don't risk the system server being killed due to
23040                // open FDs
23041                AttributeCache.instance().removePackage(ps.name);
23042            }
23043
23044            mSettings.writeLPr();
23045        }
23046        }
23047
23048        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
23049        sendResourcesChangedBroadcast(false, false, unloaded, null);
23050
23051        // Try very hard to release any references to this path so we don't risk
23052        // the system server being killed due to open FDs
23053        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
23054
23055        for (int i = 0; i < 3; i++) {
23056            System.gc();
23057            System.runFinalization();
23058        }
23059    }
23060
23061    private void assertPackageKnown(String volumeUuid, String packageName)
23062            throws PackageManagerException {
23063        synchronized (mPackages) {
23064            // Normalize package name to handle renamed packages
23065            packageName = normalizePackageNameLPr(packageName);
23066
23067            final PackageSetting ps = mSettings.mPackages.get(packageName);
23068            if (ps == null) {
23069                throw new PackageManagerException("Package " + packageName + " is unknown");
23070            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23071                throw new PackageManagerException(
23072                        "Package " + packageName + " found on unknown volume " + volumeUuid
23073                                + "; expected volume " + ps.volumeUuid);
23074            }
23075        }
23076    }
23077
23078    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23079            throws PackageManagerException {
23080        synchronized (mPackages) {
23081            // Normalize package name to handle renamed packages
23082            packageName = normalizePackageNameLPr(packageName);
23083
23084            final PackageSetting ps = mSettings.mPackages.get(packageName);
23085            if (ps == null) {
23086                throw new PackageManagerException("Package " + packageName + " is unknown");
23087            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23088                throw new PackageManagerException(
23089                        "Package " + packageName + " found on unknown volume " + volumeUuid
23090                                + "; expected volume " + ps.volumeUuid);
23091            } else if (!ps.getInstalled(userId)) {
23092                throw new PackageManagerException(
23093                        "Package " + packageName + " not installed for user " + userId);
23094            }
23095        }
23096    }
23097
23098    private List<String> collectAbsoluteCodePaths() {
23099        synchronized (mPackages) {
23100            List<String> codePaths = new ArrayList<>();
23101            final int packageCount = mSettings.mPackages.size();
23102            for (int i = 0; i < packageCount; i++) {
23103                final PackageSetting ps = mSettings.mPackages.valueAt(i);
23104                codePaths.add(ps.codePath.getAbsolutePath());
23105            }
23106            return codePaths;
23107        }
23108    }
23109
23110    /**
23111     * Examine all apps present on given mounted volume, and destroy apps that
23112     * aren't expected, either due to uninstallation or reinstallation on
23113     * another volume.
23114     */
23115    private void reconcileApps(String volumeUuid) {
23116        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
23117        List<File> filesToDelete = null;
23118
23119        final File[] files = FileUtils.listFilesOrEmpty(
23120                Environment.getDataAppDirectory(volumeUuid));
23121        for (File file : files) {
23122            final boolean isPackage = (isApkFile(file) || file.isDirectory())
23123                    && !PackageInstallerService.isStageName(file.getName());
23124            if (!isPackage) {
23125                // Ignore entries which are not packages
23126                continue;
23127            }
23128
23129            String absolutePath = file.getAbsolutePath();
23130
23131            boolean pathValid = false;
23132            final int absoluteCodePathCount = absoluteCodePaths.size();
23133            for (int i = 0; i < absoluteCodePathCount; i++) {
23134                String absoluteCodePath = absoluteCodePaths.get(i);
23135                if (absolutePath.startsWith(absoluteCodePath)) {
23136                    pathValid = true;
23137                    break;
23138                }
23139            }
23140
23141            if (!pathValid) {
23142                if (filesToDelete == null) {
23143                    filesToDelete = new ArrayList<>();
23144                }
23145                filesToDelete.add(file);
23146            }
23147        }
23148
23149        if (filesToDelete != null) {
23150            final int fileToDeleteCount = filesToDelete.size();
23151            for (int i = 0; i < fileToDeleteCount; i++) {
23152                File fileToDelete = filesToDelete.get(i);
23153                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23154                synchronized (mInstallLock) {
23155                    removeCodePathLI(fileToDelete);
23156                }
23157            }
23158        }
23159    }
23160
23161    /**
23162     * Reconcile all app data for the given user.
23163     * <p>
23164     * Verifies that directories exist and that ownership and labeling is
23165     * correct for all installed apps on all mounted volumes.
23166     */
23167    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
23168        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23169        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
23170            final String volumeUuid = vol.getFsUuid();
23171            synchronized (mInstallLock) {
23172                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
23173            }
23174        }
23175    }
23176
23177    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23178            boolean migrateAppData) {
23179        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
23180    }
23181
23182    /**
23183     * Reconcile all app data on given mounted volume.
23184     * <p>
23185     * Destroys app data that isn't expected, either due to uninstallation or
23186     * reinstallation on another volume.
23187     * <p>
23188     * Verifies that directories exist and that ownership and labeling is
23189     * correct for all installed apps.
23190     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
23191     */
23192    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23193            boolean migrateAppData, boolean onlyCoreApps) {
23194        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
23195                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
23196        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
23197
23198        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
23199        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
23200
23201        // First look for stale data that doesn't belong, and check if things
23202        // have changed since we did our last restorecon
23203        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23204            if (StorageManager.isFileEncryptedNativeOrEmulated()
23205                    && !StorageManager.isUserKeyUnlocked(userId)) {
23206                throw new RuntimeException(
23207                        "Yikes, someone asked us to reconcile CE storage while " + userId
23208                                + " was still locked; this would have caused massive data loss!");
23209            }
23210
23211            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
23212            for (File file : files) {
23213                final String packageName = file.getName();
23214                try {
23215                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23216                } catch (PackageManagerException e) {
23217                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23218                    try {
23219                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23220                                StorageManager.FLAG_STORAGE_CE, 0);
23221                    } catch (InstallerException e2) {
23222                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23223                    }
23224                }
23225            }
23226        }
23227        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
23228            final File[] files = FileUtils.listFilesOrEmpty(deDir);
23229            for (File file : files) {
23230                final String packageName = file.getName();
23231                try {
23232                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23233                } catch (PackageManagerException e) {
23234                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23235                    try {
23236                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23237                                StorageManager.FLAG_STORAGE_DE, 0);
23238                    } catch (InstallerException e2) {
23239                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23240                    }
23241                }
23242            }
23243        }
23244
23245        // Ensure that data directories are ready to roll for all packages
23246        // installed for this volume and user
23247        final List<PackageSetting> packages;
23248        synchronized (mPackages) {
23249            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23250        }
23251        int preparedCount = 0;
23252        for (PackageSetting ps : packages) {
23253            final String packageName = ps.name;
23254            if (ps.pkg == null) {
23255                Slog.w(TAG, "Odd, missing scanned package " + packageName);
23256                // TODO: might be due to legacy ASEC apps; we should circle back
23257                // and reconcile again once they're scanned
23258                continue;
23259            }
23260            // Skip non-core apps if requested
23261            if (onlyCoreApps && !ps.pkg.coreApp) {
23262                result.add(packageName);
23263                continue;
23264            }
23265
23266            if (ps.getInstalled(userId)) {
23267                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
23268                preparedCount++;
23269            }
23270        }
23271
23272        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
23273        return result;
23274    }
23275
23276    /**
23277     * Prepare app data for the given app just after it was installed or
23278     * upgraded. This method carefully only touches users that it's installed
23279     * for, and it forces a restorecon to handle any seinfo changes.
23280     * <p>
23281     * Verifies that directories exist and that ownership and labeling is
23282     * correct for all installed apps. If there is an ownership mismatch, it
23283     * will try recovering system apps by wiping data; third-party app data is
23284     * left intact.
23285     * <p>
23286     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
23287     */
23288    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
23289        final PackageSetting ps;
23290        synchronized (mPackages) {
23291            ps = mSettings.mPackages.get(pkg.packageName);
23292            mSettings.writeKernelMappingLPr(ps);
23293        }
23294
23295        final UserManager um = mContext.getSystemService(UserManager.class);
23296        UserManagerInternal umInternal = getUserManagerInternal();
23297        for (UserInfo user : um.getUsers()) {
23298            final int flags;
23299            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23300                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23301            } else if (umInternal.isUserRunning(user.id)) {
23302                flags = StorageManager.FLAG_STORAGE_DE;
23303            } else {
23304                continue;
23305            }
23306
23307            if (ps.getInstalled(user.id)) {
23308                // TODO: when user data is locked, mark that we're still dirty
23309                prepareAppDataLIF(pkg, user.id, flags);
23310            }
23311        }
23312    }
23313
23314    /**
23315     * Prepare app data for the given app.
23316     * <p>
23317     * Verifies that directories exist and that ownership and labeling is
23318     * correct for all installed apps. If there is an ownership mismatch, this
23319     * will try recovering system apps by wiping data; third-party app data is
23320     * left intact.
23321     */
23322    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
23323        if (pkg == null) {
23324            Slog.wtf(TAG, "Package was null!", new Throwable());
23325            return;
23326        }
23327        prepareAppDataLeafLIF(pkg, userId, flags);
23328        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23329        for (int i = 0; i < childCount; i++) {
23330            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
23331        }
23332    }
23333
23334    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
23335            boolean maybeMigrateAppData) {
23336        prepareAppDataLIF(pkg, userId, flags);
23337
23338        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
23339            // We may have just shuffled around app data directories, so
23340            // prepare them one more time
23341            prepareAppDataLIF(pkg, userId, flags);
23342        }
23343    }
23344
23345    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23346        if (DEBUG_APP_DATA) {
23347            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
23348                    + Integer.toHexString(flags));
23349        }
23350
23351        final String volumeUuid = pkg.volumeUuid;
23352        final String packageName = pkg.packageName;
23353        final ApplicationInfo app = pkg.applicationInfo;
23354        final int appId = UserHandle.getAppId(app.uid);
23355
23356        Preconditions.checkNotNull(app.seInfo);
23357
23358        long ceDataInode = -1;
23359        try {
23360            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23361                    appId, app.seInfo, app.targetSdkVersion);
23362        } catch (InstallerException e) {
23363            if (app.isSystemApp()) {
23364                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
23365                        + ", but trying to recover: " + e);
23366                destroyAppDataLeafLIF(pkg, userId, flags);
23367                try {
23368                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23369                            appId, app.seInfo, app.targetSdkVersion);
23370                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
23371                } catch (InstallerException e2) {
23372                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
23373                }
23374            } else {
23375                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
23376            }
23377        }
23378
23379        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
23380            // TODO: mark this structure as dirty so we persist it!
23381            synchronized (mPackages) {
23382                final PackageSetting ps = mSettings.mPackages.get(packageName);
23383                if (ps != null) {
23384                    ps.setCeDataInode(ceDataInode, userId);
23385                }
23386            }
23387        }
23388
23389        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23390    }
23391
23392    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
23393        if (pkg == null) {
23394            Slog.wtf(TAG, "Package was null!", new Throwable());
23395            return;
23396        }
23397        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23398        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23399        for (int i = 0; i < childCount; i++) {
23400            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
23401        }
23402    }
23403
23404    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23405        final String volumeUuid = pkg.volumeUuid;
23406        final String packageName = pkg.packageName;
23407        final ApplicationInfo app = pkg.applicationInfo;
23408
23409        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23410            // Create a native library symlink only if we have native libraries
23411            // and if the native libraries are 32 bit libraries. We do not provide
23412            // this symlink for 64 bit libraries.
23413            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
23414                final String nativeLibPath = app.nativeLibraryDir;
23415                try {
23416                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
23417                            nativeLibPath, userId);
23418                } catch (InstallerException e) {
23419                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
23420                }
23421            }
23422        }
23423    }
23424
23425    /**
23426     * For system apps on non-FBE devices, this method migrates any existing
23427     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
23428     * requested by the app.
23429     */
23430    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
23431        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
23432                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
23433            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
23434                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
23435            try {
23436                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
23437                        storageTarget);
23438            } catch (InstallerException e) {
23439                logCriticalInfo(Log.WARN,
23440                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
23441            }
23442            return true;
23443        } else {
23444            return false;
23445        }
23446    }
23447
23448    public PackageFreezer freezePackage(String packageName, String killReason) {
23449        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
23450    }
23451
23452    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
23453        return new PackageFreezer(packageName, userId, killReason);
23454    }
23455
23456    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
23457            String killReason) {
23458        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
23459    }
23460
23461    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
23462            String killReason) {
23463        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
23464            return new PackageFreezer();
23465        } else {
23466            return freezePackage(packageName, userId, killReason);
23467        }
23468    }
23469
23470    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
23471            String killReason) {
23472        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
23473    }
23474
23475    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
23476            String killReason) {
23477        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
23478            return new PackageFreezer();
23479        } else {
23480            return freezePackage(packageName, userId, killReason);
23481        }
23482    }
23483
23484    /**
23485     * Class that freezes and kills the given package upon creation, and
23486     * unfreezes it upon closing. This is typically used when doing surgery on
23487     * app code/data to prevent the app from running while you're working.
23488     */
23489    private class PackageFreezer implements AutoCloseable {
23490        private final String mPackageName;
23491        private final PackageFreezer[] mChildren;
23492
23493        private final boolean mWeFroze;
23494
23495        private final AtomicBoolean mClosed = new AtomicBoolean();
23496        private final CloseGuard mCloseGuard = CloseGuard.get();
23497
23498        /**
23499         * Create and return a stub freezer that doesn't actually do anything,
23500         * typically used when someone requested
23501         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
23502         * {@link PackageManager#DELETE_DONT_KILL_APP}.
23503         */
23504        public PackageFreezer() {
23505            mPackageName = null;
23506            mChildren = null;
23507            mWeFroze = false;
23508            mCloseGuard.open("close");
23509        }
23510
23511        public PackageFreezer(String packageName, int userId, String killReason) {
23512            synchronized (mPackages) {
23513                mPackageName = packageName;
23514                mWeFroze = mFrozenPackages.add(mPackageName);
23515
23516                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
23517                if (ps != null) {
23518                    killApplication(ps.name, ps.appId, userId, killReason);
23519                }
23520
23521                final PackageParser.Package p = mPackages.get(packageName);
23522                if (p != null && p.childPackages != null) {
23523                    final int N = p.childPackages.size();
23524                    mChildren = new PackageFreezer[N];
23525                    for (int i = 0; i < N; i++) {
23526                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
23527                                userId, killReason);
23528                    }
23529                } else {
23530                    mChildren = null;
23531                }
23532            }
23533            mCloseGuard.open("close");
23534        }
23535
23536        @Override
23537        protected void finalize() throws Throwable {
23538            try {
23539                if (mCloseGuard != null) {
23540                    mCloseGuard.warnIfOpen();
23541                }
23542
23543                close();
23544            } finally {
23545                super.finalize();
23546            }
23547        }
23548
23549        @Override
23550        public void close() {
23551            mCloseGuard.close();
23552            if (mClosed.compareAndSet(false, true)) {
23553                synchronized (mPackages) {
23554                    if (mWeFroze) {
23555                        mFrozenPackages.remove(mPackageName);
23556                    }
23557
23558                    if (mChildren != null) {
23559                        for (PackageFreezer freezer : mChildren) {
23560                            freezer.close();
23561                        }
23562                    }
23563                }
23564            }
23565        }
23566    }
23567
23568    /**
23569     * Verify that given package is currently frozen.
23570     */
23571    private void checkPackageFrozen(String packageName) {
23572        synchronized (mPackages) {
23573            if (!mFrozenPackages.contains(packageName)) {
23574                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
23575            }
23576        }
23577    }
23578
23579    @Override
23580    public int movePackage(final String packageName, final String volumeUuid) {
23581        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23582
23583        final int callingUid = Binder.getCallingUid();
23584        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
23585        final int moveId = mNextMoveId.getAndIncrement();
23586        mHandler.post(new Runnable() {
23587            @Override
23588            public void run() {
23589                try {
23590                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
23591                } catch (PackageManagerException e) {
23592                    Slog.w(TAG, "Failed to move " + packageName, e);
23593                    mMoveCallbacks.notifyStatusChanged(moveId,
23594                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23595                }
23596            }
23597        });
23598        return moveId;
23599    }
23600
23601    private void movePackageInternal(final String packageName, final String volumeUuid,
23602            final int moveId, final int callingUid, UserHandle user)
23603                    throws PackageManagerException {
23604        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23605        final PackageManager pm = mContext.getPackageManager();
23606
23607        final boolean currentAsec;
23608        final String currentVolumeUuid;
23609        final File codeFile;
23610        final String installerPackageName;
23611        final String packageAbiOverride;
23612        final int appId;
23613        final String seinfo;
23614        final String label;
23615        final int targetSdkVersion;
23616        final PackageFreezer freezer;
23617        final int[] installedUserIds;
23618
23619        // reader
23620        synchronized (mPackages) {
23621            final PackageParser.Package pkg = mPackages.get(packageName);
23622            final PackageSetting ps = mSettings.mPackages.get(packageName);
23623            if (pkg == null
23624                    || ps == null
23625                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
23626                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
23627            }
23628            if (pkg.applicationInfo.isSystemApp()) {
23629                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
23630                        "Cannot move system application");
23631            }
23632
23633            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
23634            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
23635                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
23636            if (isInternalStorage && !allow3rdPartyOnInternal) {
23637                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
23638                        "3rd party apps are not allowed on internal storage");
23639            }
23640
23641            if (pkg.applicationInfo.isExternalAsec()) {
23642                currentAsec = true;
23643                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
23644            } else if (pkg.applicationInfo.isForwardLocked()) {
23645                currentAsec = true;
23646                currentVolumeUuid = "forward_locked";
23647            } else {
23648                currentAsec = false;
23649                currentVolumeUuid = ps.volumeUuid;
23650
23651                final File probe = new File(pkg.codePath);
23652                final File probeOat = new File(probe, "oat");
23653                if (!probe.isDirectory() || !probeOat.isDirectory()) {
23654                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23655                            "Move only supported for modern cluster style installs");
23656                }
23657            }
23658
23659            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
23660                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23661                        "Package already moved to " + volumeUuid);
23662            }
23663            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
23664                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
23665                        "Device admin cannot be moved");
23666            }
23667
23668            if (mFrozenPackages.contains(packageName)) {
23669                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
23670                        "Failed to move already frozen package");
23671            }
23672
23673            codeFile = new File(pkg.codePath);
23674            installerPackageName = ps.installerPackageName;
23675            packageAbiOverride = ps.cpuAbiOverrideString;
23676            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
23677            seinfo = pkg.applicationInfo.seInfo;
23678            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
23679            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
23680            freezer = freezePackage(packageName, "movePackageInternal");
23681            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
23682        }
23683
23684        final Bundle extras = new Bundle();
23685        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
23686        extras.putString(Intent.EXTRA_TITLE, label);
23687        mMoveCallbacks.notifyCreated(moveId, extras);
23688
23689        int installFlags;
23690        final boolean moveCompleteApp;
23691        final File measurePath;
23692
23693        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
23694            installFlags = INSTALL_INTERNAL;
23695            moveCompleteApp = !currentAsec;
23696            measurePath = Environment.getDataAppDirectory(volumeUuid);
23697        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
23698            installFlags = INSTALL_EXTERNAL;
23699            moveCompleteApp = false;
23700            measurePath = storage.getPrimaryPhysicalVolume().getPath();
23701        } else {
23702            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
23703            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
23704                    || !volume.isMountedWritable()) {
23705                freezer.close();
23706                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23707                        "Move location not mounted private volume");
23708            }
23709
23710            Preconditions.checkState(!currentAsec);
23711
23712            installFlags = INSTALL_INTERNAL;
23713            moveCompleteApp = true;
23714            measurePath = Environment.getDataAppDirectory(volumeUuid);
23715        }
23716
23717        final PackageStats stats = new PackageStats(null, -1);
23718        synchronized (mInstaller) {
23719            for (int userId : installedUserIds) {
23720                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
23721                    freezer.close();
23722                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23723                            "Failed to measure package size");
23724                }
23725            }
23726        }
23727
23728        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
23729                + stats.dataSize);
23730
23731        final long startFreeBytes = measurePath.getUsableSpace();
23732        final long sizeBytes;
23733        if (moveCompleteApp) {
23734            sizeBytes = stats.codeSize + stats.dataSize;
23735        } else {
23736            sizeBytes = stats.codeSize;
23737        }
23738
23739        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
23740            freezer.close();
23741            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23742                    "Not enough free space to move");
23743        }
23744
23745        mMoveCallbacks.notifyStatusChanged(moveId, 10);
23746
23747        final CountDownLatch installedLatch = new CountDownLatch(1);
23748        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
23749            @Override
23750            public void onUserActionRequired(Intent intent) throws RemoteException {
23751                throw new IllegalStateException();
23752            }
23753
23754            @Override
23755            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
23756                    Bundle extras) throws RemoteException {
23757                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
23758                        + PackageManager.installStatusToString(returnCode, msg));
23759
23760                installedLatch.countDown();
23761                freezer.close();
23762
23763                final int status = PackageManager.installStatusToPublicStatus(returnCode);
23764                switch (status) {
23765                    case PackageInstaller.STATUS_SUCCESS:
23766                        mMoveCallbacks.notifyStatusChanged(moveId,
23767                                PackageManager.MOVE_SUCCEEDED);
23768                        break;
23769                    case PackageInstaller.STATUS_FAILURE_STORAGE:
23770                        mMoveCallbacks.notifyStatusChanged(moveId,
23771                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
23772                        break;
23773                    default:
23774                        mMoveCallbacks.notifyStatusChanged(moveId,
23775                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23776                        break;
23777                }
23778            }
23779        };
23780
23781        final MoveInfo move;
23782        if (moveCompleteApp) {
23783            // Kick off a thread to report progress estimates
23784            new Thread() {
23785                @Override
23786                public void run() {
23787                    while (true) {
23788                        try {
23789                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
23790                                break;
23791                            }
23792                        } catch (InterruptedException ignored) {
23793                        }
23794
23795                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
23796                        final int progress = 10 + (int) MathUtils.constrain(
23797                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
23798                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
23799                    }
23800                }
23801            }.start();
23802
23803            final String dataAppName = codeFile.getName();
23804            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
23805                    dataAppName, appId, seinfo, targetSdkVersion);
23806        } else {
23807            move = null;
23808        }
23809
23810        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
23811
23812        final Message msg = mHandler.obtainMessage(INIT_COPY);
23813        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
23814        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
23815                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
23816                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
23817                PackageManager.INSTALL_REASON_UNKNOWN);
23818        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
23819        msg.obj = params;
23820
23821        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
23822                System.identityHashCode(msg.obj));
23823        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
23824                System.identityHashCode(msg.obj));
23825
23826        mHandler.sendMessage(msg);
23827    }
23828
23829    @Override
23830    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
23831        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23832
23833        final int realMoveId = mNextMoveId.getAndIncrement();
23834        final Bundle extras = new Bundle();
23835        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
23836        mMoveCallbacks.notifyCreated(realMoveId, extras);
23837
23838        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
23839            @Override
23840            public void onCreated(int moveId, Bundle extras) {
23841                // Ignored
23842            }
23843
23844            @Override
23845            public void onStatusChanged(int moveId, int status, long estMillis) {
23846                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
23847            }
23848        };
23849
23850        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23851        storage.setPrimaryStorageUuid(volumeUuid, callback);
23852        return realMoveId;
23853    }
23854
23855    @Override
23856    public int getMoveStatus(int moveId) {
23857        mContext.enforceCallingOrSelfPermission(
23858                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23859        return mMoveCallbacks.mLastStatus.get(moveId);
23860    }
23861
23862    @Override
23863    public void registerMoveCallback(IPackageMoveObserver callback) {
23864        mContext.enforceCallingOrSelfPermission(
23865                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23866        mMoveCallbacks.register(callback);
23867    }
23868
23869    @Override
23870    public void unregisterMoveCallback(IPackageMoveObserver callback) {
23871        mContext.enforceCallingOrSelfPermission(
23872                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23873        mMoveCallbacks.unregister(callback);
23874    }
23875
23876    @Override
23877    public boolean setInstallLocation(int loc) {
23878        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
23879                null);
23880        if (getInstallLocation() == loc) {
23881            return true;
23882        }
23883        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
23884                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
23885            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
23886                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
23887            return true;
23888        }
23889        return false;
23890   }
23891
23892    @Override
23893    public int getInstallLocation() {
23894        // allow instant app access
23895        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
23896                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
23897                PackageHelper.APP_INSTALL_AUTO);
23898    }
23899
23900    /** Called by UserManagerService */
23901    void cleanUpUser(UserManagerService userManager, int userHandle) {
23902        synchronized (mPackages) {
23903            mDirtyUsers.remove(userHandle);
23904            mUserNeedsBadging.delete(userHandle);
23905            mSettings.removeUserLPw(userHandle);
23906            mPendingBroadcasts.remove(userHandle);
23907            mInstantAppRegistry.onUserRemovedLPw(userHandle);
23908            removeUnusedPackagesLPw(userManager, userHandle);
23909        }
23910    }
23911
23912    /**
23913     * We're removing userHandle and would like to remove any downloaded packages
23914     * that are no longer in use by any other user.
23915     * @param userHandle the user being removed
23916     */
23917    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
23918        final boolean DEBUG_CLEAN_APKS = false;
23919        int [] users = userManager.getUserIds();
23920        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
23921        while (psit.hasNext()) {
23922            PackageSetting ps = psit.next();
23923            if (ps.pkg == null) {
23924                continue;
23925            }
23926            final String packageName = ps.pkg.packageName;
23927            // Skip over if system app
23928            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23929                continue;
23930            }
23931            if (DEBUG_CLEAN_APKS) {
23932                Slog.i(TAG, "Checking package " + packageName);
23933            }
23934            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
23935            if (keep) {
23936                if (DEBUG_CLEAN_APKS) {
23937                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
23938                }
23939            } else {
23940                for (int i = 0; i < users.length; i++) {
23941                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
23942                        keep = true;
23943                        if (DEBUG_CLEAN_APKS) {
23944                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
23945                                    + users[i]);
23946                        }
23947                        break;
23948                    }
23949                }
23950            }
23951            if (!keep) {
23952                if (DEBUG_CLEAN_APKS) {
23953                    Slog.i(TAG, "  Removing package " + packageName);
23954                }
23955                mHandler.post(new Runnable() {
23956                    public void run() {
23957                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23958                                userHandle, 0);
23959                    } //end run
23960                });
23961            }
23962        }
23963    }
23964
23965    /** Called by UserManagerService */
23966    void createNewUser(int userId, String[] disallowedPackages) {
23967        synchronized (mInstallLock) {
23968            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
23969        }
23970        synchronized (mPackages) {
23971            scheduleWritePackageRestrictionsLocked(userId);
23972            scheduleWritePackageListLocked(userId);
23973            applyFactoryDefaultBrowserLPw(userId);
23974            primeDomainVerificationsLPw(userId);
23975        }
23976    }
23977
23978    void onNewUserCreated(final int userId) {
23979        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
23980        // If permission review for legacy apps is required, we represent
23981        // dagerous permissions for such apps as always granted runtime
23982        // permissions to keep per user flag state whether review is needed.
23983        // Hence, if a new user is added we have to propagate dangerous
23984        // permission grants for these legacy apps.
23985        if (mPermissionReviewRequired) {
23986            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
23987                    | UPDATE_PERMISSIONS_REPLACE_ALL);
23988        }
23989    }
23990
23991    @Override
23992    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
23993        mContext.enforceCallingOrSelfPermission(
23994                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
23995                "Only package verification agents can read the verifier device identity");
23996
23997        synchronized (mPackages) {
23998            return mSettings.getVerifierDeviceIdentityLPw();
23999        }
24000    }
24001
24002    @Override
24003    public void setPermissionEnforced(String permission, boolean enforced) {
24004        // TODO: Now that we no longer change GID for storage, this should to away.
24005        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
24006                "setPermissionEnforced");
24007        if (READ_EXTERNAL_STORAGE.equals(permission)) {
24008            synchronized (mPackages) {
24009                if (mSettings.mReadExternalStorageEnforced == null
24010                        || mSettings.mReadExternalStorageEnforced != enforced) {
24011                    mSettings.mReadExternalStorageEnforced = enforced;
24012                    mSettings.writeLPr();
24013                }
24014            }
24015            // kill any non-foreground processes so we restart them and
24016            // grant/revoke the GID.
24017            final IActivityManager am = ActivityManager.getService();
24018            if (am != null) {
24019                final long token = Binder.clearCallingIdentity();
24020                try {
24021                    am.killProcessesBelowForeground("setPermissionEnforcement");
24022                } catch (RemoteException e) {
24023                } finally {
24024                    Binder.restoreCallingIdentity(token);
24025                }
24026            }
24027        } else {
24028            throw new IllegalArgumentException("No selective enforcement for " + permission);
24029        }
24030    }
24031
24032    @Override
24033    @Deprecated
24034    public boolean isPermissionEnforced(String permission) {
24035        // allow instant applications
24036        return true;
24037    }
24038
24039    @Override
24040    public boolean isStorageLow() {
24041        // allow instant applications
24042        final long token = Binder.clearCallingIdentity();
24043        try {
24044            final DeviceStorageMonitorInternal
24045                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
24046            if (dsm != null) {
24047                return dsm.isMemoryLow();
24048            } else {
24049                return false;
24050            }
24051        } finally {
24052            Binder.restoreCallingIdentity(token);
24053        }
24054    }
24055
24056    @Override
24057    public IPackageInstaller getPackageInstaller() {
24058        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24059            return null;
24060        }
24061        return mInstallerService;
24062    }
24063
24064    private boolean userNeedsBadging(int userId) {
24065        int index = mUserNeedsBadging.indexOfKey(userId);
24066        if (index < 0) {
24067            final UserInfo userInfo;
24068            final long token = Binder.clearCallingIdentity();
24069            try {
24070                userInfo = sUserManager.getUserInfo(userId);
24071            } finally {
24072                Binder.restoreCallingIdentity(token);
24073            }
24074            final boolean b;
24075            if (userInfo != null && userInfo.isManagedProfile()) {
24076                b = true;
24077            } else {
24078                b = false;
24079            }
24080            mUserNeedsBadging.put(userId, b);
24081            return b;
24082        }
24083        return mUserNeedsBadging.valueAt(index);
24084    }
24085
24086    @Override
24087    public KeySet getKeySetByAlias(String packageName, String alias) {
24088        if (packageName == null || alias == null) {
24089            return null;
24090        }
24091        synchronized(mPackages) {
24092            final PackageParser.Package pkg = mPackages.get(packageName);
24093            if (pkg == null) {
24094                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24095                throw new IllegalArgumentException("Unknown package: " + packageName);
24096            }
24097            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24098            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24099                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24100                throw new IllegalArgumentException("Unknown package: " + packageName);
24101            }
24102            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24103            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24104        }
24105    }
24106
24107    @Override
24108    public KeySet getSigningKeySet(String packageName) {
24109        if (packageName == null) {
24110            return null;
24111        }
24112        synchronized(mPackages) {
24113            final int callingUid = Binder.getCallingUid();
24114            final int callingUserId = UserHandle.getUserId(callingUid);
24115            final PackageParser.Package pkg = mPackages.get(packageName);
24116            if (pkg == null) {
24117                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24118                throw new IllegalArgumentException("Unknown package: " + packageName);
24119            }
24120            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24121            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24122                // filter and pretend the package doesn't exist
24123                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24124                        + ", uid:" + callingUid);
24125                throw new IllegalArgumentException("Unknown package: " + packageName);
24126            }
24127            if (pkg.applicationInfo.uid != callingUid
24128                    && Process.SYSTEM_UID != callingUid) {
24129                throw new SecurityException("May not access signing KeySet of other apps.");
24130            }
24131            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24132            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24133        }
24134    }
24135
24136    @Override
24137    public boolean isPackageSignedByKeySet(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.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
24157            }
24158            return false;
24159        }
24160    }
24161
24162    @Override
24163    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
24164        final int callingUid = Binder.getCallingUid();
24165        if (getInstantAppPackageName(callingUid) != null) {
24166            return false;
24167        }
24168        if (packageName == null || ks == null) {
24169            return false;
24170        }
24171        synchronized(mPackages) {
24172            final PackageParser.Package pkg = mPackages.get(packageName);
24173            if (pkg == null
24174                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24175                            UserHandle.getUserId(callingUid))) {
24176                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24177                throw new IllegalArgumentException("Unknown package: " + packageName);
24178            }
24179            IBinder ksh = ks.getToken();
24180            if (ksh instanceof KeySetHandle) {
24181                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24182                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
24183            }
24184            return false;
24185        }
24186    }
24187
24188    private void deletePackageIfUnusedLPr(final String packageName) {
24189        PackageSetting ps = mSettings.mPackages.get(packageName);
24190        if (ps == null) {
24191            return;
24192        }
24193        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
24194            // TODO Implement atomic delete if package is unused
24195            // It is currently possible that the package will be deleted even if it is installed
24196            // after this method returns.
24197            mHandler.post(new Runnable() {
24198                public void run() {
24199                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24200                            0, PackageManager.DELETE_ALL_USERS);
24201                }
24202            });
24203        }
24204    }
24205
24206    /**
24207     * Check and throw if the given before/after packages would be considered a
24208     * downgrade.
24209     */
24210    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
24211            throws PackageManagerException {
24212        if (after.versionCode < before.mVersionCode) {
24213            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24214                    "Update version code " + after.versionCode + " is older than current "
24215                    + before.mVersionCode);
24216        } else if (after.versionCode == before.mVersionCode) {
24217            if (after.baseRevisionCode < before.baseRevisionCode) {
24218                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24219                        "Update base revision code " + after.baseRevisionCode
24220                        + " is older than current " + before.baseRevisionCode);
24221            }
24222
24223            if (!ArrayUtils.isEmpty(after.splitNames)) {
24224                for (int i = 0; i < after.splitNames.length; i++) {
24225                    final String splitName = after.splitNames[i];
24226                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
24227                    if (j != -1) {
24228                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
24229                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24230                                    "Update split " + splitName + " revision code "
24231                                    + after.splitRevisionCodes[i] + " is older than current "
24232                                    + before.splitRevisionCodes[j]);
24233                        }
24234                    }
24235                }
24236            }
24237        }
24238    }
24239
24240    private static class MoveCallbacks extends Handler {
24241        private static final int MSG_CREATED = 1;
24242        private static final int MSG_STATUS_CHANGED = 2;
24243
24244        private final RemoteCallbackList<IPackageMoveObserver>
24245                mCallbacks = new RemoteCallbackList<>();
24246
24247        private final SparseIntArray mLastStatus = new SparseIntArray();
24248
24249        public MoveCallbacks(Looper looper) {
24250            super(looper);
24251        }
24252
24253        public void register(IPackageMoveObserver callback) {
24254            mCallbacks.register(callback);
24255        }
24256
24257        public void unregister(IPackageMoveObserver callback) {
24258            mCallbacks.unregister(callback);
24259        }
24260
24261        @Override
24262        public void handleMessage(Message msg) {
24263            final SomeArgs args = (SomeArgs) msg.obj;
24264            final int n = mCallbacks.beginBroadcast();
24265            for (int i = 0; i < n; i++) {
24266                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
24267                try {
24268                    invokeCallback(callback, msg.what, args);
24269                } catch (RemoteException ignored) {
24270                }
24271            }
24272            mCallbacks.finishBroadcast();
24273            args.recycle();
24274        }
24275
24276        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
24277                throws RemoteException {
24278            switch (what) {
24279                case MSG_CREATED: {
24280                    callback.onCreated(args.argi1, (Bundle) args.arg2);
24281                    break;
24282                }
24283                case MSG_STATUS_CHANGED: {
24284                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
24285                    break;
24286                }
24287            }
24288        }
24289
24290        private void notifyCreated(int moveId, Bundle extras) {
24291            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
24292
24293            final SomeArgs args = SomeArgs.obtain();
24294            args.argi1 = moveId;
24295            args.arg2 = extras;
24296            obtainMessage(MSG_CREATED, args).sendToTarget();
24297        }
24298
24299        private void notifyStatusChanged(int moveId, int status) {
24300            notifyStatusChanged(moveId, status, -1);
24301        }
24302
24303        private void notifyStatusChanged(int moveId, int status, long estMillis) {
24304            Slog.v(TAG, "Move " + moveId + " status " + status);
24305
24306            final SomeArgs args = SomeArgs.obtain();
24307            args.argi1 = moveId;
24308            args.argi2 = status;
24309            args.arg3 = estMillis;
24310            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
24311
24312            synchronized (mLastStatus) {
24313                mLastStatus.put(moveId, status);
24314            }
24315        }
24316    }
24317
24318    private final static class OnPermissionChangeListeners extends Handler {
24319        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
24320
24321        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
24322                new RemoteCallbackList<>();
24323
24324        public OnPermissionChangeListeners(Looper looper) {
24325            super(looper);
24326        }
24327
24328        @Override
24329        public void handleMessage(Message msg) {
24330            switch (msg.what) {
24331                case MSG_ON_PERMISSIONS_CHANGED: {
24332                    final int uid = msg.arg1;
24333                    handleOnPermissionsChanged(uid);
24334                } break;
24335            }
24336        }
24337
24338        public void addListenerLocked(IOnPermissionsChangeListener listener) {
24339            mPermissionListeners.register(listener);
24340
24341        }
24342
24343        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
24344            mPermissionListeners.unregister(listener);
24345        }
24346
24347        public void onPermissionsChanged(int uid) {
24348            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
24349                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
24350            }
24351        }
24352
24353        private void handleOnPermissionsChanged(int uid) {
24354            final int count = mPermissionListeners.beginBroadcast();
24355            try {
24356                for (int i = 0; i < count; i++) {
24357                    IOnPermissionsChangeListener callback = mPermissionListeners
24358                            .getBroadcastItem(i);
24359                    try {
24360                        callback.onPermissionsChanged(uid);
24361                    } catch (RemoteException e) {
24362                        Log.e(TAG, "Permission listener is dead", e);
24363                    }
24364                }
24365            } finally {
24366                mPermissionListeners.finishBroadcast();
24367            }
24368        }
24369    }
24370
24371    private class PackageManagerInternalImpl extends PackageManagerInternal {
24372        @Override
24373        public void setLocationPackagesProvider(PackagesProvider provider) {
24374            synchronized (mPackages) {
24375                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
24376            }
24377        }
24378
24379        @Override
24380        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
24381            synchronized (mPackages) {
24382                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
24383            }
24384        }
24385
24386        @Override
24387        public void setSmsAppPackagesProvider(PackagesProvider provider) {
24388            synchronized (mPackages) {
24389                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
24390            }
24391        }
24392
24393        @Override
24394        public void setDialerAppPackagesProvider(PackagesProvider provider) {
24395            synchronized (mPackages) {
24396                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
24397            }
24398        }
24399
24400        @Override
24401        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
24402            synchronized (mPackages) {
24403                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
24404            }
24405        }
24406
24407        @Override
24408        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
24409            synchronized (mPackages) {
24410                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
24411            }
24412        }
24413
24414        @Override
24415        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
24416            synchronized (mPackages) {
24417                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
24418                        packageName, userId);
24419            }
24420        }
24421
24422        @Override
24423        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
24424            synchronized (mPackages) {
24425                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
24426                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
24427                        packageName, userId);
24428            }
24429        }
24430
24431        @Override
24432        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
24433            synchronized (mPackages) {
24434                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
24435                        packageName, userId);
24436            }
24437        }
24438
24439        @Override
24440        public void setKeepUninstalledPackages(final List<String> packageList) {
24441            Preconditions.checkNotNull(packageList);
24442            List<String> removedFromList = null;
24443            synchronized (mPackages) {
24444                if (mKeepUninstalledPackages != null) {
24445                    final int packagesCount = mKeepUninstalledPackages.size();
24446                    for (int i = 0; i < packagesCount; i++) {
24447                        String oldPackage = mKeepUninstalledPackages.get(i);
24448                        if (packageList != null && packageList.contains(oldPackage)) {
24449                            continue;
24450                        }
24451                        if (removedFromList == null) {
24452                            removedFromList = new ArrayList<>();
24453                        }
24454                        removedFromList.add(oldPackage);
24455                    }
24456                }
24457                mKeepUninstalledPackages = new ArrayList<>(packageList);
24458                if (removedFromList != null) {
24459                    final int removedCount = removedFromList.size();
24460                    for (int i = 0; i < removedCount; i++) {
24461                        deletePackageIfUnusedLPr(removedFromList.get(i));
24462                    }
24463                }
24464            }
24465        }
24466
24467        @Override
24468        public boolean isPermissionsReviewRequired(String packageName, int userId) {
24469            synchronized (mPackages) {
24470                // If we do not support permission review, done.
24471                if (!mPermissionReviewRequired) {
24472                    return false;
24473                }
24474
24475                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
24476                if (packageSetting == null) {
24477                    return false;
24478                }
24479
24480                // Permission review applies only to apps not supporting the new permission model.
24481                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
24482                    return false;
24483                }
24484
24485                // Legacy apps have the permission and get user consent on launch.
24486                PermissionsState permissionsState = packageSetting.getPermissionsState();
24487                return permissionsState.isPermissionReviewRequired(userId);
24488            }
24489        }
24490
24491        @Override
24492        public PackageInfo getPackageInfo(
24493                String packageName, int flags, int filterCallingUid, int userId) {
24494            return PackageManagerService.this
24495                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
24496                            flags, filterCallingUid, userId);
24497        }
24498
24499        @Override
24500        public ApplicationInfo getApplicationInfo(
24501                String packageName, int flags, int filterCallingUid, int userId) {
24502            return PackageManagerService.this
24503                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
24504        }
24505
24506        @Override
24507        public ActivityInfo getActivityInfo(
24508                ComponentName component, int flags, int filterCallingUid, int userId) {
24509            return PackageManagerService.this
24510                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
24511        }
24512
24513        @Override
24514        public List<ResolveInfo> queryIntentActivities(
24515                Intent intent, int flags, int filterCallingUid, int userId) {
24516            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
24517            return PackageManagerService.this
24518                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
24519                            userId, false /*resolveForStart*/);
24520        }
24521
24522        @Override
24523        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
24524                int userId) {
24525            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
24526        }
24527
24528        @Override
24529        public void setDeviceAndProfileOwnerPackages(
24530                int deviceOwnerUserId, String deviceOwnerPackage,
24531                SparseArray<String> profileOwnerPackages) {
24532            mProtectedPackages.setDeviceAndProfileOwnerPackages(
24533                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
24534        }
24535
24536        @Override
24537        public boolean isPackageDataProtected(int userId, String packageName) {
24538            return mProtectedPackages.isPackageDataProtected(userId, packageName);
24539        }
24540
24541        @Override
24542        public boolean isPackageEphemeral(int userId, String packageName) {
24543            synchronized (mPackages) {
24544                final PackageSetting ps = mSettings.mPackages.get(packageName);
24545                return ps != null ? ps.getInstantApp(userId) : false;
24546            }
24547        }
24548
24549        @Override
24550        public boolean wasPackageEverLaunched(String packageName, int userId) {
24551            synchronized (mPackages) {
24552                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
24553            }
24554        }
24555
24556        @Override
24557        public void grantRuntimePermission(String packageName, String name, int userId,
24558                boolean overridePolicy) {
24559            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
24560                    overridePolicy);
24561        }
24562
24563        @Override
24564        public void revokeRuntimePermission(String packageName, String name, int userId,
24565                boolean overridePolicy) {
24566            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
24567                    overridePolicy);
24568        }
24569
24570        @Override
24571        public String getNameForUid(int uid) {
24572            return PackageManagerService.this.getNameForUid(uid);
24573        }
24574
24575        @Override
24576        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
24577                Intent origIntent, String resolvedType, String callingPackage,
24578                Bundle verificationBundle, int userId) {
24579            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
24580                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
24581                    userId);
24582        }
24583
24584        @Override
24585        public void grantEphemeralAccess(int userId, Intent intent,
24586                int targetAppId, int ephemeralAppId) {
24587            synchronized (mPackages) {
24588                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
24589                        targetAppId, ephemeralAppId);
24590            }
24591        }
24592
24593        @Override
24594        public boolean isInstantAppInstallerComponent(ComponentName component) {
24595            synchronized (mPackages) {
24596                return mInstantAppInstallerActivity != null
24597                        && mInstantAppInstallerActivity.getComponentName().equals(component);
24598            }
24599        }
24600
24601        @Override
24602        public void pruneInstantApps() {
24603            mInstantAppRegistry.pruneInstantApps();
24604        }
24605
24606        @Override
24607        public String getSetupWizardPackageName() {
24608            return mSetupWizardPackage;
24609        }
24610
24611        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
24612            if (policy != null) {
24613                mExternalSourcesPolicy = policy;
24614            }
24615        }
24616
24617        @Override
24618        public boolean isPackagePersistent(String packageName) {
24619            synchronized (mPackages) {
24620                PackageParser.Package pkg = mPackages.get(packageName);
24621                return pkg != null
24622                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
24623                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
24624                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
24625                        : false;
24626            }
24627        }
24628
24629        @Override
24630        public List<PackageInfo> getOverlayPackages(int userId) {
24631            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
24632            synchronized (mPackages) {
24633                for (PackageParser.Package p : mPackages.values()) {
24634                    if (p.mOverlayTarget != null) {
24635                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
24636                        if (pkg != null) {
24637                            overlayPackages.add(pkg);
24638                        }
24639                    }
24640                }
24641            }
24642            return overlayPackages;
24643        }
24644
24645        @Override
24646        public List<String> getTargetPackageNames(int userId) {
24647            List<String> targetPackages = new ArrayList<>();
24648            synchronized (mPackages) {
24649                for (PackageParser.Package p : mPackages.values()) {
24650                    if (p.mOverlayTarget == null) {
24651                        targetPackages.add(p.packageName);
24652                    }
24653                }
24654            }
24655            return targetPackages;
24656        }
24657
24658        @Override
24659        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
24660                @Nullable List<String> overlayPackageNames) {
24661            synchronized (mPackages) {
24662                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
24663                    Slog.e(TAG, "failed to find package " + targetPackageName);
24664                    return false;
24665                }
24666                ArrayList<String> overlayPaths = null;
24667                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
24668                    final int N = overlayPackageNames.size();
24669                    overlayPaths = new ArrayList<>(N);
24670                    for (int i = 0; i < N; i++) {
24671                        final String packageName = overlayPackageNames.get(i);
24672                        final PackageParser.Package pkg = mPackages.get(packageName);
24673                        if (pkg == null) {
24674                            Slog.e(TAG, "failed to find package " + packageName);
24675                            return false;
24676                        }
24677                        overlayPaths.add(pkg.baseCodePath);
24678                    }
24679                }
24680
24681                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
24682                ps.setOverlayPaths(overlayPaths, userId);
24683                return true;
24684            }
24685        }
24686
24687        @Override
24688        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
24689                int flags, int userId) {
24690            return resolveIntentInternal(
24691                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
24692        }
24693
24694        @Override
24695        public ResolveInfo resolveService(Intent intent, String resolvedType,
24696                int flags, int userId, int callingUid) {
24697            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
24698        }
24699
24700        @Override
24701        public void addIsolatedUid(int isolatedUid, int ownerUid) {
24702            synchronized (mPackages) {
24703                mIsolatedOwners.put(isolatedUid, ownerUid);
24704            }
24705        }
24706
24707        @Override
24708        public void removeIsolatedUid(int isolatedUid) {
24709            synchronized (mPackages) {
24710                mIsolatedOwners.delete(isolatedUid);
24711            }
24712        }
24713
24714        @Override
24715        public int getUidTargetSdkVersion(int uid) {
24716            synchronized (mPackages) {
24717                return getUidTargetSdkVersionLockedLPr(uid);
24718            }
24719        }
24720
24721        @Override
24722        public boolean canAccessInstantApps(int callingUid, int userId) {
24723            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
24724        }
24725    }
24726
24727    @Override
24728    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
24729        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
24730        synchronized (mPackages) {
24731            final long identity = Binder.clearCallingIdentity();
24732            try {
24733                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
24734                        packageNames, userId);
24735            } finally {
24736                Binder.restoreCallingIdentity(identity);
24737            }
24738        }
24739    }
24740
24741    @Override
24742    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
24743        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
24744        synchronized (mPackages) {
24745            final long identity = Binder.clearCallingIdentity();
24746            try {
24747                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
24748                        packageNames, userId);
24749            } finally {
24750                Binder.restoreCallingIdentity(identity);
24751            }
24752        }
24753    }
24754
24755    private static void enforceSystemOrPhoneCaller(String tag) {
24756        int callingUid = Binder.getCallingUid();
24757        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24758            throw new SecurityException(
24759                    "Cannot call " + tag + " from UID " + callingUid);
24760        }
24761    }
24762
24763    boolean isHistoricalPackageUsageAvailable() {
24764        return mPackageUsage.isHistoricalPackageUsageAvailable();
24765    }
24766
24767    /**
24768     * Return a <b>copy</b> of the collection of packages known to the package manager.
24769     * @return A copy of the values of mPackages.
24770     */
24771    Collection<PackageParser.Package> getPackages() {
24772        synchronized (mPackages) {
24773            return new ArrayList<>(mPackages.values());
24774        }
24775    }
24776
24777    /**
24778     * Logs process start information (including base APK hash) to the security log.
24779     * @hide
24780     */
24781    @Override
24782    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24783            String apkFile, int pid) {
24784        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24785            return;
24786        }
24787        if (!SecurityLog.isLoggingEnabled()) {
24788            return;
24789        }
24790        Bundle data = new Bundle();
24791        data.putLong("startTimestamp", System.currentTimeMillis());
24792        data.putString("processName", processName);
24793        data.putInt("uid", uid);
24794        data.putString("seinfo", seinfo);
24795        data.putString("apkFile", apkFile);
24796        data.putInt("pid", pid);
24797        Message msg = mProcessLoggingHandler.obtainMessage(
24798                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24799        msg.setData(data);
24800        mProcessLoggingHandler.sendMessage(msg);
24801    }
24802
24803    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24804        return mCompilerStats.getPackageStats(pkgName);
24805    }
24806
24807    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24808        return getOrCreateCompilerPackageStats(pkg.packageName);
24809    }
24810
24811    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24812        return mCompilerStats.getOrCreatePackageStats(pkgName);
24813    }
24814
24815    public void deleteCompilerPackageStats(String pkgName) {
24816        mCompilerStats.deletePackageStats(pkgName);
24817    }
24818
24819    @Override
24820    public int getInstallReason(String packageName, int userId) {
24821        final int callingUid = Binder.getCallingUid();
24822        enforceCrossUserPermission(callingUid, userId,
24823                true /* requireFullPermission */, false /* checkShell */,
24824                "get install reason");
24825        synchronized (mPackages) {
24826            final PackageSetting ps = mSettings.mPackages.get(packageName);
24827            if (filterAppAccessLPr(ps, callingUid, userId)) {
24828                return PackageManager.INSTALL_REASON_UNKNOWN;
24829            }
24830            if (ps != null) {
24831                return ps.getInstallReason(userId);
24832            }
24833        }
24834        return PackageManager.INSTALL_REASON_UNKNOWN;
24835    }
24836
24837    @Override
24838    public boolean canRequestPackageInstalls(String packageName, int userId) {
24839        return canRequestPackageInstallsInternal(packageName, 0, userId,
24840                true /* throwIfPermNotDeclared*/);
24841    }
24842
24843    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24844            boolean throwIfPermNotDeclared) {
24845        int callingUid = Binder.getCallingUid();
24846        int uid = getPackageUid(packageName, 0, userId);
24847        if (callingUid != uid && callingUid != Process.ROOT_UID
24848                && callingUid != Process.SYSTEM_UID) {
24849            throw new SecurityException(
24850                    "Caller uid " + callingUid + " does not own package " + packageName);
24851        }
24852        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24853        if (info == null) {
24854            return false;
24855        }
24856        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24857            return false;
24858        }
24859        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24860        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24861        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24862            if (throwIfPermNotDeclared) {
24863                throw new SecurityException("Need to declare " + appOpPermission
24864                        + " to call this api");
24865            } else {
24866                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24867                return false;
24868            }
24869        }
24870        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24871            return false;
24872        }
24873        if (mExternalSourcesPolicy != null) {
24874            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24875            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24876                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24877            }
24878        }
24879        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
24880    }
24881
24882    @Override
24883    public ComponentName getInstantAppResolverSettingsComponent() {
24884        return mInstantAppResolverSettingsComponent;
24885    }
24886
24887    @Override
24888    public ComponentName getInstantAppInstallerComponent() {
24889        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24890            return null;
24891        }
24892        return mInstantAppInstallerActivity == null
24893                ? null : mInstantAppInstallerActivity.getComponentName();
24894    }
24895
24896    @Override
24897    public String getInstantAppAndroidId(String packageName, int userId) {
24898        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
24899                "getInstantAppAndroidId");
24900        enforceCrossUserPermission(Binder.getCallingUid(), userId,
24901                true /* requireFullPermission */, false /* checkShell */,
24902                "getInstantAppAndroidId");
24903        // Make sure the target is an Instant App.
24904        if (!isInstantApp(packageName, userId)) {
24905            return null;
24906        }
24907        synchronized (mPackages) {
24908            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
24909        }
24910    }
24911}
24912
24913interface PackageSender {
24914    void sendPackageBroadcast(final String action, final String pkg,
24915        final Bundle extras, final int flags, final String targetPkg,
24916        final IIntentReceiver finishedReceiver, final int[] userIds);
24917    void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
24918        int appId, int... userIds);
24919}
24920