PackageManagerService.java revision 4f475cc140ca3127770fbfd4f37ccf0603dc2c2a
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.DELETE_PACKAGES;
20import static android.Manifest.permission.INSTALL_PACKAGES;
21import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS;
22import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
23import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
24import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
25import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
31import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
39import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
40import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
41import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
49import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
54import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
55import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
56import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
57import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
58import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
59import static android.content.pm.PackageManager.INSTALL_INTERNAL;
60import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
65import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
66import static android.content.pm.PackageManager.MATCH_ALL;
67import static android.content.pm.PackageManager.MATCH_ANY_USER;
68import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
70import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
71import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
72import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
73import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
74import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
75import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
76import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
77import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
78import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
79import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
80import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER;
81import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
82import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
83import static android.content.pm.PackageManager.PERMISSION_DENIED;
84import static android.content.pm.PackageManager.PERMISSION_GRANTED;
85import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
86import static android.content.pm.PackageParser.isApkFile;
87import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
88import static android.os.storage.StorageManager.FLAG_STORAGE_CE;
89import static android.os.storage.StorageManager.FLAG_STORAGE_DE;
90import static android.system.OsConstants.O_CREAT;
91import static android.system.OsConstants.O_RDWR;
92
93import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
94import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
95import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
96import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
97import static com.android.internal.util.ArrayUtils.appendInt;
98import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
99import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
100import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
101import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
102import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
103import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
104import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
105import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
106import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
107import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
108
109import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
110
111import android.Manifest;
112import android.annotation.IntDef;
113import android.annotation.NonNull;
114import android.annotation.Nullable;
115import android.app.ActivityManager;
116import android.app.AppOpsManager;
117import android.app.IActivityManager;
118import android.app.ResourcesManager;
119import android.app.admin.IDevicePolicyManager;
120import android.app.admin.SecurityLog;
121import android.app.backup.IBackupManager;
122import android.content.BroadcastReceiver;
123import android.content.ComponentName;
124import android.content.ContentResolver;
125import android.content.Context;
126import android.content.IIntentReceiver;
127import android.content.Intent;
128import android.content.IntentFilter;
129import android.content.IntentSender;
130import android.content.IntentSender.SendIntentException;
131import android.content.ServiceConnection;
132import android.content.pm.ActivityInfo;
133import android.content.pm.ApplicationInfo;
134import android.content.pm.AppsQueryHelper;
135import android.content.pm.AuxiliaryResolveInfo;
136import android.content.pm.ChangedPackages;
137import android.content.pm.ComponentInfo;
138import android.content.pm.FallbackCategoryProvider;
139import android.content.pm.FeatureInfo;
140import android.content.pm.IDexModuleRegisterCallback;
141import android.content.pm.IOnPermissionsChangeListener;
142import android.content.pm.IPackageDataObserver;
143import android.content.pm.IPackageDeleteObserver;
144import android.content.pm.IPackageDeleteObserver2;
145import android.content.pm.IPackageInstallObserver2;
146import android.content.pm.IPackageInstaller;
147import android.content.pm.IPackageManager;
148import android.content.pm.IPackageManagerNative;
149import android.content.pm.IPackageMoveObserver;
150import android.content.pm.IPackageStatsObserver;
151import android.content.pm.InstantAppInfo;
152import android.content.pm.InstantAppRequest;
153import android.content.pm.InstantAppResolveInfo;
154import android.content.pm.InstrumentationInfo;
155import android.content.pm.IntentFilterVerificationInfo;
156import android.content.pm.KeySet;
157import android.content.pm.PackageCleanItem;
158import android.content.pm.PackageInfo;
159import android.content.pm.PackageInfoLite;
160import android.content.pm.PackageInstaller;
161import android.content.pm.PackageManager;
162import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
163import android.content.pm.PackageManagerInternal;
164import android.content.pm.PackageParser;
165import android.content.pm.PackageParser.ActivityIntentInfo;
166import android.content.pm.PackageParser.PackageLite;
167import android.content.pm.PackageParser.PackageParserException;
168import android.content.pm.PackageStats;
169import android.content.pm.PackageUserState;
170import android.content.pm.ParceledListSlice;
171import android.content.pm.PermissionGroupInfo;
172import android.content.pm.PermissionInfo;
173import android.content.pm.ProviderInfo;
174import android.content.pm.ResolveInfo;
175import android.content.pm.ServiceInfo;
176import android.content.pm.SharedLibraryInfo;
177import android.content.pm.Signature;
178import android.content.pm.UserInfo;
179import android.content.pm.VerifierDeviceIdentity;
180import android.content.pm.VerifierInfo;
181import android.content.pm.VersionedPackage;
182import android.content.res.Resources;
183import android.database.ContentObserver;
184import android.graphics.Bitmap;
185import android.hardware.display.DisplayManager;
186import android.net.Uri;
187import android.os.Binder;
188import android.os.Build;
189import android.os.Bundle;
190import android.os.Debug;
191import android.os.Environment;
192import android.os.Environment.UserEnvironment;
193import android.os.FileUtils;
194import android.os.Handler;
195import android.os.IBinder;
196import android.os.Looper;
197import android.os.Message;
198import android.os.Parcel;
199import android.os.ParcelFileDescriptor;
200import android.os.PatternMatcher;
201import android.os.Process;
202import android.os.RemoteCallbackList;
203import android.os.RemoteException;
204import android.os.ResultReceiver;
205import android.os.SELinux;
206import android.os.ServiceManager;
207import android.os.ShellCallback;
208import android.os.SystemClock;
209import android.os.SystemProperties;
210import android.os.Trace;
211import android.os.UserHandle;
212import android.os.UserManager;
213import android.os.UserManagerInternal;
214import android.os.storage.IStorageManager;
215import android.os.storage.StorageEventListener;
216import android.os.storage.StorageManager;
217import android.os.storage.StorageManagerInternal;
218import android.os.storage.VolumeInfo;
219import android.os.storage.VolumeRecord;
220import android.provider.Settings.Global;
221import android.provider.Settings.Secure;
222import android.security.KeyStore;
223import android.security.SystemKeyStore;
224import android.service.pm.PackageServiceDumpProto;
225import android.system.ErrnoException;
226import android.system.Os;
227import android.text.TextUtils;
228import android.text.format.DateUtils;
229import android.util.ArrayMap;
230import android.util.ArraySet;
231import android.util.Base64;
232import android.util.TimingsTraceLog;
233import android.util.DisplayMetrics;
234import android.util.EventLog;
235import android.util.ExceptionUtils;
236import android.util.Log;
237import android.util.LogPrinter;
238import android.util.MathUtils;
239import android.util.PackageUtils;
240import android.util.Pair;
241import android.util.PrintStreamPrinter;
242import android.util.Slog;
243import android.util.SparseArray;
244import android.util.SparseBooleanArray;
245import android.util.SparseIntArray;
246import android.util.Xml;
247import android.util.jar.StrictJarFile;
248import android.util.proto.ProtoOutputStream;
249import android.view.Display;
250
251import com.android.internal.R;
252import com.android.internal.annotations.GuardedBy;
253import com.android.internal.app.IMediaContainerService;
254import com.android.internal.app.ResolverActivity;
255import com.android.internal.content.NativeLibraryHelper;
256import com.android.internal.content.PackageHelper;
257import com.android.internal.logging.MetricsLogger;
258import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
259import com.android.internal.os.IParcelFileDescriptorFactory;
260import com.android.internal.os.RoSystemProperties;
261import com.android.internal.os.SomeArgs;
262import com.android.internal.os.Zygote;
263import com.android.internal.telephony.CarrierAppUtils;
264import com.android.internal.util.ArrayUtils;
265import com.android.internal.util.ConcurrentUtils;
266import com.android.internal.util.DumpUtils;
267import com.android.internal.util.FastPrintWriter;
268import com.android.internal.util.FastXmlSerializer;
269import com.android.internal.util.IndentingPrintWriter;
270import com.android.internal.util.Preconditions;
271import com.android.internal.util.XmlUtils;
272import com.android.server.AttributeCache;
273import com.android.server.DeviceIdleController;
274import com.android.server.EventLogTags;
275import com.android.server.FgThread;
276import com.android.server.IntentResolver;
277import com.android.server.LocalServices;
278import com.android.server.LockGuard;
279import com.android.server.ServiceThread;
280import com.android.server.SystemConfig;
281import com.android.server.SystemServerInitThreadPool;
282import com.android.server.Watchdog;
283import com.android.server.net.NetworkPolicyManagerInternal;
284import com.android.server.pm.Installer.InstallerException;
285import com.android.server.pm.PermissionsState.PermissionState;
286import com.android.server.pm.Settings.DatabaseVersion;
287import com.android.server.pm.Settings.VersionInfo;
288import com.android.server.pm.dex.DexManager;
289import com.android.server.pm.dex.DexoptOptions;
290import com.android.server.pm.dex.PackageDexUsage;
291import com.android.server.storage.DeviceStorageMonitorInternal;
292
293import dalvik.system.CloseGuard;
294import dalvik.system.DexFile;
295import dalvik.system.VMRuntime;
296
297import libcore.io.IoUtils;
298import libcore.io.Streams;
299import libcore.util.EmptyArray;
300
301import org.xmlpull.v1.XmlPullParser;
302import org.xmlpull.v1.XmlPullParserException;
303import org.xmlpull.v1.XmlSerializer;
304
305import java.io.BufferedOutputStream;
306import java.io.BufferedReader;
307import java.io.ByteArrayInputStream;
308import java.io.ByteArrayOutputStream;
309import java.io.File;
310import java.io.FileDescriptor;
311import java.io.FileInputStream;
312import java.io.FileOutputStream;
313import java.io.FileReader;
314import java.io.FilenameFilter;
315import java.io.IOException;
316import java.io.InputStream;
317import java.io.OutputStream;
318import java.io.PrintWriter;
319import java.lang.annotation.Retention;
320import java.lang.annotation.RetentionPolicy;
321import java.nio.charset.StandardCharsets;
322import java.security.DigestInputStream;
323import java.security.MessageDigest;
324import java.security.NoSuchAlgorithmException;
325import java.security.PublicKey;
326import java.security.SecureRandom;
327import java.security.cert.Certificate;
328import java.security.cert.CertificateEncodingException;
329import java.security.cert.CertificateException;
330import java.text.SimpleDateFormat;
331import java.util.ArrayList;
332import java.util.Arrays;
333import java.util.Collection;
334import java.util.Collections;
335import java.util.Comparator;
336import java.util.Date;
337import java.util.HashMap;
338import java.util.HashSet;
339import java.util.Iterator;
340import java.util.List;
341import java.util.Map;
342import java.util.Objects;
343import java.util.Set;
344import java.util.concurrent.CountDownLatch;
345import java.util.concurrent.Future;
346import java.util.concurrent.TimeUnit;
347import java.util.concurrent.atomic.AtomicBoolean;
348import java.util.concurrent.atomic.AtomicInteger;
349import java.util.zip.GZIPInputStream;
350
351/**
352 * Keep track of all those APKs everywhere.
353 * <p>
354 * Internally there are two important locks:
355 * <ul>
356 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
357 * and other related state. It is a fine-grained lock that should only be held
358 * momentarily, as it's one of the most contended locks in the system.
359 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
360 * operations typically involve heavy lifting of application data on disk. Since
361 * {@code installd} is single-threaded, and it's operations can often be slow,
362 * this lock should never be acquired while already holding {@link #mPackages}.
363 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
364 * holding {@link #mInstallLock}.
365 * </ul>
366 * Many internal methods rely on the caller to hold the appropriate locks, and
367 * this contract is expressed through method name suffixes:
368 * <ul>
369 * <li>fooLI(): the caller must hold {@link #mInstallLock}
370 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
371 * being modified must be frozen
372 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
373 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
374 * </ul>
375 * <p>
376 * Because this class is very central to the platform's security; please run all
377 * CTS and unit tests whenever making modifications:
378 *
379 * <pre>
380 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
381 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
382 * </pre>
383 */
384public class PackageManagerService extends IPackageManager.Stub
385        implements PackageSender {
386    static final String TAG = "PackageManager";
387    static final boolean DEBUG_SETTINGS = false;
388    static final boolean DEBUG_PREFERRED = false;
389    static final boolean DEBUG_UPGRADE = false;
390    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
391    private static final boolean DEBUG_BACKUP = false;
392    private static final boolean DEBUG_INSTALL = false;
393    private static final boolean DEBUG_REMOVE = false;
394    private static final boolean DEBUG_BROADCASTS = false;
395    private static final boolean DEBUG_SHOW_INFO = false;
396    private static final boolean DEBUG_PACKAGE_INFO = false;
397    private static final boolean DEBUG_INTENT_MATCHING = false;
398    private static final boolean DEBUG_PACKAGE_SCANNING = false;
399    private static final boolean DEBUG_VERIFY = false;
400    private static final boolean DEBUG_FILTERS = false;
401    private static final boolean DEBUG_PERMISSIONS = false;
402    private static final boolean DEBUG_SHARED_LIBRARIES = false;
403    private static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
404
405    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
406    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
407    // user, but by default initialize to this.
408    public static final boolean DEBUG_DEXOPT = false;
409
410    private static final boolean DEBUG_ABI_SELECTION = false;
411    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
412    private static final boolean DEBUG_TRIAGED_MISSING = false;
413    private static final boolean DEBUG_APP_DATA = false;
414
415    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
416    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
417
418    private static final boolean HIDE_EPHEMERAL_APIS = false;
419
420    private static final boolean ENABLE_FREE_CACHE_V2 =
421            SystemProperties.getBoolean("fw.free_cache_v2", true);
422
423    private static final int RADIO_UID = Process.PHONE_UID;
424    private static final int LOG_UID = Process.LOG_UID;
425    private static final int NFC_UID = Process.NFC_UID;
426    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
427    private static final int SHELL_UID = Process.SHELL_UID;
428
429    // Cap the size of permission trees that 3rd party apps can define
430    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
431
432    // Suffix used during package installation when copying/moving
433    // package apks to install directory.
434    private static final String INSTALL_PACKAGE_SUFFIX = "-";
435
436    static final int SCAN_NO_DEX = 1<<1;
437    static final int SCAN_FORCE_DEX = 1<<2;
438    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
439    static final int SCAN_NEW_INSTALL = 1<<4;
440    static final int SCAN_UPDATE_TIME = 1<<5;
441    static final int SCAN_BOOTING = 1<<6;
442    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
443    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
444    static final int SCAN_REPLACING = 1<<9;
445    static final int SCAN_REQUIRE_KNOWN = 1<<10;
446    static final int SCAN_MOVE = 1<<11;
447    static final int SCAN_INITIAL = 1<<12;
448    static final int SCAN_CHECK_ONLY = 1<<13;
449    static final int SCAN_DONT_KILL_APP = 1<<14;
450    static final int SCAN_IGNORE_FROZEN = 1<<15;
451    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
452    static final int SCAN_AS_INSTANT_APP = 1<<17;
453    static final int SCAN_AS_FULL_APP = 1<<18;
454    static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<19;
455    /** Should not be with the scan flags */
456    static final int FLAGS_REMOVE_CHATTY = 1<<31;
457
458    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
459    /** Extension of the compressed packages */
460    private final static String COMPRESSED_EXTENSION = ".gz";
461    /** Suffix of stub packages on the system partition */
462    private final static String STUB_SUFFIX = "-Stub";
463
464    private static final int[] EMPTY_INT_ARRAY = new int[0];
465
466    private static final int TYPE_UNKNOWN = 0;
467    private static final int TYPE_ACTIVITY = 1;
468    private static final int TYPE_RECEIVER = 2;
469    private static final int TYPE_SERVICE = 3;
470    private static final int TYPE_PROVIDER = 4;
471    @IntDef(prefix = { "TYPE_" }, value = {
472            TYPE_UNKNOWN,
473            TYPE_ACTIVITY,
474            TYPE_RECEIVER,
475            TYPE_SERVICE,
476            TYPE_PROVIDER,
477    })
478    @Retention(RetentionPolicy.SOURCE)
479    public @interface ComponentType {}
480
481    /**
482     * Timeout (in milliseconds) after which the watchdog should declare that
483     * our handler thread is wedged.  The usual default for such things is one
484     * minute but we sometimes do very lengthy I/O operations on this thread,
485     * such as installing multi-gigabyte applications, so ours needs to be longer.
486     */
487    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
488
489    /**
490     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
491     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
492     * settings entry if available, otherwise we use the hardcoded default.  If it's been
493     * more than this long since the last fstrim, we force one during the boot sequence.
494     *
495     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
496     * one gets run at the next available charging+idle time.  This final mandatory
497     * no-fstrim check kicks in only of the other scheduling criteria is never met.
498     */
499    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
500
501    /**
502     * Whether verification is enabled by default.
503     */
504    private static final boolean DEFAULT_VERIFY_ENABLE = true;
505
506    /**
507     * The default maximum time to wait for the verification agent to return in
508     * milliseconds.
509     */
510    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
511
512    /**
513     * The default response for package verification timeout.
514     *
515     * This can be either PackageManager.VERIFICATION_ALLOW or
516     * PackageManager.VERIFICATION_REJECT.
517     */
518    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
519
520    static final String PLATFORM_PACKAGE_NAME = "android";
521
522    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
523
524    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
525            DEFAULT_CONTAINER_PACKAGE,
526            "com.android.defcontainer.DefaultContainerService");
527
528    private static final String KILL_APP_REASON_GIDS_CHANGED =
529            "permission grant or revoke changed gids";
530
531    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
532            "permissions revoked";
533
534    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
535
536    private static final String PACKAGE_SCHEME = "package";
537
538    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
539
540    /** Permission grant: not grant the permission. */
541    private static final int GRANT_DENIED = 1;
542
543    /** Permission grant: grant the permission as an install permission. */
544    private static final int GRANT_INSTALL = 2;
545
546    /** Permission grant: grant the permission as a runtime one. */
547    private static final int GRANT_RUNTIME = 3;
548
549    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
550    private static final int GRANT_UPGRADE = 4;
551
552    /** Canonical intent used to identify what counts as a "web browser" app */
553    private static final Intent sBrowserIntent;
554    static {
555        sBrowserIntent = new Intent();
556        sBrowserIntent.setAction(Intent.ACTION_VIEW);
557        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
558        sBrowserIntent.setData(Uri.parse("http:"));
559    }
560
561    /**
562     * The set of all protected actions [i.e. those actions for which a high priority
563     * intent filter is disallowed].
564     */
565    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
566    static {
567        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
568        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
569        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
570        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
571    }
572
573    // Compilation reasons.
574    public static final int REASON_FIRST_BOOT = 0;
575    public static final int REASON_BOOT = 1;
576    public static final int REASON_INSTALL = 2;
577    public static final int REASON_BACKGROUND_DEXOPT = 3;
578    public static final int REASON_AB_OTA = 4;
579    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
580    public static final int REASON_SHARED = 6;
581
582    public static final int REASON_LAST = REASON_SHARED;
583
584    /** All dangerous permission names in the same order as the events in MetricsEvent */
585    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
586            Manifest.permission.READ_CALENDAR,
587            Manifest.permission.WRITE_CALENDAR,
588            Manifest.permission.CAMERA,
589            Manifest.permission.READ_CONTACTS,
590            Manifest.permission.WRITE_CONTACTS,
591            Manifest.permission.GET_ACCOUNTS,
592            Manifest.permission.ACCESS_FINE_LOCATION,
593            Manifest.permission.ACCESS_COARSE_LOCATION,
594            Manifest.permission.RECORD_AUDIO,
595            Manifest.permission.READ_PHONE_STATE,
596            Manifest.permission.CALL_PHONE,
597            Manifest.permission.READ_CALL_LOG,
598            Manifest.permission.WRITE_CALL_LOG,
599            Manifest.permission.ADD_VOICEMAIL,
600            Manifest.permission.USE_SIP,
601            Manifest.permission.PROCESS_OUTGOING_CALLS,
602            Manifest.permission.READ_CELL_BROADCASTS,
603            Manifest.permission.BODY_SENSORS,
604            Manifest.permission.SEND_SMS,
605            Manifest.permission.RECEIVE_SMS,
606            Manifest.permission.READ_SMS,
607            Manifest.permission.RECEIVE_WAP_PUSH,
608            Manifest.permission.RECEIVE_MMS,
609            Manifest.permission.READ_EXTERNAL_STORAGE,
610            Manifest.permission.WRITE_EXTERNAL_STORAGE,
611            Manifest.permission.READ_PHONE_NUMBERS,
612            Manifest.permission.ANSWER_PHONE_CALLS);
613
614
615    /**
616     * Version number for the package parser cache. Increment this whenever the format or
617     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
618     */
619    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
620
621    /**
622     * Whether the package parser cache is enabled.
623     */
624    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
625
626    final ServiceThread mHandlerThread;
627
628    final PackageHandler mHandler;
629
630    private final ProcessLoggingHandler mProcessLoggingHandler;
631
632    /**
633     * Messages for {@link #mHandler} that need to wait for system ready before
634     * being dispatched.
635     */
636    private ArrayList<Message> mPostSystemReadyMessages;
637
638    final int mSdkVersion = Build.VERSION.SDK_INT;
639
640    final Context mContext;
641    final boolean mFactoryTest;
642    final boolean mOnlyCore;
643    final DisplayMetrics mMetrics;
644    final int mDefParseFlags;
645    final String[] mSeparateProcesses;
646    final boolean mIsUpgrade;
647    final boolean mIsPreNUpgrade;
648    final boolean mIsPreNMR1Upgrade;
649
650    // Have we told the Activity Manager to whitelist the default container service by uid yet?
651    @GuardedBy("mPackages")
652    boolean mDefaultContainerWhitelisted = false;
653
654    @GuardedBy("mPackages")
655    private boolean mDexOptDialogShown;
656
657    /** The location for ASEC container files on internal storage. */
658    final String mAsecInternalPath;
659
660    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
661    // LOCK HELD.  Can be called with mInstallLock held.
662    @GuardedBy("mInstallLock")
663    final Installer mInstaller;
664
665    /** Directory where installed third-party apps stored */
666    final File mAppInstallDir;
667
668    /**
669     * Directory to which applications installed internally have their
670     * 32 bit native libraries copied.
671     */
672    private File mAppLib32InstallDir;
673
674    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
675    // apps.
676    final File mDrmAppPrivateInstallDir;
677
678    // ----------------------------------------------------------------
679
680    // Lock for state used when installing and doing other long running
681    // operations.  Methods that must be called with this lock held have
682    // the suffix "LI".
683    final Object mInstallLock = new Object();
684
685    // ----------------------------------------------------------------
686
687    // Keys are String (package name), values are Package.  This also serves
688    // as the lock for the global state.  Methods that must be called with
689    // this lock held have the prefix "LP".
690    @GuardedBy("mPackages")
691    final ArrayMap<String, PackageParser.Package> mPackages =
692            new ArrayMap<String, PackageParser.Package>();
693
694    final ArrayMap<String, Set<String>> mKnownCodebase =
695            new ArrayMap<String, Set<String>>();
696
697    // Keys are isolated uids and values are the uid of the application
698    // that created the isolated proccess.
699    @GuardedBy("mPackages")
700    final SparseIntArray mIsolatedOwners = new SparseIntArray();
701
702    /**
703     * Tracks new system packages [received in an OTA] that we expect to
704     * find updated user-installed versions. Keys are package name, values
705     * are package location.
706     */
707    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
708    /**
709     * Tracks high priority intent filters for protected actions. During boot, certain
710     * filter actions are protected and should never be allowed to have a high priority
711     * intent filter for them. However, there is one, and only one exception -- the
712     * setup wizard. It must be able to define a high priority intent filter for these
713     * actions to ensure there are no escapes from the wizard. We need to delay processing
714     * of these during boot as we need to look at all of the system packages in order
715     * to know which component is the setup wizard.
716     */
717    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
718    /**
719     * Whether or not processing protected filters should be deferred.
720     */
721    private boolean mDeferProtectedFilters = true;
722
723    /**
724     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
725     */
726    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
727    /**
728     * Whether or not system app permissions should be promoted from install to runtime.
729     */
730    boolean mPromoteSystemApps;
731
732    @GuardedBy("mPackages")
733    final Settings mSettings;
734
735    /**
736     * Set of package names that are currently "frozen", which means active
737     * surgery is being done on the code/data for that package. The platform
738     * will refuse to launch frozen packages to avoid race conditions.
739     *
740     * @see PackageFreezer
741     */
742    @GuardedBy("mPackages")
743    final ArraySet<String> mFrozenPackages = new ArraySet<>();
744
745    final ProtectedPackages mProtectedPackages;
746
747    @GuardedBy("mLoadedVolumes")
748    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
749
750    boolean mFirstBoot;
751
752    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
753
754    // System configuration read by SystemConfig.
755    final int[] mGlobalGids;
756    final SparseArray<ArraySet<String>> mSystemPermissions;
757    @GuardedBy("mAvailableFeatures")
758    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
759
760    // If mac_permissions.xml was found for seinfo labeling.
761    boolean mFoundPolicyFile;
762
763    private final InstantAppRegistry mInstantAppRegistry;
764
765    @GuardedBy("mPackages")
766    int mChangedPackagesSequenceNumber;
767    /**
768     * List of changed [installed, removed or updated] packages.
769     * mapping from user id -> sequence number -> package name
770     */
771    @GuardedBy("mPackages")
772    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
773    /**
774     * The sequence number of the last change to a package.
775     * mapping from user id -> package name -> sequence number
776     */
777    @GuardedBy("mPackages")
778    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
779
780    class PackageParserCallback implements PackageParser.Callback {
781        @Override public final boolean hasFeature(String feature) {
782            return PackageManagerService.this.hasSystemFeature(feature, 0);
783        }
784
785        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
786                Collection<PackageParser.Package> allPackages, String targetPackageName) {
787            List<PackageParser.Package> overlayPackages = null;
788            for (PackageParser.Package p : allPackages) {
789                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
790                    if (overlayPackages == null) {
791                        overlayPackages = new ArrayList<PackageParser.Package>();
792                    }
793                    overlayPackages.add(p);
794                }
795            }
796            if (overlayPackages != null) {
797                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
798                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
799                        return p1.mOverlayPriority - p2.mOverlayPriority;
800                    }
801                };
802                Collections.sort(overlayPackages, cmp);
803            }
804            return overlayPackages;
805        }
806
807        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
808                String targetPackageName, String targetPath) {
809            if ("android".equals(targetPackageName)) {
810                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
811                // native AssetManager.
812                return null;
813            }
814            List<PackageParser.Package> overlayPackages =
815                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
816            if (overlayPackages == null || overlayPackages.isEmpty()) {
817                return null;
818            }
819            List<String> overlayPathList = null;
820            for (PackageParser.Package overlayPackage : overlayPackages) {
821                if (targetPath == null) {
822                    if (overlayPathList == null) {
823                        overlayPathList = new ArrayList<String>();
824                    }
825                    overlayPathList.add(overlayPackage.baseCodePath);
826                    continue;
827                }
828
829                try {
830                    // Creates idmaps for system to parse correctly the Android manifest of the
831                    // target package.
832                    //
833                    // OverlayManagerService will update each of them with a correct gid from its
834                    // target package app id.
835                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
836                            UserHandle.getSharedAppGid(
837                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
838                    if (overlayPathList == null) {
839                        overlayPathList = new ArrayList<String>();
840                    }
841                    overlayPathList.add(overlayPackage.baseCodePath);
842                } catch (InstallerException e) {
843                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
844                            overlayPackage.baseCodePath);
845                }
846            }
847            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
848        }
849
850        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
851            synchronized (mPackages) {
852                return getStaticOverlayPathsLocked(
853                        mPackages.values(), targetPackageName, targetPath);
854            }
855        }
856
857        @Override public final String[] getOverlayApks(String targetPackageName) {
858            return getStaticOverlayPaths(targetPackageName, null);
859        }
860
861        @Override public final String[] getOverlayPaths(String targetPackageName,
862                String targetPath) {
863            return getStaticOverlayPaths(targetPackageName, targetPath);
864        }
865    };
866
867    class ParallelPackageParserCallback extends PackageParserCallback {
868        List<PackageParser.Package> mOverlayPackages = null;
869
870        void findStaticOverlayPackages() {
871            synchronized (mPackages) {
872                for (PackageParser.Package p : mPackages.values()) {
873                    if (p.mIsStaticOverlay) {
874                        if (mOverlayPackages == null) {
875                            mOverlayPackages = new ArrayList<PackageParser.Package>();
876                        }
877                        mOverlayPackages.add(p);
878                    }
879                }
880            }
881        }
882
883        @Override
884        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
885            // We can trust mOverlayPackages without holding mPackages because package uninstall
886            // can't happen while running parallel parsing.
887            // Moreover holding mPackages on each parsing thread causes dead-lock.
888            return mOverlayPackages == null ? null :
889                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
890        }
891    }
892
893    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
894    final ParallelPackageParserCallback mParallelPackageParserCallback =
895            new ParallelPackageParserCallback();
896
897    public static final class SharedLibraryEntry {
898        public final @Nullable String path;
899        public final @Nullable String apk;
900        public final @NonNull SharedLibraryInfo info;
901
902        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
903                String declaringPackageName, int declaringPackageVersionCode) {
904            path = _path;
905            apk = _apk;
906            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
907                    declaringPackageName, declaringPackageVersionCode), null);
908        }
909    }
910
911    // Currently known shared libraries.
912    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
913    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
914            new ArrayMap<>();
915
916    // All available activities, for your resolving pleasure.
917    final ActivityIntentResolver mActivities =
918            new ActivityIntentResolver();
919
920    // All available receivers, for your resolving pleasure.
921    final ActivityIntentResolver mReceivers =
922            new ActivityIntentResolver();
923
924    // All available services, for your resolving pleasure.
925    final ServiceIntentResolver mServices = new ServiceIntentResolver();
926
927    // All available providers, for your resolving pleasure.
928    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
929
930    // Mapping from provider base names (first directory in content URI codePath)
931    // to the provider information.
932    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
933            new ArrayMap<String, PackageParser.Provider>();
934
935    // Mapping from instrumentation class names to info about them.
936    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
937            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
938
939    // Mapping from permission names to info about them.
940    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
941            new ArrayMap<String, PackageParser.PermissionGroup>();
942
943    // Packages whose data we have transfered into another package, thus
944    // should no longer exist.
945    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
946
947    // Broadcast actions that are only available to the system.
948    @GuardedBy("mProtectedBroadcasts")
949    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
950
951    /** List of packages waiting for verification. */
952    final SparseArray<PackageVerificationState> mPendingVerification
953            = new SparseArray<PackageVerificationState>();
954
955    /** Set of packages associated with each app op permission. */
956    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
957
958    final PackageInstallerService mInstallerService;
959
960    private final PackageDexOptimizer mPackageDexOptimizer;
961    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
962    // is used by other apps).
963    private final DexManager mDexManager;
964
965    private AtomicInteger mNextMoveId = new AtomicInteger();
966    private final MoveCallbacks mMoveCallbacks;
967
968    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
969
970    // Cache of users who need badging.
971    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
972
973    /** Token for keys in mPendingVerification. */
974    private int mPendingVerificationToken = 0;
975
976    volatile boolean mSystemReady;
977    volatile boolean mSafeMode;
978    volatile boolean mHasSystemUidErrors;
979    private volatile boolean mEphemeralAppsDisabled;
980
981    ApplicationInfo mAndroidApplication;
982    final ActivityInfo mResolveActivity = new ActivityInfo();
983    final ResolveInfo mResolveInfo = new ResolveInfo();
984    ComponentName mResolveComponentName;
985    PackageParser.Package mPlatformPackage;
986    ComponentName mCustomResolverComponentName;
987
988    boolean mResolverReplaced = false;
989
990    private final @Nullable ComponentName mIntentFilterVerifierComponent;
991    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
992
993    private int mIntentFilterVerificationToken = 0;
994
995    /** The service connection to the ephemeral resolver */
996    final EphemeralResolverConnection mInstantAppResolverConnection;
997    /** Component used to show resolver settings for Instant Apps */
998    final ComponentName mInstantAppResolverSettingsComponent;
999
1000    /** Activity used to install instant applications */
1001    ActivityInfo mInstantAppInstallerActivity;
1002    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
1003
1004    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
1005            = new SparseArray<IntentFilterVerificationState>();
1006
1007    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
1008
1009    // List of packages names to keep cached, even if they are uninstalled for all users
1010    private List<String> mKeepUninstalledPackages;
1011
1012    private UserManagerInternal mUserManagerInternal;
1013
1014    private DeviceIdleController.LocalService mDeviceIdleController;
1015
1016    private File mCacheDir;
1017
1018    private ArraySet<String> mPrivappPermissionsViolations;
1019
1020    private Future<?> mPrepareAppDataFuture;
1021
1022    private static class IFVerificationParams {
1023        PackageParser.Package pkg;
1024        boolean replacing;
1025        int userId;
1026        int verifierUid;
1027
1028        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1029                int _userId, int _verifierUid) {
1030            pkg = _pkg;
1031            replacing = _replacing;
1032            userId = _userId;
1033            replacing = _replacing;
1034            verifierUid = _verifierUid;
1035        }
1036    }
1037
1038    private interface IntentFilterVerifier<T extends IntentFilter> {
1039        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1040                                               T filter, String packageName);
1041        void startVerifications(int userId);
1042        void receiveVerificationResponse(int verificationId);
1043    }
1044
1045    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1046        private Context mContext;
1047        private ComponentName mIntentFilterVerifierComponent;
1048        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1049
1050        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1051            mContext = context;
1052            mIntentFilterVerifierComponent = verifierComponent;
1053        }
1054
1055        private String getDefaultScheme() {
1056            return IntentFilter.SCHEME_HTTPS;
1057        }
1058
1059        @Override
1060        public void startVerifications(int userId) {
1061            // Launch verifications requests
1062            int count = mCurrentIntentFilterVerifications.size();
1063            for (int n=0; n<count; n++) {
1064                int verificationId = mCurrentIntentFilterVerifications.get(n);
1065                final IntentFilterVerificationState ivs =
1066                        mIntentFilterVerificationStates.get(verificationId);
1067
1068                String packageName = ivs.getPackageName();
1069
1070                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1071                final int filterCount = filters.size();
1072                ArraySet<String> domainsSet = new ArraySet<>();
1073                for (int m=0; m<filterCount; m++) {
1074                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1075                    domainsSet.addAll(filter.getHostsList());
1076                }
1077                synchronized (mPackages) {
1078                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1079                            packageName, domainsSet) != null) {
1080                        scheduleWriteSettingsLocked();
1081                    }
1082                }
1083                sendVerificationRequest(verificationId, ivs);
1084            }
1085            mCurrentIntentFilterVerifications.clear();
1086        }
1087
1088        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1089            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1090            verificationIntent.putExtra(
1091                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1092                    verificationId);
1093            verificationIntent.putExtra(
1094                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1095                    getDefaultScheme());
1096            verificationIntent.putExtra(
1097                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1098                    ivs.getHostsString());
1099            verificationIntent.putExtra(
1100                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1101                    ivs.getPackageName());
1102            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1103            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1104
1105            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1106            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1107                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1108                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1109
1110            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1111            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1112                    "Sending IntentFilter verification broadcast");
1113        }
1114
1115        public void receiveVerificationResponse(int verificationId) {
1116            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1117
1118            final boolean verified = ivs.isVerified();
1119
1120            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1121            final int count = filters.size();
1122            if (DEBUG_DOMAIN_VERIFICATION) {
1123                Slog.i(TAG, "Received verification response " + verificationId
1124                        + " for " + count + " filters, verified=" + verified);
1125            }
1126            for (int n=0; n<count; n++) {
1127                PackageParser.ActivityIntentInfo filter = filters.get(n);
1128                filter.setVerified(verified);
1129
1130                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1131                        + " verified with result:" + verified + " and hosts:"
1132                        + ivs.getHostsString());
1133            }
1134
1135            mIntentFilterVerificationStates.remove(verificationId);
1136
1137            final String packageName = ivs.getPackageName();
1138            IntentFilterVerificationInfo ivi = null;
1139
1140            synchronized (mPackages) {
1141                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1142            }
1143            if (ivi == null) {
1144                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1145                        + verificationId + " packageName:" + packageName);
1146                return;
1147            }
1148            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1149                    "Updating IntentFilterVerificationInfo for package " + packageName
1150                            +" verificationId:" + verificationId);
1151
1152            synchronized (mPackages) {
1153                if (verified) {
1154                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1155                } else {
1156                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1157                }
1158                scheduleWriteSettingsLocked();
1159
1160                final int userId = ivs.getUserId();
1161                if (userId != UserHandle.USER_ALL) {
1162                    final int userStatus =
1163                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1164
1165                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1166                    boolean needUpdate = false;
1167
1168                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1169                    // already been set by the User thru the Disambiguation dialog
1170                    switch (userStatus) {
1171                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1172                            if (verified) {
1173                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1174                            } else {
1175                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1176                            }
1177                            needUpdate = true;
1178                            break;
1179
1180                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1181                            if (verified) {
1182                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1183                                needUpdate = true;
1184                            }
1185                            break;
1186
1187                        default:
1188                            // Nothing to do
1189                    }
1190
1191                    if (needUpdate) {
1192                        mSettings.updateIntentFilterVerificationStatusLPw(
1193                                packageName, updatedStatus, userId);
1194                        scheduleWritePackageRestrictionsLocked(userId);
1195                    }
1196                }
1197            }
1198        }
1199
1200        @Override
1201        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1202                    ActivityIntentInfo filter, String packageName) {
1203            if (!hasValidDomains(filter)) {
1204                return false;
1205            }
1206            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1207            if (ivs == null) {
1208                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1209                        packageName);
1210            }
1211            if (DEBUG_DOMAIN_VERIFICATION) {
1212                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1213            }
1214            ivs.addFilter(filter);
1215            return true;
1216        }
1217
1218        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1219                int userId, int verificationId, String packageName) {
1220            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1221                    verifierUid, userId, packageName);
1222            ivs.setPendingState();
1223            synchronized (mPackages) {
1224                mIntentFilterVerificationStates.append(verificationId, ivs);
1225                mCurrentIntentFilterVerifications.add(verificationId);
1226            }
1227            return ivs;
1228        }
1229    }
1230
1231    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1232        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1233                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1234                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1235    }
1236
1237    // Set of pending broadcasts for aggregating enable/disable of components.
1238    static class PendingPackageBroadcasts {
1239        // for each user id, a map of <package name -> components within that package>
1240        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1241
1242        public PendingPackageBroadcasts() {
1243            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1244        }
1245
1246        public ArrayList<String> get(int userId, String packageName) {
1247            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1248            return packages.get(packageName);
1249        }
1250
1251        public void put(int userId, String packageName, ArrayList<String> components) {
1252            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1253            packages.put(packageName, components);
1254        }
1255
1256        public void remove(int userId, String packageName) {
1257            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1258            if (packages != null) {
1259                packages.remove(packageName);
1260            }
1261        }
1262
1263        public void remove(int userId) {
1264            mUidMap.remove(userId);
1265        }
1266
1267        public int userIdCount() {
1268            return mUidMap.size();
1269        }
1270
1271        public int userIdAt(int n) {
1272            return mUidMap.keyAt(n);
1273        }
1274
1275        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1276            return mUidMap.get(userId);
1277        }
1278
1279        public int size() {
1280            // total number of pending broadcast entries across all userIds
1281            int num = 0;
1282            for (int i = 0; i< mUidMap.size(); i++) {
1283                num += mUidMap.valueAt(i).size();
1284            }
1285            return num;
1286        }
1287
1288        public void clear() {
1289            mUidMap.clear();
1290        }
1291
1292        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1293            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1294            if (map == null) {
1295                map = new ArrayMap<String, ArrayList<String>>();
1296                mUidMap.put(userId, map);
1297            }
1298            return map;
1299        }
1300    }
1301    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1302
1303    // Service Connection to remote media container service to copy
1304    // package uri's from external media onto secure containers
1305    // or internal storage.
1306    private IMediaContainerService mContainerService = null;
1307
1308    static final int SEND_PENDING_BROADCAST = 1;
1309    static final int MCS_BOUND = 3;
1310    static final int END_COPY = 4;
1311    static final int INIT_COPY = 5;
1312    static final int MCS_UNBIND = 6;
1313    static final int START_CLEANING_PACKAGE = 7;
1314    static final int FIND_INSTALL_LOC = 8;
1315    static final int POST_INSTALL = 9;
1316    static final int MCS_RECONNECT = 10;
1317    static final int MCS_GIVE_UP = 11;
1318    static final int UPDATED_MEDIA_STATUS = 12;
1319    static final int WRITE_SETTINGS = 13;
1320    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1321    static final int PACKAGE_VERIFIED = 15;
1322    static final int CHECK_PENDING_VERIFICATION = 16;
1323    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1324    static final int INTENT_FILTER_VERIFIED = 18;
1325    static final int WRITE_PACKAGE_LIST = 19;
1326    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1327
1328    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1329
1330    // Delay time in millisecs
1331    static final int BROADCAST_DELAY = 10 * 1000;
1332
1333    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1334            2 * 60 * 60 * 1000L; /* two hours */
1335
1336    static UserManagerService sUserManager;
1337
1338    // Stores a list of users whose package restrictions file needs to be updated
1339    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1340
1341    final private DefaultContainerConnection mDefContainerConn =
1342            new DefaultContainerConnection();
1343    class DefaultContainerConnection implements ServiceConnection {
1344        public void onServiceConnected(ComponentName name, IBinder service) {
1345            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1346            final IMediaContainerService imcs = IMediaContainerService.Stub
1347                    .asInterface(Binder.allowBlocking(service));
1348            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1349        }
1350
1351        public void onServiceDisconnected(ComponentName name) {
1352            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1353        }
1354    }
1355
1356    // Recordkeeping of restore-after-install operations that are currently in flight
1357    // between the Package Manager and the Backup Manager
1358    static class PostInstallData {
1359        public InstallArgs args;
1360        public PackageInstalledInfo res;
1361
1362        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1363            args = _a;
1364            res = _r;
1365        }
1366    }
1367
1368    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1369    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1370
1371    // XML tags for backup/restore of various bits of state
1372    private static final String TAG_PREFERRED_BACKUP = "pa";
1373    private static final String TAG_DEFAULT_APPS = "da";
1374    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1375
1376    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1377    private static final String TAG_ALL_GRANTS = "rt-grants";
1378    private static final String TAG_GRANT = "grant";
1379    private static final String ATTR_PACKAGE_NAME = "pkg";
1380
1381    private static final String TAG_PERMISSION = "perm";
1382    private static final String ATTR_PERMISSION_NAME = "name";
1383    private static final String ATTR_IS_GRANTED = "g";
1384    private static final String ATTR_USER_SET = "set";
1385    private static final String ATTR_USER_FIXED = "fixed";
1386    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1387
1388    // System/policy permission grants are not backed up
1389    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1390            FLAG_PERMISSION_POLICY_FIXED
1391            | FLAG_PERMISSION_SYSTEM_FIXED
1392            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1393
1394    // And we back up these user-adjusted states
1395    private static final int USER_RUNTIME_GRANT_MASK =
1396            FLAG_PERMISSION_USER_SET
1397            | FLAG_PERMISSION_USER_FIXED
1398            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1399
1400    final @Nullable String mRequiredVerifierPackage;
1401    final @NonNull String mRequiredInstallerPackage;
1402    final @NonNull String mRequiredUninstallerPackage;
1403    final @Nullable String mSetupWizardPackage;
1404    final @Nullable String mStorageManagerPackage;
1405    final @NonNull String mServicesSystemSharedLibraryPackageName;
1406    final @NonNull String mSharedSystemSharedLibraryPackageName;
1407
1408    final boolean mPermissionReviewRequired;
1409
1410    private final PackageUsage mPackageUsage = new PackageUsage();
1411    private final CompilerStats mCompilerStats = new CompilerStats();
1412
1413    class PackageHandler extends Handler {
1414        private boolean mBound = false;
1415        final ArrayList<HandlerParams> mPendingInstalls =
1416            new ArrayList<HandlerParams>();
1417
1418        private boolean connectToService() {
1419            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1420                    " DefaultContainerService");
1421            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1422            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1423            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1424                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1425                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1426                mBound = true;
1427                return true;
1428            }
1429            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1430            return false;
1431        }
1432
1433        private void disconnectService() {
1434            mContainerService = null;
1435            mBound = false;
1436            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1437            mContext.unbindService(mDefContainerConn);
1438            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1439        }
1440
1441        PackageHandler(Looper looper) {
1442            super(looper);
1443        }
1444
1445        public void handleMessage(Message msg) {
1446            try {
1447                doHandleMessage(msg);
1448            } finally {
1449                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1450            }
1451        }
1452
1453        void doHandleMessage(Message msg) {
1454            switch (msg.what) {
1455                case INIT_COPY: {
1456                    HandlerParams params = (HandlerParams) msg.obj;
1457                    int idx = mPendingInstalls.size();
1458                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1459                    // If a bind was already initiated we dont really
1460                    // need to do anything. The pending install
1461                    // will be processed later on.
1462                    if (!mBound) {
1463                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1464                                System.identityHashCode(mHandler));
1465                        // If this is the only one pending we might
1466                        // have to bind to the service again.
1467                        if (!connectToService()) {
1468                            Slog.e(TAG, "Failed to bind to media container service");
1469                            params.serviceError();
1470                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1471                                    System.identityHashCode(mHandler));
1472                            if (params.traceMethod != null) {
1473                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1474                                        params.traceCookie);
1475                            }
1476                            return;
1477                        } else {
1478                            // Once we bind to the service, the first
1479                            // pending request will be processed.
1480                            mPendingInstalls.add(idx, params);
1481                        }
1482                    } else {
1483                        mPendingInstalls.add(idx, params);
1484                        // Already bound to the service. Just make
1485                        // sure we trigger off processing the first request.
1486                        if (idx == 0) {
1487                            mHandler.sendEmptyMessage(MCS_BOUND);
1488                        }
1489                    }
1490                    break;
1491                }
1492                case MCS_BOUND: {
1493                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1494                    if (msg.obj != null) {
1495                        mContainerService = (IMediaContainerService) msg.obj;
1496                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1497                                System.identityHashCode(mHandler));
1498                    }
1499                    if (mContainerService == null) {
1500                        if (!mBound) {
1501                            // Something seriously wrong since we are not bound and we are not
1502                            // waiting for connection. Bail out.
1503                            Slog.e(TAG, "Cannot bind to media container service");
1504                            for (HandlerParams params : mPendingInstalls) {
1505                                // Indicate service bind error
1506                                params.serviceError();
1507                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1508                                        System.identityHashCode(params));
1509                                if (params.traceMethod != null) {
1510                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1511                                            params.traceMethod, params.traceCookie);
1512                                }
1513                                return;
1514                            }
1515                            mPendingInstalls.clear();
1516                        } else {
1517                            Slog.w(TAG, "Waiting to connect to media container service");
1518                        }
1519                    } else if (mPendingInstalls.size() > 0) {
1520                        HandlerParams params = mPendingInstalls.get(0);
1521                        if (params != null) {
1522                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1523                                    System.identityHashCode(params));
1524                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1525                            if (params.startCopy()) {
1526                                // We are done...  look for more work or to
1527                                // go idle.
1528                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1529                                        "Checking for more work or unbind...");
1530                                // Delete pending install
1531                                if (mPendingInstalls.size() > 0) {
1532                                    mPendingInstalls.remove(0);
1533                                }
1534                                if (mPendingInstalls.size() == 0) {
1535                                    if (mBound) {
1536                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1537                                                "Posting delayed MCS_UNBIND");
1538                                        removeMessages(MCS_UNBIND);
1539                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1540                                        // Unbind after a little delay, to avoid
1541                                        // continual thrashing.
1542                                        sendMessageDelayed(ubmsg, 10000);
1543                                    }
1544                                } else {
1545                                    // There are more pending requests in queue.
1546                                    // Just post MCS_BOUND message to trigger processing
1547                                    // of next pending install.
1548                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1549                                            "Posting MCS_BOUND for next work");
1550                                    mHandler.sendEmptyMessage(MCS_BOUND);
1551                                }
1552                            }
1553                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1554                        }
1555                    } else {
1556                        // Should never happen ideally.
1557                        Slog.w(TAG, "Empty queue");
1558                    }
1559                    break;
1560                }
1561                case MCS_RECONNECT: {
1562                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1563                    if (mPendingInstalls.size() > 0) {
1564                        if (mBound) {
1565                            disconnectService();
1566                        }
1567                        if (!connectToService()) {
1568                            Slog.e(TAG, "Failed to bind to media container service");
1569                            for (HandlerParams params : mPendingInstalls) {
1570                                // Indicate service bind error
1571                                params.serviceError();
1572                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1573                                        System.identityHashCode(params));
1574                            }
1575                            mPendingInstalls.clear();
1576                        }
1577                    }
1578                    break;
1579                }
1580                case MCS_UNBIND: {
1581                    // If there is no actual work left, then time to unbind.
1582                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1583
1584                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1585                        if (mBound) {
1586                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1587
1588                            disconnectService();
1589                        }
1590                    } else if (mPendingInstalls.size() > 0) {
1591                        // There are more pending requests in queue.
1592                        // Just post MCS_BOUND message to trigger processing
1593                        // of next pending install.
1594                        mHandler.sendEmptyMessage(MCS_BOUND);
1595                    }
1596
1597                    break;
1598                }
1599                case MCS_GIVE_UP: {
1600                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1601                    HandlerParams params = mPendingInstalls.remove(0);
1602                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1603                            System.identityHashCode(params));
1604                    break;
1605                }
1606                case SEND_PENDING_BROADCAST: {
1607                    String packages[];
1608                    ArrayList<String> components[];
1609                    int size = 0;
1610                    int uids[];
1611                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1612                    synchronized (mPackages) {
1613                        if (mPendingBroadcasts == null) {
1614                            return;
1615                        }
1616                        size = mPendingBroadcasts.size();
1617                        if (size <= 0) {
1618                            // Nothing to be done. Just return
1619                            return;
1620                        }
1621                        packages = new String[size];
1622                        components = new ArrayList[size];
1623                        uids = new int[size];
1624                        int i = 0;  // filling out the above arrays
1625
1626                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1627                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1628                            Iterator<Map.Entry<String, ArrayList<String>>> it
1629                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1630                                            .entrySet().iterator();
1631                            while (it.hasNext() && i < size) {
1632                                Map.Entry<String, ArrayList<String>> ent = it.next();
1633                                packages[i] = ent.getKey();
1634                                components[i] = ent.getValue();
1635                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1636                                uids[i] = (ps != null)
1637                                        ? UserHandle.getUid(packageUserId, ps.appId)
1638                                        : -1;
1639                                i++;
1640                            }
1641                        }
1642                        size = i;
1643                        mPendingBroadcasts.clear();
1644                    }
1645                    // Send broadcasts
1646                    for (int i = 0; i < size; i++) {
1647                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1648                    }
1649                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1650                    break;
1651                }
1652                case START_CLEANING_PACKAGE: {
1653                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1654                    final String packageName = (String)msg.obj;
1655                    final int userId = msg.arg1;
1656                    final boolean andCode = msg.arg2 != 0;
1657                    synchronized (mPackages) {
1658                        if (userId == UserHandle.USER_ALL) {
1659                            int[] users = sUserManager.getUserIds();
1660                            for (int user : users) {
1661                                mSettings.addPackageToCleanLPw(
1662                                        new PackageCleanItem(user, packageName, andCode));
1663                            }
1664                        } else {
1665                            mSettings.addPackageToCleanLPw(
1666                                    new PackageCleanItem(userId, packageName, andCode));
1667                        }
1668                    }
1669                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1670                    startCleaningPackages();
1671                } break;
1672                case POST_INSTALL: {
1673                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1674
1675                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1676                    final boolean didRestore = (msg.arg2 != 0);
1677                    mRunningInstalls.delete(msg.arg1);
1678
1679                    if (data != null) {
1680                        InstallArgs args = data.args;
1681                        PackageInstalledInfo parentRes = data.res;
1682
1683                        final boolean grantPermissions = (args.installFlags
1684                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1685                        final boolean killApp = (args.installFlags
1686                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1687                        final boolean virtualPreload = ((args.installFlags
1688                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1689                        final String[] grantedPermissions = args.installGrantPermissions;
1690
1691                        // Handle the parent package
1692                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1693                                virtualPreload, grantedPermissions, didRestore,
1694                                args.installerPackageName, args.observer);
1695
1696                        // Handle the child packages
1697                        final int childCount = (parentRes.addedChildPackages != null)
1698                                ? parentRes.addedChildPackages.size() : 0;
1699                        for (int i = 0; i < childCount; i++) {
1700                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1701                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1702                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1703                                    args.installerPackageName, args.observer);
1704                        }
1705
1706                        // Log tracing if needed
1707                        if (args.traceMethod != null) {
1708                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1709                                    args.traceCookie);
1710                        }
1711                    } else {
1712                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1713                    }
1714
1715                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1716                } break;
1717                case UPDATED_MEDIA_STATUS: {
1718                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1719                    boolean reportStatus = msg.arg1 == 1;
1720                    boolean doGc = msg.arg2 == 1;
1721                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1722                    if (doGc) {
1723                        // Force a gc to clear up stale containers.
1724                        Runtime.getRuntime().gc();
1725                    }
1726                    if (msg.obj != null) {
1727                        @SuppressWarnings("unchecked")
1728                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1729                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1730                        // Unload containers
1731                        unloadAllContainers(args);
1732                    }
1733                    if (reportStatus) {
1734                        try {
1735                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1736                                    "Invoking StorageManagerService call back");
1737                            PackageHelper.getStorageManager().finishMediaUpdate();
1738                        } catch (RemoteException e) {
1739                            Log.e(TAG, "StorageManagerService not running?");
1740                        }
1741                    }
1742                } break;
1743                case WRITE_SETTINGS: {
1744                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1745                    synchronized (mPackages) {
1746                        removeMessages(WRITE_SETTINGS);
1747                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1748                        mSettings.writeLPr();
1749                        mDirtyUsers.clear();
1750                    }
1751                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1752                } break;
1753                case WRITE_PACKAGE_RESTRICTIONS: {
1754                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1755                    synchronized (mPackages) {
1756                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1757                        for (int userId : mDirtyUsers) {
1758                            mSettings.writePackageRestrictionsLPr(userId);
1759                        }
1760                        mDirtyUsers.clear();
1761                    }
1762                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1763                } break;
1764                case WRITE_PACKAGE_LIST: {
1765                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1766                    synchronized (mPackages) {
1767                        removeMessages(WRITE_PACKAGE_LIST);
1768                        mSettings.writePackageListLPr(msg.arg1);
1769                    }
1770                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1771                } break;
1772                case CHECK_PENDING_VERIFICATION: {
1773                    final int verificationId = msg.arg1;
1774                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1775
1776                    if ((state != null) && !state.timeoutExtended()) {
1777                        final InstallArgs args = state.getInstallArgs();
1778                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1779
1780                        Slog.i(TAG, "Verification timed out for " + originUri);
1781                        mPendingVerification.remove(verificationId);
1782
1783                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1784
1785                        final UserHandle user = args.getUser();
1786                        if (getDefaultVerificationResponse(user)
1787                                == PackageManager.VERIFICATION_ALLOW) {
1788                            Slog.i(TAG, "Continuing with installation of " + originUri);
1789                            state.setVerifierResponse(Binder.getCallingUid(),
1790                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1791                            broadcastPackageVerified(verificationId, originUri,
1792                                    PackageManager.VERIFICATION_ALLOW, user);
1793                            try {
1794                                ret = args.copyApk(mContainerService, true);
1795                            } catch (RemoteException e) {
1796                                Slog.e(TAG, "Could not contact the ContainerService");
1797                            }
1798                        } else {
1799                            broadcastPackageVerified(verificationId, originUri,
1800                                    PackageManager.VERIFICATION_REJECT, user);
1801                        }
1802
1803                        Trace.asyncTraceEnd(
1804                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1805
1806                        processPendingInstall(args, ret);
1807                        mHandler.sendEmptyMessage(MCS_UNBIND);
1808                    }
1809                    break;
1810                }
1811                case PACKAGE_VERIFIED: {
1812                    final int verificationId = msg.arg1;
1813
1814                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1815                    if (state == null) {
1816                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1817                        break;
1818                    }
1819
1820                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1821
1822                    state.setVerifierResponse(response.callerUid, response.code);
1823
1824                    if (state.isVerificationComplete()) {
1825                        mPendingVerification.remove(verificationId);
1826
1827                        final InstallArgs args = state.getInstallArgs();
1828                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1829
1830                        int ret;
1831                        if (state.isInstallAllowed()) {
1832                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1833                            broadcastPackageVerified(verificationId, originUri,
1834                                    response.code, state.getInstallArgs().getUser());
1835                            try {
1836                                ret = args.copyApk(mContainerService, true);
1837                            } catch (RemoteException e) {
1838                                Slog.e(TAG, "Could not contact the ContainerService");
1839                            }
1840                        } else {
1841                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1842                        }
1843
1844                        Trace.asyncTraceEnd(
1845                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1846
1847                        processPendingInstall(args, ret);
1848                        mHandler.sendEmptyMessage(MCS_UNBIND);
1849                    }
1850
1851                    break;
1852                }
1853                case START_INTENT_FILTER_VERIFICATIONS: {
1854                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1855                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1856                            params.replacing, params.pkg);
1857                    break;
1858                }
1859                case INTENT_FILTER_VERIFIED: {
1860                    final int verificationId = msg.arg1;
1861
1862                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1863                            verificationId);
1864                    if (state == null) {
1865                        Slog.w(TAG, "Invalid IntentFilter verification token "
1866                                + verificationId + " received");
1867                        break;
1868                    }
1869
1870                    final int userId = state.getUserId();
1871
1872                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1873                            "Processing IntentFilter verification with token:"
1874                            + verificationId + " and userId:" + userId);
1875
1876                    final IntentFilterVerificationResponse response =
1877                            (IntentFilterVerificationResponse) msg.obj;
1878
1879                    state.setVerifierResponse(response.callerUid, response.code);
1880
1881                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1882                            "IntentFilter verification with token:" + verificationId
1883                            + " and userId:" + userId
1884                            + " is settings verifier response with response code:"
1885                            + response.code);
1886
1887                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1888                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1889                                + response.getFailedDomainsString());
1890                    }
1891
1892                    if (state.isVerificationComplete()) {
1893                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1894                    } else {
1895                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1896                                "IntentFilter verification with token:" + verificationId
1897                                + " was not said to be complete");
1898                    }
1899
1900                    break;
1901                }
1902                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1903                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1904                            mInstantAppResolverConnection,
1905                            (InstantAppRequest) msg.obj,
1906                            mInstantAppInstallerActivity,
1907                            mHandler);
1908                }
1909            }
1910        }
1911    }
1912
1913    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1914            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1915            boolean launchedForRestore, String installerPackage,
1916            IPackageInstallObserver2 installObserver) {
1917        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1918            // Send the removed broadcasts
1919            if (res.removedInfo != null) {
1920                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1921            }
1922
1923            // Now that we successfully installed the package, grant runtime
1924            // permissions if requested before broadcasting the install. Also
1925            // for legacy apps in permission review mode we clear the permission
1926            // review flag which is used to emulate runtime permissions for
1927            // legacy apps.
1928            if (grantPermissions) {
1929                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1930            }
1931
1932            final boolean update = res.removedInfo != null
1933                    && res.removedInfo.removedPackage != null;
1934            final String installerPackageName =
1935                    res.installerPackageName != null
1936                            ? res.installerPackageName
1937                            : res.removedInfo != null
1938                                    ? res.removedInfo.installerPackageName
1939                                    : null;
1940
1941            // If this is the first time we have child packages for a disabled privileged
1942            // app that had no children, we grant requested runtime permissions to the new
1943            // children if the parent on the system image had them already granted.
1944            if (res.pkg.parentPackage != null) {
1945                synchronized (mPackages) {
1946                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1947                }
1948            }
1949
1950            synchronized (mPackages) {
1951                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1952            }
1953
1954            final String packageName = res.pkg.applicationInfo.packageName;
1955
1956            // Determine the set of users who are adding this package for
1957            // the first time vs. those who are seeing an update.
1958            int[] firstUsers = EMPTY_INT_ARRAY;
1959            int[] updateUsers = EMPTY_INT_ARRAY;
1960            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1961            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1962            for (int newUser : res.newUsers) {
1963                if (ps.getInstantApp(newUser)) {
1964                    continue;
1965                }
1966                if (allNewUsers) {
1967                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1968                    continue;
1969                }
1970                boolean isNew = true;
1971                for (int origUser : res.origUsers) {
1972                    if (origUser == newUser) {
1973                        isNew = false;
1974                        break;
1975                    }
1976                }
1977                if (isNew) {
1978                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1979                } else {
1980                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1981                }
1982            }
1983
1984            // Send installed broadcasts if the package is not a static shared lib.
1985            if (res.pkg.staticSharedLibName == null) {
1986                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1987
1988                // Send added for users that see the package for the first time
1989                // sendPackageAddedForNewUsers also deals with system apps
1990                int appId = UserHandle.getAppId(res.uid);
1991                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1992                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
1993                        virtualPreload /*startReceiver*/, appId, firstUsers);
1994
1995                // Send added for users that don't see the package for the first time
1996                Bundle extras = new Bundle(1);
1997                extras.putInt(Intent.EXTRA_UID, res.uid);
1998                if (update) {
1999                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
2000                }
2001                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2002                        extras, 0 /*flags*/,
2003                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
2004                if (installerPackageName != null) {
2005                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2006                            extras, 0 /*flags*/,
2007                            installerPackageName, null /*finishedReceiver*/, updateUsers);
2008                }
2009
2010                // Send replaced for users that don't see the package for the first time
2011                if (update) {
2012                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2013                            packageName, extras, 0 /*flags*/,
2014                            null /*targetPackage*/, null /*finishedReceiver*/,
2015                            updateUsers);
2016                    if (installerPackageName != null) {
2017                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2018                                extras, 0 /*flags*/,
2019                                installerPackageName, null /*finishedReceiver*/, updateUsers);
2020                    }
2021                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2022                            null /*package*/, null /*extras*/, 0 /*flags*/,
2023                            packageName /*targetPackage*/,
2024                            null /*finishedReceiver*/, updateUsers);
2025                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2026                    // First-install and we did a restore, so we're responsible for the
2027                    // first-launch broadcast.
2028                    if (DEBUG_BACKUP) {
2029                        Slog.i(TAG, "Post-restore of " + packageName
2030                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2031                    }
2032                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2033                }
2034
2035                // Send broadcast package appeared if forward locked/external for all users
2036                // treat asec-hosted packages like removable media on upgrade
2037                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2038                    if (DEBUG_INSTALL) {
2039                        Slog.i(TAG, "upgrading pkg " + res.pkg
2040                                + " is ASEC-hosted -> AVAILABLE");
2041                    }
2042                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2043                    ArrayList<String> pkgList = new ArrayList<>(1);
2044                    pkgList.add(packageName);
2045                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2046                }
2047            }
2048
2049            // Work that needs to happen on first install within each user
2050            if (firstUsers != null && firstUsers.length > 0) {
2051                synchronized (mPackages) {
2052                    for (int userId : firstUsers) {
2053                        // If this app is a browser and it's newly-installed for some
2054                        // users, clear any default-browser state in those users. The
2055                        // app's nature doesn't depend on the user, so we can just check
2056                        // its browser nature in any user and generalize.
2057                        if (packageIsBrowser(packageName, userId)) {
2058                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2059                        }
2060
2061                        // We may also need to apply pending (restored) runtime
2062                        // permission grants within these users.
2063                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2064                    }
2065                }
2066            }
2067
2068            // Log current value of "unknown sources" setting
2069            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2070                    getUnknownSourcesSettings());
2071
2072            // Remove the replaced package's older resources safely now
2073            // We delete after a gc for applications  on sdcard.
2074            if (res.removedInfo != null && res.removedInfo.args != null) {
2075                Runtime.getRuntime().gc();
2076                synchronized (mInstallLock) {
2077                    res.removedInfo.args.doPostDeleteLI(true);
2078                }
2079            } else {
2080                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2081                // and not block here.
2082                VMRuntime.getRuntime().requestConcurrentGC();
2083            }
2084
2085            // Notify DexManager that the package was installed for new users.
2086            // The updated users should already be indexed and the package code paths
2087            // should not change.
2088            // Don't notify the manager for ephemeral apps as they are not expected to
2089            // survive long enough to benefit of background optimizations.
2090            for (int userId : firstUsers) {
2091                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2092                // There's a race currently where some install events may interleave with an uninstall.
2093                // This can lead to package info being null (b/36642664).
2094                if (info != null) {
2095                    mDexManager.notifyPackageInstalled(info, userId);
2096                }
2097            }
2098        }
2099
2100        // If someone is watching installs - notify them
2101        if (installObserver != null) {
2102            try {
2103                Bundle extras = extrasForInstallResult(res);
2104                installObserver.onPackageInstalled(res.name, res.returnCode,
2105                        res.returnMsg, extras);
2106            } catch (RemoteException e) {
2107                Slog.i(TAG, "Observer no longer exists.");
2108            }
2109        }
2110    }
2111
2112    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2113            PackageParser.Package pkg) {
2114        if (pkg.parentPackage == null) {
2115            return;
2116        }
2117        if (pkg.requestedPermissions == null) {
2118            return;
2119        }
2120        final PackageSetting disabledSysParentPs = mSettings
2121                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2122        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2123                || !disabledSysParentPs.isPrivileged()
2124                || (disabledSysParentPs.childPackageNames != null
2125                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2126            return;
2127        }
2128        final int[] allUserIds = sUserManager.getUserIds();
2129        final int permCount = pkg.requestedPermissions.size();
2130        for (int i = 0; i < permCount; i++) {
2131            String permission = pkg.requestedPermissions.get(i);
2132            BasePermission bp = mSettings.mPermissions.get(permission);
2133            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2134                continue;
2135            }
2136            for (int userId : allUserIds) {
2137                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2138                        permission, userId)) {
2139                    grantRuntimePermission(pkg.packageName, permission, userId);
2140                }
2141            }
2142        }
2143    }
2144
2145    private StorageEventListener mStorageListener = new StorageEventListener() {
2146        @Override
2147        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2148            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2149                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2150                    final String volumeUuid = vol.getFsUuid();
2151
2152                    // Clean up any users or apps that were removed or recreated
2153                    // while this volume was missing
2154                    sUserManager.reconcileUsers(volumeUuid);
2155                    reconcileApps(volumeUuid);
2156
2157                    // Clean up any install sessions that expired or were
2158                    // cancelled while this volume was missing
2159                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2160
2161                    loadPrivatePackages(vol);
2162
2163                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2164                    unloadPrivatePackages(vol);
2165                }
2166            }
2167
2168            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2169                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2170                    updateExternalMediaStatus(true, false);
2171                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2172                    updateExternalMediaStatus(false, false);
2173                }
2174            }
2175        }
2176
2177        @Override
2178        public void onVolumeForgotten(String fsUuid) {
2179            if (TextUtils.isEmpty(fsUuid)) {
2180                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2181                return;
2182            }
2183
2184            // Remove any apps installed on the forgotten volume
2185            synchronized (mPackages) {
2186                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2187                for (PackageSetting ps : packages) {
2188                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2189                    deletePackageVersioned(new VersionedPackage(ps.name,
2190                            PackageManager.VERSION_CODE_HIGHEST),
2191                            new LegacyPackageDeleteObserver(null).getBinder(),
2192                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2193                    // Try very hard to release any references to this package
2194                    // so we don't risk the system server being killed due to
2195                    // open FDs
2196                    AttributeCache.instance().removePackage(ps.name);
2197                }
2198
2199                mSettings.onVolumeForgotten(fsUuid);
2200                mSettings.writeLPr();
2201            }
2202        }
2203    };
2204
2205    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2206            String[] grantedPermissions) {
2207        for (int userId : userIds) {
2208            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2209        }
2210    }
2211
2212    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2213            String[] grantedPermissions) {
2214        PackageSetting ps = (PackageSetting) pkg.mExtras;
2215        if (ps == null) {
2216            return;
2217        }
2218
2219        PermissionsState permissionsState = ps.getPermissionsState();
2220
2221        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2222                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2223
2224        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2225                >= Build.VERSION_CODES.M;
2226
2227        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2228
2229        for (String permission : pkg.requestedPermissions) {
2230            final BasePermission bp;
2231            synchronized (mPackages) {
2232                bp = mSettings.mPermissions.get(permission);
2233            }
2234            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2235                    && (!instantApp || bp.isInstant())
2236                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2237                    && (grantedPermissions == null
2238                           || ArrayUtils.contains(grantedPermissions, permission))) {
2239                final int flags = permissionsState.getPermissionFlags(permission, userId);
2240                if (supportsRuntimePermissions) {
2241                    // Installer cannot change immutable permissions.
2242                    if ((flags & immutableFlags) == 0) {
2243                        grantRuntimePermission(pkg.packageName, permission, userId);
2244                    }
2245                } else if (mPermissionReviewRequired) {
2246                    // In permission review mode we clear the review flag when we
2247                    // are asked to install the app with all permissions granted.
2248                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2249                        updatePermissionFlags(permission, pkg.packageName,
2250                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2251                    }
2252                }
2253            }
2254        }
2255    }
2256
2257    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2258        Bundle extras = null;
2259        switch (res.returnCode) {
2260            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2261                extras = new Bundle();
2262                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2263                        res.origPermission);
2264                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2265                        res.origPackage);
2266                break;
2267            }
2268            case PackageManager.INSTALL_SUCCEEDED: {
2269                extras = new Bundle();
2270                extras.putBoolean(Intent.EXTRA_REPLACING,
2271                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2272                break;
2273            }
2274        }
2275        return extras;
2276    }
2277
2278    void scheduleWriteSettingsLocked() {
2279        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2280            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2281        }
2282    }
2283
2284    void scheduleWritePackageListLocked(int userId) {
2285        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2286            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2287            msg.arg1 = userId;
2288            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2289        }
2290    }
2291
2292    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2293        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2294        scheduleWritePackageRestrictionsLocked(userId);
2295    }
2296
2297    void scheduleWritePackageRestrictionsLocked(int userId) {
2298        final int[] userIds = (userId == UserHandle.USER_ALL)
2299                ? sUserManager.getUserIds() : new int[]{userId};
2300        for (int nextUserId : userIds) {
2301            if (!sUserManager.exists(nextUserId)) return;
2302            mDirtyUsers.add(nextUserId);
2303            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2304                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2305            }
2306        }
2307    }
2308
2309    public static PackageManagerService main(Context context, Installer installer,
2310            boolean factoryTest, boolean onlyCore) {
2311        // Self-check for initial settings.
2312        PackageManagerServiceCompilerMapping.checkProperties();
2313
2314        PackageManagerService m = new PackageManagerService(context, installer,
2315                factoryTest, onlyCore);
2316        m.enableSystemUserPackages();
2317        ServiceManager.addService("package", m);
2318        final PackageManagerNative pmn = m.new PackageManagerNative();
2319        ServiceManager.addService("package_native", pmn);
2320        return m;
2321    }
2322
2323    private void enableSystemUserPackages() {
2324        if (!UserManager.isSplitSystemUser()) {
2325            return;
2326        }
2327        // For system user, enable apps based on the following conditions:
2328        // - app is whitelisted or belong to one of these groups:
2329        //   -- system app which has no launcher icons
2330        //   -- system app which has INTERACT_ACROSS_USERS permission
2331        //   -- system IME app
2332        // - app is not in the blacklist
2333        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2334        Set<String> enableApps = new ArraySet<>();
2335        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2336                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2337                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2338        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2339        enableApps.addAll(wlApps);
2340        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2341                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2342        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2343        enableApps.removeAll(blApps);
2344        Log.i(TAG, "Applications installed for system user: " + enableApps);
2345        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2346                UserHandle.SYSTEM);
2347        final int allAppsSize = allAps.size();
2348        synchronized (mPackages) {
2349            for (int i = 0; i < allAppsSize; i++) {
2350                String pName = allAps.get(i);
2351                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2352                // Should not happen, but we shouldn't be failing if it does
2353                if (pkgSetting == null) {
2354                    continue;
2355                }
2356                boolean install = enableApps.contains(pName);
2357                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2358                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2359                            + " for system user");
2360                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2361                }
2362            }
2363            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2364        }
2365    }
2366
2367    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2368        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2369                Context.DISPLAY_SERVICE);
2370        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2371    }
2372
2373    /**
2374     * Requests that files preopted on a secondary system partition be copied to the data partition
2375     * if possible.  Note that the actual copying of the files is accomplished by init for security
2376     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2377     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2378     */
2379    private static void requestCopyPreoptedFiles() {
2380        final int WAIT_TIME_MS = 100;
2381        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2382        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2383            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2384            // We will wait for up to 100 seconds.
2385            final long timeStart = SystemClock.uptimeMillis();
2386            final long timeEnd = timeStart + 100 * 1000;
2387            long timeNow = timeStart;
2388            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2389                try {
2390                    Thread.sleep(WAIT_TIME_MS);
2391                } catch (InterruptedException e) {
2392                    // Do nothing
2393                }
2394                timeNow = SystemClock.uptimeMillis();
2395                if (timeNow > timeEnd) {
2396                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2397                    Slog.wtf(TAG, "cppreopt did not finish!");
2398                    break;
2399                }
2400            }
2401
2402            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2403        }
2404    }
2405
2406    public PackageManagerService(Context context, Installer installer,
2407            boolean factoryTest, boolean onlyCore) {
2408        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2409        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2410        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2411                SystemClock.uptimeMillis());
2412
2413        if (mSdkVersion <= 0) {
2414            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2415        }
2416
2417        mContext = context;
2418
2419        mPermissionReviewRequired = context.getResources().getBoolean(
2420                R.bool.config_permissionReviewRequired);
2421
2422        mFactoryTest = factoryTest;
2423        mOnlyCore = onlyCore;
2424        mMetrics = new DisplayMetrics();
2425        mSettings = new Settings(mPackages);
2426        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2427                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2428        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2429                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2430        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2431                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2432        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2433                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2434        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2435                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2436        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2437                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2438
2439        String separateProcesses = SystemProperties.get("debug.separate_processes");
2440        if (separateProcesses != null && separateProcesses.length() > 0) {
2441            if ("*".equals(separateProcesses)) {
2442                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2443                mSeparateProcesses = null;
2444                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2445            } else {
2446                mDefParseFlags = 0;
2447                mSeparateProcesses = separateProcesses.split(",");
2448                Slog.w(TAG, "Running with debug.separate_processes: "
2449                        + separateProcesses);
2450            }
2451        } else {
2452            mDefParseFlags = 0;
2453            mSeparateProcesses = null;
2454        }
2455
2456        mInstaller = installer;
2457        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2458                "*dexopt*");
2459        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2460        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2461
2462        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2463                FgThread.get().getLooper());
2464
2465        getDefaultDisplayMetrics(context, mMetrics);
2466
2467        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2468        SystemConfig systemConfig = SystemConfig.getInstance();
2469        mGlobalGids = systemConfig.getGlobalGids();
2470        mSystemPermissions = systemConfig.getSystemPermissions();
2471        mAvailableFeatures = systemConfig.getAvailableFeatures();
2472        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2473
2474        mProtectedPackages = new ProtectedPackages(mContext);
2475
2476        synchronized (mInstallLock) {
2477        // writer
2478        synchronized (mPackages) {
2479            mHandlerThread = new ServiceThread(TAG,
2480                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2481            mHandlerThread.start();
2482            mHandler = new PackageHandler(mHandlerThread.getLooper());
2483            mProcessLoggingHandler = new ProcessLoggingHandler();
2484            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2485
2486            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2487            mInstantAppRegistry = new InstantAppRegistry(this);
2488
2489            File dataDir = Environment.getDataDirectory();
2490            mAppInstallDir = new File(dataDir, "app");
2491            mAppLib32InstallDir = new File(dataDir, "app-lib");
2492            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2493            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2494            sUserManager = new UserManagerService(context, this,
2495                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2496
2497            // Propagate permission configuration in to package manager.
2498            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2499                    = systemConfig.getPermissions();
2500            for (int i=0; i<permConfig.size(); i++) {
2501                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2502                BasePermission bp = mSettings.mPermissions.get(perm.name);
2503                if (bp == null) {
2504                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2505                    mSettings.mPermissions.put(perm.name, bp);
2506                }
2507                if (perm.gids != null) {
2508                    bp.setGids(perm.gids, perm.perUser);
2509                }
2510            }
2511
2512            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2513            final int builtInLibCount = libConfig.size();
2514            for (int i = 0; i < builtInLibCount; i++) {
2515                String name = libConfig.keyAt(i);
2516                String path = libConfig.valueAt(i);
2517                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2518                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2519            }
2520
2521            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2522
2523            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2524            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2525            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2526
2527            // Clean up orphaned packages for which the code path doesn't exist
2528            // and they are an update to a system app - caused by bug/32321269
2529            final int packageSettingCount = mSettings.mPackages.size();
2530            for (int i = packageSettingCount - 1; i >= 0; i--) {
2531                PackageSetting ps = mSettings.mPackages.valueAt(i);
2532                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2533                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2534                    mSettings.mPackages.removeAt(i);
2535                    mSettings.enableSystemPackageLPw(ps.name);
2536                }
2537            }
2538
2539            if (mFirstBoot) {
2540                requestCopyPreoptedFiles();
2541            }
2542
2543            String customResolverActivity = Resources.getSystem().getString(
2544                    R.string.config_customResolverActivity);
2545            if (TextUtils.isEmpty(customResolverActivity)) {
2546                customResolverActivity = null;
2547            } else {
2548                mCustomResolverComponentName = ComponentName.unflattenFromString(
2549                        customResolverActivity);
2550            }
2551
2552            long startTime = SystemClock.uptimeMillis();
2553
2554            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2555                    startTime);
2556
2557            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2558            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2559
2560            if (bootClassPath == null) {
2561                Slog.w(TAG, "No BOOTCLASSPATH found!");
2562            }
2563
2564            if (systemServerClassPath == null) {
2565                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2566            }
2567
2568            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2569
2570            final VersionInfo ver = mSettings.getInternalVersion();
2571            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2572            if (mIsUpgrade) {
2573                logCriticalInfo(Log.INFO,
2574                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2575            }
2576
2577            // when upgrading from pre-M, promote system app permissions from install to runtime
2578            mPromoteSystemApps =
2579                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2580
2581            // When upgrading from pre-N, we need to handle package extraction like first boot,
2582            // as there is no profiling data available.
2583            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2584
2585            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2586
2587            // save off the names of pre-existing system packages prior to scanning; we don't
2588            // want to automatically grant runtime permissions for new system apps
2589            if (mPromoteSystemApps) {
2590                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2591                while (pkgSettingIter.hasNext()) {
2592                    PackageSetting ps = pkgSettingIter.next();
2593                    if (isSystemApp(ps)) {
2594                        mExistingSystemPackages.add(ps.name);
2595                    }
2596                }
2597            }
2598
2599            mCacheDir = preparePackageParserCache(mIsUpgrade);
2600
2601            // Set flag to monitor and not change apk file paths when
2602            // scanning install directories.
2603            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2604
2605            if (mIsUpgrade || mFirstBoot) {
2606                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2607            }
2608
2609            // Collect vendor overlay packages. (Do this before scanning any apps.)
2610            // For security and version matching reason, only consider
2611            // overlay packages if they reside in the right directory.
2612            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2613                    | PackageParser.PARSE_IS_SYSTEM
2614                    | PackageParser.PARSE_IS_SYSTEM_DIR
2615                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2616
2617            mParallelPackageParserCallback.findStaticOverlayPackages();
2618
2619            // Find base frameworks (resource packages without code).
2620            scanDirTracedLI(frameworkDir, mDefParseFlags
2621                    | PackageParser.PARSE_IS_SYSTEM
2622                    | PackageParser.PARSE_IS_SYSTEM_DIR
2623                    | PackageParser.PARSE_IS_PRIVILEGED,
2624                    scanFlags | SCAN_NO_DEX, 0);
2625
2626            // Collected privileged system packages.
2627            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2628            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2629                    | PackageParser.PARSE_IS_SYSTEM
2630                    | PackageParser.PARSE_IS_SYSTEM_DIR
2631                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2632
2633            // Collect ordinary system packages.
2634            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2635            scanDirTracedLI(systemAppDir, mDefParseFlags
2636                    | PackageParser.PARSE_IS_SYSTEM
2637                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2638
2639            // Collect all vendor packages.
2640            File vendorAppDir = new File("/vendor/app");
2641            try {
2642                vendorAppDir = vendorAppDir.getCanonicalFile();
2643            } catch (IOException e) {
2644                // failed to look up canonical path, continue with original one
2645            }
2646            scanDirTracedLI(vendorAppDir, mDefParseFlags
2647                    | PackageParser.PARSE_IS_SYSTEM
2648                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2649
2650            // Collect all OEM packages.
2651            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2652            scanDirTracedLI(oemAppDir, mDefParseFlags
2653                    | PackageParser.PARSE_IS_SYSTEM
2654                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2655
2656            // Prune any system packages that no longer exist.
2657            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2658            // Stub packages must either be replaced with full versions in the /data
2659            // partition or be disabled.
2660            final List<String> stubSystemApps = new ArrayList<>();
2661            if (!mOnlyCore) {
2662                // do this first before mucking with mPackages for the "expecting better" case
2663                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2664                while (pkgIterator.hasNext()) {
2665                    final PackageParser.Package pkg = pkgIterator.next();
2666                    if (pkg.isStub) {
2667                        stubSystemApps.add(pkg.packageName);
2668                    }
2669                }
2670
2671                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2672                while (psit.hasNext()) {
2673                    PackageSetting ps = psit.next();
2674
2675                    /*
2676                     * If this is not a system app, it can't be a
2677                     * disable system app.
2678                     */
2679                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2680                        continue;
2681                    }
2682
2683                    /*
2684                     * If the package is scanned, it's not erased.
2685                     */
2686                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2687                    if (scannedPkg != null) {
2688                        /*
2689                         * If the system app is both scanned and in the
2690                         * disabled packages list, then it must have been
2691                         * added via OTA. Remove it from the currently
2692                         * scanned package so the previously user-installed
2693                         * application can be scanned.
2694                         */
2695                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2696                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2697                                    + ps.name + "; removing system app.  Last known codePath="
2698                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2699                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2700                                    + scannedPkg.mVersionCode);
2701                            removePackageLI(scannedPkg, true);
2702                            mExpectingBetter.put(ps.name, ps.codePath);
2703                        }
2704
2705                        continue;
2706                    }
2707
2708                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2709                        psit.remove();
2710                        logCriticalInfo(Log.WARN, "System package " + ps.name
2711                                + " no longer exists; it's data will be wiped");
2712                        // Actual deletion of code and data will be handled by later
2713                        // reconciliation step
2714                    } else {
2715                        // we still have a disabled system package, but, it still might have
2716                        // been removed. check the code path still exists and check there's
2717                        // still a package. the latter can happen if an OTA keeps the same
2718                        // code path, but, changes the package name.
2719                        final PackageSetting disabledPs =
2720                                mSettings.getDisabledSystemPkgLPr(ps.name);
2721                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2722                                || disabledPs.pkg == null) {
2723                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2724                        }
2725                    }
2726                }
2727            }
2728
2729            //look for any incomplete package installations
2730            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2731            for (int i = 0; i < deletePkgsList.size(); i++) {
2732                // Actual deletion of code and data will be handled by later
2733                // reconciliation step
2734                final String packageName = deletePkgsList.get(i).name;
2735                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2736                synchronized (mPackages) {
2737                    mSettings.removePackageLPw(packageName);
2738                }
2739            }
2740
2741            //delete tmp files
2742            deleteTempPackageFiles();
2743
2744            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2745
2746            // Remove any shared userIDs that have no associated packages
2747            mSettings.pruneSharedUsersLPw();
2748            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2749            final int systemPackagesCount = mPackages.size();
2750            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2751                    + " ms, packageCount: " + systemPackagesCount
2752                    + " , timePerPackage: "
2753                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2754                    + " , cached: " + cachedSystemApps);
2755            if (mIsUpgrade && systemPackagesCount > 0) {
2756                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2757                        ((int) systemScanTime) / systemPackagesCount);
2758            }
2759            if (!mOnlyCore) {
2760                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2761                        SystemClock.uptimeMillis());
2762                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2763
2764                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2765                        | PackageParser.PARSE_FORWARD_LOCK,
2766                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2767
2768                // Remove disable package settings for updated system apps that were
2769                // removed via an OTA. If the update is no longer present, remove the
2770                // app completely. Otherwise, revoke their system privileges.
2771                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2772                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2773                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2774
2775                    final String msg;
2776                    if (deletedPkg == null) {
2777                        // should have found an update, but, we didn't; remove everything
2778                        msg = "Updated system package " + deletedAppName
2779                                + " no longer exists; removing its data";
2780                        // Actual deletion of code and data will be handled by later
2781                        // reconciliation step
2782                    } else {
2783                        // found an update; revoke system privileges
2784                        msg = "Updated system package + " + deletedAppName
2785                                + " no longer exists; revoking system privileges";
2786
2787                        // Don't do anything if a stub is removed from the system image. If
2788                        // we were to remove the uncompressed version from the /data partition,
2789                        // this is where it'd be done.
2790
2791                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2792                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2793                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2794                    }
2795                    logCriticalInfo(Log.WARN, msg);
2796                }
2797
2798                /*
2799                 * Make sure all system apps that we expected to appear on
2800                 * the userdata partition actually showed up. If they never
2801                 * appeared, crawl back and revive the system version.
2802                 */
2803                for (int i = 0; i < mExpectingBetter.size(); i++) {
2804                    final String packageName = mExpectingBetter.keyAt(i);
2805                    if (!mPackages.containsKey(packageName)) {
2806                        final File scanFile = mExpectingBetter.valueAt(i);
2807
2808                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2809                                + " but never showed up; reverting to system");
2810
2811                        int reparseFlags = mDefParseFlags;
2812                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2813                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2814                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2815                                    | PackageParser.PARSE_IS_PRIVILEGED;
2816                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2817                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2818                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2819                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2820                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2821                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2822                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2823                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2824                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2825                        } else {
2826                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2827                            continue;
2828                        }
2829
2830                        mSettings.enableSystemPackageLPw(packageName);
2831
2832                        try {
2833                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2834                        } catch (PackageManagerException e) {
2835                            Slog.e(TAG, "Failed to parse original system package: "
2836                                    + e.getMessage());
2837                        }
2838                    }
2839                }
2840
2841                // Uncompress and install any stubbed system applications.
2842                // This must be done last to ensure all stubs are replaced or disabled.
2843                decompressSystemApplications(stubSystemApps, scanFlags);
2844
2845                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2846                                - cachedSystemApps;
2847
2848                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2849                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2850                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2851                        + " ms, packageCount: " + dataPackagesCount
2852                        + " , timePerPackage: "
2853                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2854                        + " , cached: " + cachedNonSystemApps);
2855                if (mIsUpgrade && dataPackagesCount > 0) {
2856                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2857                            ((int) dataScanTime) / dataPackagesCount);
2858                }
2859            }
2860            mExpectingBetter.clear();
2861
2862            // Resolve the storage manager.
2863            mStorageManagerPackage = getStorageManagerPackageName();
2864
2865            // Resolve protected action filters. Only the setup wizard is allowed to
2866            // have a high priority filter for these actions.
2867            mSetupWizardPackage = getSetupWizardPackageName();
2868            if (mProtectedFilters.size() > 0) {
2869                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2870                    Slog.i(TAG, "No setup wizard;"
2871                        + " All protected intents capped to priority 0");
2872                }
2873                for (ActivityIntentInfo filter : mProtectedFilters) {
2874                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2875                        if (DEBUG_FILTERS) {
2876                            Slog.i(TAG, "Found setup wizard;"
2877                                + " allow priority " + filter.getPriority() + ";"
2878                                + " package: " + filter.activity.info.packageName
2879                                + " activity: " + filter.activity.className
2880                                + " priority: " + filter.getPriority());
2881                        }
2882                        // skip setup wizard; allow it to keep the high priority filter
2883                        continue;
2884                    }
2885                    if (DEBUG_FILTERS) {
2886                        Slog.i(TAG, "Protected action; cap priority to 0;"
2887                                + " package: " + filter.activity.info.packageName
2888                                + " activity: " + filter.activity.className
2889                                + " origPrio: " + filter.getPriority());
2890                    }
2891                    filter.setPriority(0);
2892                }
2893            }
2894            mDeferProtectedFilters = false;
2895            mProtectedFilters.clear();
2896
2897            // Now that we know all of the shared libraries, update all clients to have
2898            // the correct library paths.
2899            updateAllSharedLibrariesLPw(null);
2900
2901            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2902                // NOTE: We ignore potential failures here during a system scan (like
2903                // the rest of the commands above) because there's precious little we
2904                // can do about it. A settings error is reported, though.
2905                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2906            }
2907
2908            // Now that we know all the packages we are keeping,
2909            // read and update their last usage times.
2910            mPackageUsage.read(mPackages);
2911            mCompilerStats.read();
2912
2913            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2914                    SystemClock.uptimeMillis());
2915            Slog.i(TAG, "Time to scan packages: "
2916                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2917                    + " seconds");
2918
2919            // If the platform SDK has changed since the last time we booted,
2920            // we need to re-grant app permission to catch any new ones that
2921            // appear.  This is really a hack, and means that apps can in some
2922            // cases get permissions that the user didn't initially explicitly
2923            // allow...  it would be nice to have some better way to handle
2924            // this situation.
2925            int updateFlags = UPDATE_PERMISSIONS_ALL;
2926            if (ver.sdkVersion != mSdkVersion) {
2927                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2928                        + mSdkVersion + "; regranting permissions for internal storage");
2929                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2930            }
2931            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2932            ver.sdkVersion = mSdkVersion;
2933
2934            // If this is the first boot or an update from pre-M, and it is a normal
2935            // boot, then we need to initialize the default preferred apps across
2936            // all defined users.
2937            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2938                for (UserInfo user : sUserManager.getUsers(true)) {
2939                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2940                    applyFactoryDefaultBrowserLPw(user.id);
2941                    primeDomainVerificationsLPw(user.id);
2942                }
2943            }
2944
2945            // Prepare storage for system user really early during boot,
2946            // since core system apps like SettingsProvider and SystemUI
2947            // can't wait for user to start
2948            final int storageFlags;
2949            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2950                storageFlags = StorageManager.FLAG_STORAGE_DE;
2951            } else {
2952                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2953            }
2954            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2955                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2956                    true /* onlyCoreApps */);
2957            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2958                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
2959                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2960                traceLog.traceBegin("AppDataFixup");
2961                try {
2962                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2963                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2964                } catch (InstallerException e) {
2965                    Slog.w(TAG, "Trouble fixing GIDs", e);
2966                }
2967                traceLog.traceEnd();
2968
2969                traceLog.traceBegin("AppDataPrepare");
2970                if (deferPackages == null || deferPackages.isEmpty()) {
2971                    return;
2972                }
2973                int count = 0;
2974                for (String pkgName : deferPackages) {
2975                    PackageParser.Package pkg = null;
2976                    synchronized (mPackages) {
2977                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2978                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2979                            pkg = ps.pkg;
2980                        }
2981                    }
2982                    if (pkg != null) {
2983                        synchronized (mInstallLock) {
2984                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2985                                    true /* maybeMigrateAppData */);
2986                        }
2987                        count++;
2988                    }
2989                }
2990                traceLog.traceEnd();
2991                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2992            }, "prepareAppData");
2993
2994            // If this is first boot after an OTA, and a normal boot, then
2995            // we need to clear code cache directories.
2996            // Note that we do *not* clear the application profiles. These remain valid
2997            // across OTAs and are used to drive profile verification (post OTA) and
2998            // profile compilation (without waiting to collect a fresh set of profiles).
2999            if (mIsUpgrade && !onlyCore) {
3000                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
3001                for (int i = 0; i < mSettings.mPackages.size(); i++) {
3002                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
3003                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
3004                        // No apps are running this early, so no need to freeze
3005                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
3006                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
3007                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
3008                    }
3009                }
3010                ver.fingerprint = Build.FINGERPRINT;
3011            }
3012
3013            checkDefaultBrowser();
3014
3015            // clear only after permissions and other defaults have been updated
3016            mExistingSystemPackages.clear();
3017            mPromoteSystemApps = false;
3018
3019            // All the changes are done during package scanning.
3020            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3021
3022            // can downgrade to reader
3023            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3024            mSettings.writeLPr();
3025            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3026            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3027                    SystemClock.uptimeMillis());
3028
3029            if (!mOnlyCore) {
3030                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3031                mRequiredInstallerPackage = getRequiredInstallerLPr();
3032                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3033                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3034                if (mIntentFilterVerifierComponent != null) {
3035                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3036                            mIntentFilterVerifierComponent);
3037                } else {
3038                    mIntentFilterVerifier = null;
3039                }
3040                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3041                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3042                        SharedLibraryInfo.VERSION_UNDEFINED);
3043                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3044                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3045                        SharedLibraryInfo.VERSION_UNDEFINED);
3046            } else {
3047                mRequiredVerifierPackage = null;
3048                mRequiredInstallerPackage = null;
3049                mRequiredUninstallerPackage = null;
3050                mIntentFilterVerifierComponent = null;
3051                mIntentFilterVerifier = null;
3052                mServicesSystemSharedLibraryPackageName = null;
3053                mSharedSystemSharedLibraryPackageName = null;
3054            }
3055
3056            mInstallerService = new PackageInstallerService(context, this);
3057            final Pair<ComponentName, String> instantAppResolverComponent =
3058                    getInstantAppResolverLPr();
3059            if (instantAppResolverComponent != null) {
3060                if (DEBUG_EPHEMERAL) {
3061                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3062                }
3063                mInstantAppResolverConnection = new EphemeralResolverConnection(
3064                        mContext, instantAppResolverComponent.first,
3065                        instantAppResolverComponent.second);
3066                mInstantAppResolverSettingsComponent =
3067                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3068            } else {
3069                mInstantAppResolverConnection = null;
3070                mInstantAppResolverSettingsComponent = null;
3071            }
3072            updateInstantAppInstallerLocked(null);
3073
3074            // Read and update the usage of dex files.
3075            // Do this at the end of PM init so that all the packages have their
3076            // data directory reconciled.
3077            // At this point we know the code paths of the packages, so we can validate
3078            // the disk file and build the internal cache.
3079            // The usage file is expected to be small so loading and verifying it
3080            // should take a fairly small time compare to the other activities (e.g. package
3081            // scanning).
3082            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3083            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3084            for (int userId : currentUserIds) {
3085                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3086            }
3087            mDexManager.load(userPackages);
3088            if (mIsUpgrade) {
3089                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3090                        (int) (SystemClock.uptimeMillis() - startTime));
3091            }
3092        } // synchronized (mPackages)
3093        } // synchronized (mInstallLock)
3094
3095        // Now after opening every single application zip, make sure they
3096        // are all flushed.  Not really needed, but keeps things nice and
3097        // tidy.
3098        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3099        Runtime.getRuntime().gc();
3100        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3101
3102        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3103        FallbackCategoryProvider.loadFallbacks();
3104        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3105
3106        // The initial scanning above does many calls into installd while
3107        // holding the mPackages lock, but we're mostly interested in yelling
3108        // once we have a booted system.
3109        mInstaller.setWarnIfHeld(mPackages);
3110
3111        // Expose private service for system components to use.
3112        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3113        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3114    }
3115
3116    /**
3117     * Uncompress and install stub applications.
3118     * <p>In order to save space on the system partition, some applications are shipped in a
3119     * compressed form. In addition the compressed bits for the full application, the
3120     * system image contains a tiny stub comprised of only the Android manifest.
3121     * <p>During the first boot, attempt to uncompress and install the full application. If
3122     * the application can't be installed for any reason, disable the stub and prevent
3123     * uncompressing the full application during future boots.
3124     * <p>In order to forcefully attempt an installation of a full application, go to app
3125     * settings and enable the application.
3126     */
3127    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3128        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3129            final String pkgName = stubSystemApps.get(i);
3130            // skip if the system package is already disabled
3131            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3132                stubSystemApps.remove(i);
3133                continue;
3134            }
3135            // skip if the package isn't installed (?!); this should never happen
3136            final PackageParser.Package pkg = mPackages.get(pkgName);
3137            if (pkg == null) {
3138                stubSystemApps.remove(i);
3139                continue;
3140            }
3141            // skip if the package has been disabled by the user
3142            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3143            if (ps != null) {
3144                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3145                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3146                    stubSystemApps.remove(i);
3147                    continue;
3148                }
3149            }
3150
3151            if (DEBUG_COMPRESSION) {
3152                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3153            }
3154
3155            // uncompress the binary to its eventual destination on /data
3156            final File scanFile = decompressPackage(pkg);
3157            if (scanFile == null) {
3158                continue;
3159            }
3160
3161            // install the package to replace the stub on /system
3162            try {
3163                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3164                removePackageLI(pkg, true /*chatty*/);
3165                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3166                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3167                        UserHandle.USER_SYSTEM, "android");
3168                stubSystemApps.remove(i);
3169                continue;
3170            } catch (PackageManagerException e) {
3171                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3172            }
3173
3174            // any failed attempt to install the package will be cleaned up later
3175        }
3176
3177        // disable any stub still left; these failed to install the full application
3178        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3179            final String pkgName = stubSystemApps.get(i);
3180            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3181            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3182                    UserHandle.USER_SYSTEM, "android");
3183            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3184        }
3185    }
3186
3187    private int decompressFile(File srcFile, File dstFile) throws ErrnoException {
3188        if (DEBUG_COMPRESSION) {
3189            Slog.i(TAG, "Decompress file"
3190                    + "; src: " + srcFile.getAbsolutePath()
3191                    + ", dst: " + dstFile.getAbsolutePath());
3192        }
3193        try (
3194                InputStream fileIn = new GZIPInputStream(new FileInputStream(srcFile));
3195                OutputStream fileOut = new FileOutputStream(dstFile, false /*append*/);
3196        ) {
3197            Streams.copy(fileIn, fileOut);
3198            Os.chmod(dstFile.getAbsolutePath(), 0644);
3199            return PackageManager.INSTALL_SUCCEEDED;
3200        } catch (IOException e) {
3201            logCriticalInfo(Log.ERROR, "Failed to decompress file"
3202                    + "; src: " + srcFile.getAbsolutePath()
3203                    + ", dst: " + dstFile.getAbsolutePath());
3204        }
3205        return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3206    }
3207
3208    private File[] getCompressedFiles(String codePath) {
3209        final File stubCodePath = new File(codePath);
3210        final String stubName = stubCodePath.getName();
3211
3212        // The layout of a compressed package on a given partition is as follows :
3213        //
3214        // Compressed artifacts:
3215        //
3216        // /partition/ModuleName/foo.gz
3217        // /partation/ModuleName/bar.gz
3218        //
3219        // Stub artifact:
3220        //
3221        // /partition/ModuleName-Stub/ModuleName-Stub.apk
3222        //
3223        // In other words, stub is on the same partition as the compressed artifacts
3224        // and in a directory that's suffixed with "-Stub".
3225        int idx = stubName.lastIndexOf(STUB_SUFFIX);
3226        if (idx < 0 || (stubName.length() != (idx + STUB_SUFFIX.length()))) {
3227            return null;
3228        }
3229
3230        final File stubParentDir = stubCodePath.getParentFile();
3231        if (stubParentDir == null) {
3232            Slog.e(TAG, "Unable to determine stub parent dir for codePath: " + codePath);
3233            return null;
3234        }
3235
3236        final File compressedPath = new File(stubParentDir, stubName.substring(0, idx));
3237        final File[] files = compressedPath.listFiles(new FilenameFilter() {
3238            @Override
3239            public boolean accept(File dir, String name) {
3240                return name.toLowerCase().endsWith(COMPRESSED_EXTENSION);
3241            }
3242        });
3243
3244        if (DEBUG_COMPRESSION && files != null && files.length > 0) {
3245            Slog.i(TAG, "getCompressedFiles[" + codePath + "]: " + Arrays.toString(files));
3246        }
3247
3248        return files;
3249    }
3250
3251    private boolean compressedFileExists(String codePath) {
3252        final File[] compressedFiles = getCompressedFiles(codePath);
3253        return compressedFiles != null && compressedFiles.length > 0;
3254    }
3255
3256    /**
3257     * Decompresses the given package on the system image onto
3258     * the /data partition.
3259     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3260     */
3261    private File decompressPackage(PackageParser.Package pkg) {
3262        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3263        if (compressedFiles == null || compressedFiles.length == 0) {
3264            if (DEBUG_COMPRESSION) {
3265                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3266            }
3267            return null;
3268        }
3269        final File dstCodePath =
3270                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3271        int ret = PackageManager.INSTALL_SUCCEEDED;
3272        try {
3273            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3274            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3275            for (File srcFile : compressedFiles) {
3276                final String srcFileName = srcFile.getName();
3277                final String dstFileName = srcFileName.substring(
3278                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3279                final File dstFile = new File(dstCodePath, dstFileName);
3280                ret = decompressFile(srcFile, dstFile);
3281                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3282                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3283                            + "; pkg: " + pkg.packageName
3284                            + ", file: " + dstFileName);
3285                    break;
3286                }
3287            }
3288        } catch (ErrnoException e) {
3289            logCriticalInfo(Log.ERROR, "Failed to decompress"
3290                    + "; pkg: " + pkg.packageName
3291                    + ", err: " + e.errno);
3292        }
3293        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3294            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3295            NativeLibraryHelper.Handle handle = null;
3296            try {
3297                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3298                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3299                        null /*abiOverride*/);
3300            } catch (IOException e) {
3301                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3302                        + "; pkg: " + pkg.packageName);
3303                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3304            } finally {
3305                IoUtils.closeQuietly(handle);
3306            }
3307        }
3308        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3309            if (dstCodePath == null || !dstCodePath.exists()) {
3310                return null;
3311            }
3312            removeCodePathLI(dstCodePath);
3313            return null;
3314        }
3315        return dstCodePath;
3316    }
3317
3318    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3319        // we're only interested in updating the installer appliction when 1) it's not
3320        // already set or 2) the modified package is the installer
3321        if (mInstantAppInstallerActivity != null
3322                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3323                        .equals(modifiedPackage)) {
3324            return;
3325        }
3326        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3327    }
3328
3329    private static File preparePackageParserCache(boolean isUpgrade) {
3330        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3331            return null;
3332        }
3333
3334        // Disable package parsing on eng builds to allow for faster incremental development.
3335        if (Build.IS_ENG) {
3336            return null;
3337        }
3338
3339        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3340            Slog.i(TAG, "Disabling package parser cache due to system property.");
3341            return null;
3342        }
3343
3344        // The base directory for the package parser cache lives under /data/system/.
3345        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3346                "package_cache");
3347        if (cacheBaseDir == null) {
3348            return null;
3349        }
3350
3351        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3352        // This also serves to "GC" unused entries when the package cache version changes (which
3353        // can only happen during upgrades).
3354        if (isUpgrade) {
3355            FileUtils.deleteContents(cacheBaseDir);
3356        }
3357
3358
3359        // Return the versioned package cache directory. This is something like
3360        // "/data/system/package_cache/1"
3361        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3362
3363        // The following is a workaround to aid development on non-numbered userdebug
3364        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3365        // the system partition is newer.
3366        //
3367        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3368        // that starts with "eng." to signify that this is an engineering build and not
3369        // destined for release.
3370        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3371            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3372
3373            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3374            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3375            // in general and should not be used for production changes. In this specific case,
3376            // we know that they will work.
3377            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3378            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3379                FileUtils.deleteContents(cacheBaseDir);
3380                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3381            }
3382        }
3383
3384        return cacheDir;
3385    }
3386
3387    @Override
3388    public boolean isFirstBoot() {
3389        // allow instant applications
3390        return mFirstBoot;
3391    }
3392
3393    @Override
3394    public boolean isOnlyCoreApps() {
3395        // allow instant applications
3396        return mOnlyCore;
3397    }
3398
3399    @Override
3400    public boolean isUpgrade() {
3401        // allow instant applications
3402        return mIsUpgrade;
3403    }
3404
3405    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3406        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3407
3408        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3409                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3410                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3411        if (matches.size() == 1) {
3412            return matches.get(0).getComponentInfo().packageName;
3413        } else if (matches.size() == 0) {
3414            Log.e(TAG, "There should probably be a verifier, but, none were found");
3415            return null;
3416        }
3417        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3418    }
3419
3420    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3421        synchronized (mPackages) {
3422            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3423            if (libraryEntry == null) {
3424                throw new IllegalStateException("Missing required shared library:" + name);
3425            }
3426            return libraryEntry.apk;
3427        }
3428    }
3429
3430    private @NonNull String getRequiredInstallerLPr() {
3431        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3432        intent.addCategory(Intent.CATEGORY_DEFAULT);
3433        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3434
3435        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3436                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3437                UserHandle.USER_SYSTEM);
3438        if (matches.size() == 1) {
3439            ResolveInfo resolveInfo = matches.get(0);
3440            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3441                throw new RuntimeException("The installer must be a privileged app");
3442            }
3443            return matches.get(0).getComponentInfo().packageName;
3444        } else {
3445            throw new RuntimeException("There must be exactly one installer; found " + matches);
3446        }
3447    }
3448
3449    private @NonNull String getRequiredUninstallerLPr() {
3450        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3451        intent.addCategory(Intent.CATEGORY_DEFAULT);
3452        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3453
3454        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3455                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3456                UserHandle.USER_SYSTEM);
3457        if (resolveInfo == null ||
3458                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3459            throw new RuntimeException("There must be exactly one uninstaller; found "
3460                    + resolveInfo);
3461        }
3462        return resolveInfo.getComponentInfo().packageName;
3463    }
3464
3465    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3466        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3467
3468        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3469                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3470                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3471        ResolveInfo best = null;
3472        final int N = matches.size();
3473        for (int i = 0; i < N; i++) {
3474            final ResolveInfo cur = matches.get(i);
3475            final String packageName = cur.getComponentInfo().packageName;
3476            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3477                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3478                continue;
3479            }
3480
3481            if (best == null || cur.priority > best.priority) {
3482                best = cur;
3483            }
3484        }
3485
3486        if (best != null) {
3487            return best.getComponentInfo().getComponentName();
3488        }
3489        Slog.w(TAG, "Intent filter verifier not found");
3490        return null;
3491    }
3492
3493    @Override
3494    public @Nullable ComponentName getInstantAppResolverComponent() {
3495        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3496            return null;
3497        }
3498        synchronized (mPackages) {
3499            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3500            if (instantAppResolver == null) {
3501                return null;
3502            }
3503            return instantAppResolver.first;
3504        }
3505    }
3506
3507    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3508        final String[] packageArray =
3509                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3510        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3511            if (DEBUG_EPHEMERAL) {
3512                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3513            }
3514            return null;
3515        }
3516
3517        final int callingUid = Binder.getCallingUid();
3518        final int resolveFlags =
3519                MATCH_DIRECT_BOOT_AWARE
3520                | MATCH_DIRECT_BOOT_UNAWARE
3521                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3522        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3523        final Intent resolverIntent = new Intent(actionName);
3524        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3525                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3526        // temporarily look for the old action
3527        if (resolvers.size() == 0) {
3528            if (DEBUG_EPHEMERAL) {
3529                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3530            }
3531            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3532            resolverIntent.setAction(actionName);
3533            resolvers = queryIntentServicesInternal(resolverIntent, null,
3534                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3535        }
3536        final int N = resolvers.size();
3537        if (N == 0) {
3538            if (DEBUG_EPHEMERAL) {
3539                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3540            }
3541            return null;
3542        }
3543
3544        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3545        for (int i = 0; i < N; i++) {
3546            final ResolveInfo info = resolvers.get(i);
3547
3548            if (info.serviceInfo == null) {
3549                continue;
3550            }
3551
3552            final String packageName = info.serviceInfo.packageName;
3553            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3554                if (DEBUG_EPHEMERAL) {
3555                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3556                            + " pkg: " + packageName + ", info:" + info);
3557                }
3558                continue;
3559            }
3560
3561            if (DEBUG_EPHEMERAL) {
3562                Slog.v(TAG, "Ephemeral resolver found;"
3563                        + " pkg: " + packageName + ", info:" + info);
3564            }
3565            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3566        }
3567        if (DEBUG_EPHEMERAL) {
3568            Slog.v(TAG, "Ephemeral resolver NOT found");
3569        }
3570        return null;
3571    }
3572
3573    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3574        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3575        intent.addCategory(Intent.CATEGORY_DEFAULT);
3576        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3577
3578        final int resolveFlags =
3579                MATCH_DIRECT_BOOT_AWARE
3580                | MATCH_DIRECT_BOOT_UNAWARE
3581                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3582        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3583                resolveFlags, UserHandle.USER_SYSTEM);
3584        // temporarily look for the old action
3585        if (matches.isEmpty()) {
3586            if (DEBUG_EPHEMERAL) {
3587                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3588            }
3589            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3590            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3591                    resolveFlags, UserHandle.USER_SYSTEM);
3592        }
3593        Iterator<ResolveInfo> iter = matches.iterator();
3594        while (iter.hasNext()) {
3595            final ResolveInfo rInfo = iter.next();
3596            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3597            if (ps != null) {
3598                final PermissionsState permissionsState = ps.getPermissionsState();
3599                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3600                    continue;
3601                }
3602            }
3603            iter.remove();
3604        }
3605        if (matches.size() == 0) {
3606            return null;
3607        } else if (matches.size() == 1) {
3608            return (ActivityInfo) matches.get(0).getComponentInfo();
3609        } else {
3610            throw new RuntimeException(
3611                    "There must be at most one ephemeral installer; found " + matches);
3612        }
3613    }
3614
3615    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3616            @NonNull ComponentName resolver) {
3617        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3618                .addCategory(Intent.CATEGORY_DEFAULT)
3619                .setPackage(resolver.getPackageName());
3620        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3621        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3622                UserHandle.USER_SYSTEM);
3623        // temporarily look for the old action
3624        if (matches.isEmpty()) {
3625            if (DEBUG_EPHEMERAL) {
3626                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3627            }
3628            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3629            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3630                    UserHandle.USER_SYSTEM);
3631        }
3632        if (matches.isEmpty()) {
3633            return null;
3634        }
3635        return matches.get(0).getComponentInfo().getComponentName();
3636    }
3637
3638    private void primeDomainVerificationsLPw(int userId) {
3639        if (DEBUG_DOMAIN_VERIFICATION) {
3640            Slog.d(TAG, "Priming domain verifications in user " + userId);
3641        }
3642
3643        SystemConfig systemConfig = SystemConfig.getInstance();
3644        ArraySet<String> packages = systemConfig.getLinkedApps();
3645
3646        for (String packageName : packages) {
3647            PackageParser.Package pkg = mPackages.get(packageName);
3648            if (pkg != null) {
3649                if (!pkg.isSystemApp()) {
3650                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3651                    continue;
3652                }
3653
3654                ArraySet<String> domains = null;
3655                for (PackageParser.Activity a : pkg.activities) {
3656                    for (ActivityIntentInfo filter : a.intents) {
3657                        if (hasValidDomains(filter)) {
3658                            if (domains == null) {
3659                                domains = new ArraySet<String>();
3660                            }
3661                            domains.addAll(filter.getHostsList());
3662                        }
3663                    }
3664                }
3665
3666                if (domains != null && domains.size() > 0) {
3667                    if (DEBUG_DOMAIN_VERIFICATION) {
3668                        Slog.v(TAG, "      + " + packageName);
3669                    }
3670                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3671                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3672                    // and then 'always' in the per-user state actually used for intent resolution.
3673                    final IntentFilterVerificationInfo ivi;
3674                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3675                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3676                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3677                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3678                } else {
3679                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3680                            + "' does not handle web links");
3681                }
3682            } else {
3683                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3684            }
3685        }
3686
3687        scheduleWritePackageRestrictionsLocked(userId);
3688        scheduleWriteSettingsLocked();
3689    }
3690
3691    private void applyFactoryDefaultBrowserLPw(int userId) {
3692        // The default browser app's package name is stored in a string resource,
3693        // with a product-specific overlay used for vendor customization.
3694        String browserPkg = mContext.getResources().getString(
3695                com.android.internal.R.string.default_browser);
3696        if (!TextUtils.isEmpty(browserPkg)) {
3697            // non-empty string => required to be a known package
3698            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3699            if (ps == null) {
3700                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3701                browserPkg = null;
3702            } else {
3703                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3704            }
3705        }
3706
3707        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3708        // default.  If there's more than one, just leave everything alone.
3709        if (browserPkg == null) {
3710            calculateDefaultBrowserLPw(userId);
3711        }
3712    }
3713
3714    private void calculateDefaultBrowserLPw(int userId) {
3715        List<String> allBrowsers = resolveAllBrowserApps(userId);
3716        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3717        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3718    }
3719
3720    private List<String> resolveAllBrowserApps(int userId) {
3721        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3722        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3723                PackageManager.MATCH_ALL, userId);
3724
3725        final int count = list.size();
3726        List<String> result = new ArrayList<String>(count);
3727        for (int i=0; i<count; i++) {
3728            ResolveInfo info = list.get(i);
3729            if (info.activityInfo == null
3730                    || !info.handleAllWebDataURI
3731                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3732                    || result.contains(info.activityInfo.packageName)) {
3733                continue;
3734            }
3735            result.add(info.activityInfo.packageName);
3736        }
3737
3738        return result;
3739    }
3740
3741    private boolean packageIsBrowser(String packageName, int userId) {
3742        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3743                PackageManager.MATCH_ALL, userId);
3744        final int N = list.size();
3745        for (int i = 0; i < N; i++) {
3746            ResolveInfo info = list.get(i);
3747            if (packageName.equals(info.activityInfo.packageName)) {
3748                return true;
3749            }
3750        }
3751        return false;
3752    }
3753
3754    private void checkDefaultBrowser() {
3755        final int myUserId = UserHandle.myUserId();
3756        final String packageName = getDefaultBrowserPackageName(myUserId);
3757        if (packageName != null) {
3758            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3759            if (info == null) {
3760                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3761                synchronized (mPackages) {
3762                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3763                }
3764            }
3765        }
3766    }
3767
3768    @Override
3769    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3770            throws RemoteException {
3771        try {
3772            return super.onTransact(code, data, reply, flags);
3773        } catch (RuntimeException e) {
3774            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3775                Slog.wtf(TAG, "Package Manager Crash", e);
3776            }
3777            throw e;
3778        }
3779    }
3780
3781    static int[] appendInts(int[] cur, int[] add) {
3782        if (add == null) return cur;
3783        if (cur == null) return add;
3784        final int N = add.length;
3785        for (int i=0; i<N; i++) {
3786            cur = appendInt(cur, add[i]);
3787        }
3788        return cur;
3789    }
3790
3791    /**
3792     * Returns whether or not a full application can see an instant application.
3793     * <p>
3794     * Currently, there are three cases in which this can occur:
3795     * <ol>
3796     * <li>The calling application is a "special" process. The special
3797     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3798     *     and {@code 0}</li>
3799     * <li>The calling application has the permission
3800     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3801     * <li>The calling application is the default launcher on the
3802     *     system partition.</li>
3803     * </ol>
3804     */
3805    private boolean canViewInstantApps(int callingUid, int userId) {
3806        if (callingUid == Process.SYSTEM_UID
3807                || callingUid == Process.SHELL_UID
3808                || callingUid == Process.ROOT_UID) {
3809            return true;
3810        }
3811        if (mContext.checkCallingOrSelfPermission(
3812                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3813            return true;
3814        }
3815        if (mContext.checkCallingOrSelfPermission(
3816                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3817            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3818            if (homeComponent != null
3819                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3820                return true;
3821            }
3822        }
3823        return false;
3824    }
3825
3826    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3827        if (!sUserManager.exists(userId)) return null;
3828        if (ps == null) {
3829            return null;
3830        }
3831        PackageParser.Package p = ps.pkg;
3832        if (p == null) {
3833            return null;
3834        }
3835        final int callingUid = Binder.getCallingUid();
3836        // Filter out ephemeral app metadata:
3837        //   * The system/shell/root can see metadata for any app
3838        //   * An installed app can see metadata for 1) other installed apps
3839        //     and 2) ephemeral apps that have explicitly interacted with it
3840        //   * Ephemeral apps can only see their own data and exposed installed apps
3841        //   * Holding a signature permission allows seeing instant apps
3842        if (filterAppAccessLPr(ps, callingUid, userId)) {
3843            return null;
3844        }
3845
3846        final PermissionsState permissionsState = ps.getPermissionsState();
3847
3848        // Compute GIDs only if requested
3849        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3850                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3851        // Compute granted permissions only if package has requested permissions
3852        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3853                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3854        final PackageUserState state = ps.readUserState(userId);
3855
3856        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3857                && ps.isSystem()) {
3858            flags |= MATCH_ANY_USER;
3859        }
3860
3861        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3862                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3863
3864        if (packageInfo == null) {
3865            return null;
3866        }
3867
3868        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3869                resolveExternalPackageNameLPr(p);
3870
3871        return packageInfo;
3872    }
3873
3874    @Override
3875    public void checkPackageStartable(String packageName, int userId) {
3876        final int callingUid = Binder.getCallingUid();
3877        if (getInstantAppPackageName(callingUid) != null) {
3878            throw new SecurityException("Instant applications don't have access to this method");
3879        }
3880        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3881        synchronized (mPackages) {
3882            final PackageSetting ps = mSettings.mPackages.get(packageName);
3883            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3884                throw new SecurityException("Package " + packageName + " was not found!");
3885            }
3886
3887            if (!ps.getInstalled(userId)) {
3888                throw new SecurityException(
3889                        "Package " + packageName + " was not installed for user " + userId + "!");
3890            }
3891
3892            if (mSafeMode && !ps.isSystem()) {
3893                throw new SecurityException("Package " + packageName + " not a system app!");
3894            }
3895
3896            if (mFrozenPackages.contains(packageName)) {
3897                throw new SecurityException("Package " + packageName + " is currently frozen!");
3898            }
3899
3900            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3901                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3902            }
3903        }
3904    }
3905
3906    @Override
3907    public boolean isPackageAvailable(String packageName, int userId) {
3908        if (!sUserManager.exists(userId)) return false;
3909        final int callingUid = Binder.getCallingUid();
3910        enforceCrossUserPermission(callingUid, userId,
3911                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3912        synchronized (mPackages) {
3913            PackageParser.Package p = mPackages.get(packageName);
3914            if (p != null) {
3915                final PackageSetting ps = (PackageSetting) p.mExtras;
3916                if (filterAppAccessLPr(ps, callingUid, userId)) {
3917                    return false;
3918                }
3919                if (ps != null) {
3920                    final PackageUserState state = ps.readUserState(userId);
3921                    if (state != null) {
3922                        return PackageParser.isAvailable(state);
3923                    }
3924                }
3925            }
3926        }
3927        return false;
3928    }
3929
3930    @Override
3931    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3932        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3933                flags, Binder.getCallingUid(), userId);
3934    }
3935
3936    @Override
3937    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3938            int flags, int userId) {
3939        return getPackageInfoInternal(versionedPackage.getPackageName(),
3940                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3941    }
3942
3943    /**
3944     * Important: The provided filterCallingUid is used exclusively to filter out packages
3945     * that can be seen based on user state. It's typically the original caller uid prior
3946     * to clearing. Because it can only be provided by trusted code, it's value can be
3947     * trusted and will be used as-is; unlike userId which will be validated by this method.
3948     */
3949    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3950            int flags, int filterCallingUid, int userId) {
3951        if (!sUserManager.exists(userId)) return null;
3952        flags = updateFlagsForPackage(flags, userId, packageName);
3953        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3954                false /* requireFullPermission */, false /* checkShell */, "get package info");
3955
3956        // reader
3957        synchronized (mPackages) {
3958            // Normalize package name to handle renamed packages and static libs
3959            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3960
3961            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3962            if (matchFactoryOnly) {
3963                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3964                if (ps != null) {
3965                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3966                        return null;
3967                    }
3968                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3969                        return null;
3970                    }
3971                    return generatePackageInfo(ps, flags, userId);
3972                }
3973            }
3974
3975            PackageParser.Package p = mPackages.get(packageName);
3976            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3977                return null;
3978            }
3979            if (DEBUG_PACKAGE_INFO)
3980                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3981            if (p != null) {
3982                final PackageSetting ps = (PackageSetting) p.mExtras;
3983                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3984                    return null;
3985                }
3986                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3987                    return null;
3988                }
3989                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3990            }
3991            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3992                final PackageSetting ps = mSettings.mPackages.get(packageName);
3993                if (ps == null) return null;
3994                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3995                    return null;
3996                }
3997                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3998                    return null;
3999                }
4000                return generatePackageInfo(ps, flags, userId);
4001            }
4002        }
4003        return null;
4004    }
4005
4006    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
4007        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
4008            return true;
4009        }
4010        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
4011            return true;
4012        }
4013        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
4014            return true;
4015        }
4016        return false;
4017    }
4018
4019    private boolean isComponentVisibleToInstantApp(
4020            @Nullable ComponentName component, @ComponentType int type) {
4021        if (type == TYPE_ACTIVITY) {
4022            final PackageParser.Activity activity = mActivities.mActivities.get(component);
4023            return activity != null
4024                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4025                    : false;
4026        } else if (type == TYPE_RECEIVER) {
4027            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
4028            return activity != null
4029                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4030                    : false;
4031        } else if (type == TYPE_SERVICE) {
4032            final PackageParser.Service service = mServices.mServices.get(component);
4033            return service != null
4034                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4035                    : false;
4036        } else if (type == TYPE_PROVIDER) {
4037            final PackageParser.Provider provider = mProviders.mProviders.get(component);
4038            return provider != null
4039                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4040                    : false;
4041        } else if (type == TYPE_UNKNOWN) {
4042            return isComponentVisibleToInstantApp(component);
4043        }
4044        return false;
4045    }
4046
4047    /**
4048     * Returns whether or not access to the application should be filtered.
4049     * <p>
4050     * Access may be limited based upon whether the calling or target applications
4051     * are instant applications.
4052     *
4053     * @see #canAccessInstantApps(int)
4054     */
4055    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4056            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4057        // if we're in an isolated process, get the real calling UID
4058        if (Process.isIsolated(callingUid)) {
4059            callingUid = mIsolatedOwners.get(callingUid);
4060        }
4061        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4062        final boolean callerIsInstantApp = instantAppPkgName != null;
4063        if (ps == null) {
4064            if (callerIsInstantApp) {
4065                // pretend the application exists, but, needs to be filtered
4066                return true;
4067            }
4068            return false;
4069        }
4070        // if the target and caller are the same application, don't filter
4071        if (isCallerSameApp(ps.name, callingUid)) {
4072            return false;
4073        }
4074        if (callerIsInstantApp) {
4075            // request for a specific component; if it hasn't been explicitly exposed, filter
4076            if (component != null) {
4077                return !isComponentVisibleToInstantApp(component, componentType);
4078            }
4079            // request for application; if no components have been explicitly exposed, filter
4080            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
4081        }
4082        if (ps.getInstantApp(userId)) {
4083            // caller can see all components of all instant applications, don't filter
4084            if (canViewInstantApps(callingUid, userId)) {
4085                return false;
4086            }
4087            // request for a specific instant application component, filter
4088            if (component != null) {
4089                return true;
4090            }
4091            // request for an instant application; if the caller hasn't been granted access, filter
4092            return !mInstantAppRegistry.isInstantAccessGranted(
4093                    userId, UserHandle.getAppId(callingUid), ps.appId);
4094        }
4095        return false;
4096    }
4097
4098    /**
4099     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4100     */
4101    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4102        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4103    }
4104
4105    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4106            int flags) {
4107        // Callers can access only the libs they depend on, otherwise they need to explicitly
4108        // ask for the shared libraries given the caller is allowed to access all static libs.
4109        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4110            // System/shell/root get to see all static libs
4111            final int appId = UserHandle.getAppId(uid);
4112            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4113                    || appId == Process.ROOT_UID) {
4114                return false;
4115            }
4116        }
4117
4118        // No package means no static lib as it is always on internal storage
4119        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4120            return false;
4121        }
4122
4123        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4124                ps.pkg.staticSharedLibVersion);
4125        if (libEntry == null) {
4126            return false;
4127        }
4128
4129        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4130        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4131        if (uidPackageNames == null) {
4132            return true;
4133        }
4134
4135        for (String uidPackageName : uidPackageNames) {
4136            if (ps.name.equals(uidPackageName)) {
4137                return false;
4138            }
4139            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4140            if (uidPs != null) {
4141                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4142                        libEntry.info.getName());
4143                if (index < 0) {
4144                    continue;
4145                }
4146                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
4147                    return false;
4148                }
4149            }
4150        }
4151        return true;
4152    }
4153
4154    @Override
4155    public String[] currentToCanonicalPackageNames(String[] names) {
4156        final int callingUid = Binder.getCallingUid();
4157        if (getInstantAppPackageName(callingUid) != null) {
4158            return names;
4159        }
4160        final String[] out = new String[names.length];
4161        // reader
4162        synchronized (mPackages) {
4163            final int callingUserId = UserHandle.getUserId(callingUid);
4164            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4165            for (int i=names.length-1; i>=0; i--) {
4166                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4167                boolean translateName = false;
4168                if (ps != null && ps.realName != null) {
4169                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4170                    translateName = !targetIsInstantApp
4171                            || canViewInstantApps
4172                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4173                                    UserHandle.getAppId(callingUid), ps.appId);
4174                }
4175                out[i] = translateName ? ps.realName : names[i];
4176            }
4177        }
4178        return out;
4179    }
4180
4181    @Override
4182    public String[] canonicalToCurrentPackageNames(String[] names) {
4183        final int callingUid = Binder.getCallingUid();
4184        if (getInstantAppPackageName(callingUid) != null) {
4185            return names;
4186        }
4187        final String[] out = new String[names.length];
4188        // reader
4189        synchronized (mPackages) {
4190            final int callingUserId = UserHandle.getUserId(callingUid);
4191            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4192            for (int i=names.length-1; i>=0; i--) {
4193                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4194                boolean translateName = false;
4195                if (cur != null) {
4196                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4197                    final boolean targetIsInstantApp =
4198                            ps != null && ps.getInstantApp(callingUserId);
4199                    translateName = !targetIsInstantApp
4200                            || canViewInstantApps
4201                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4202                                    UserHandle.getAppId(callingUid), ps.appId);
4203                }
4204                out[i] = translateName ? cur : names[i];
4205            }
4206        }
4207        return out;
4208    }
4209
4210    @Override
4211    public int getPackageUid(String packageName, int flags, int userId) {
4212        if (!sUserManager.exists(userId)) return -1;
4213        final int callingUid = Binder.getCallingUid();
4214        flags = updateFlagsForPackage(flags, userId, packageName);
4215        enforceCrossUserPermission(callingUid, userId,
4216                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4217
4218        // reader
4219        synchronized (mPackages) {
4220            final PackageParser.Package p = mPackages.get(packageName);
4221            if (p != null && p.isMatch(flags)) {
4222                PackageSetting ps = (PackageSetting) p.mExtras;
4223                if (filterAppAccessLPr(ps, callingUid, userId)) {
4224                    return -1;
4225                }
4226                return UserHandle.getUid(userId, p.applicationInfo.uid);
4227            }
4228            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4229                final PackageSetting ps = mSettings.mPackages.get(packageName);
4230                if (ps != null && ps.isMatch(flags)
4231                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4232                    return UserHandle.getUid(userId, ps.appId);
4233                }
4234            }
4235        }
4236
4237        return -1;
4238    }
4239
4240    @Override
4241    public int[] getPackageGids(String packageName, int flags, int userId) {
4242        if (!sUserManager.exists(userId)) return null;
4243        final int callingUid = Binder.getCallingUid();
4244        flags = updateFlagsForPackage(flags, userId, packageName);
4245        enforceCrossUserPermission(callingUid, userId,
4246                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4247
4248        // reader
4249        synchronized (mPackages) {
4250            final PackageParser.Package p = mPackages.get(packageName);
4251            if (p != null && p.isMatch(flags)) {
4252                PackageSetting ps = (PackageSetting) p.mExtras;
4253                if (filterAppAccessLPr(ps, callingUid, userId)) {
4254                    return null;
4255                }
4256                // TODO: Shouldn't this be checking for package installed state for userId and
4257                // return null?
4258                return ps.getPermissionsState().computeGids(userId);
4259            }
4260            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4261                final PackageSetting ps = mSettings.mPackages.get(packageName);
4262                if (ps != null && ps.isMatch(flags)
4263                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4264                    return ps.getPermissionsState().computeGids(userId);
4265                }
4266            }
4267        }
4268
4269        return null;
4270    }
4271
4272    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
4273        if (bp.perm != null) {
4274            return PackageParser.generatePermissionInfo(bp.perm, flags);
4275        }
4276        PermissionInfo pi = new PermissionInfo();
4277        pi.name = bp.name;
4278        pi.packageName = bp.sourcePackage;
4279        pi.nonLocalizedLabel = bp.name;
4280        pi.protectionLevel = bp.protectionLevel;
4281        return pi;
4282    }
4283
4284    @Override
4285    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4286        final int callingUid = Binder.getCallingUid();
4287        if (getInstantAppPackageName(callingUid) != null) {
4288            return null;
4289        }
4290        // reader
4291        synchronized (mPackages) {
4292            final BasePermission p = mSettings.mPermissions.get(name);
4293            if (p == null) {
4294                return null;
4295            }
4296            // If the caller is an app that targets pre 26 SDK drop protection flags.
4297            PermissionInfo permissionInfo = generatePermissionInfo(p, flags);
4298            if (permissionInfo != null) {
4299                final int protectionLevel = adjustPermissionProtectionFlagsLPr(
4300                        permissionInfo.protectionLevel, packageName, callingUid);
4301                if (permissionInfo.protectionLevel != protectionLevel) {
4302                    // If we return different protection level, don't use the cached info
4303                    if (p.perm != null && p.perm.info == permissionInfo) {
4304                        permissionInfo = new PermissionInfo(permissionInfo);
4305                    }
4306                    permissionInfo.protectionLevel = protectionLevel;
4307                }
4308            }
4309            return permissionInfo;
4310        }
4311    }
4312
4313    private int adjustPermissionProtectionFlagsLPr(int protectionLevel,
4314            String packageName, int uid) {
4315        // Signature permission flags area always reported
4316        final int protectionLevelMasked = protectionLevel
4317                & (PermissionInfo.PROTECTION_NORMAL
4318                | PermissionInfo.PROTECTION_DANGEROUS
4319                | PermissionInfo.PROTECTION_SIGNATURE);
4320        if (protectionLevelMasked == PermissionInfo.PROTECTION_SIGNATURE) {
4321            return protectionLevel;
4322        }
4323
4324        // System sees all flags.
4325        final int appId = UserHandle.getAppId(uid);
4326        if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID
4327                || appId == Process.SHELL_UID) {
4328            return protectionLevel;
4329        }
4330
4331        // Normalize package name to handle renamed packages and static libs
4332        packageName = resolveInternalPackageNameLPr(packageName,
4333                PackageManager.VERSION_CODE_HIGHEST);
4334
4335        // Apps that target O see flags for all protection levels.
4336        final PackageSetting ps = mSettings.mPackages.get(packageName);
4337        if (ps == null) {
4338            return protectionLevel;
4339        }
4340        if (ps.appId != appId) {
4341            return protectionLevel;
4342        }
4343
4344        final PackageParser.Package pkg = mPackages.get(packageName);
4345        if (pkg == null) {
4346            return protectionLevel;
4347        }
4348        if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
4349            return protectionLevelMasked;
4350        }
4351
4352        return protectionLevel;
4353    }
4354
4355    @Override
4356    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
4357            int flags) {
4358        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4359            return null;
4360        }
4361        // reader
4362        synchronized (mPackages) {
4363            if (group != null && !mPermissionGroups.containsKey(group)) {
4364                // This is thrown as NameNotFoundException
4365                return null;
4366            }
4367
4368            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4369            for (BasePermission p : mSettings.mPermissions.values()) {
4370                if (group == null) {
4371                    if (p.perm == null || p.perm.info.group == null) {
4372                        out.add(generatePermissionInfo(p, flags));
4373                    }
4374                } else {
4375                    if (p.perm != null && group.equals(p.perm.info.group)) {
4376                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
4377                    }
4378                }
4379            }
4380            return new ParceledListSlice<>(out);
4381        }
4382    }
4383
4384    @Override
4385    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4386        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4387            return null;
4388        }
4389        // reader
4390        synchronized (mPackages) {
4391            return PackageParser.generatePermissionGroupInfo(
4392                    mPermissionGroups.get(name), flags);
4393        }
4394    }
4395
4396    @Override
4397    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4398        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4399            return ParceledListSlice.emptyList();
4400        }
4401        // reader
4402        synchronized (mPackages) {
4403            final int N = mPermissionGroups.size();
4404            ArrayList<PermissionGroupInfo> out
4405                    = new ArrayList<PermissionGroupInfo>(N);
4406            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4407                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4408            }
4409            return new ParceledListSlice<>(out);
4410        }
4411    }
4412
4413    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4414            int filterCallingUid, int userId) {
4415        if (!sUserManager.exists(userId)) return null;
4416        PackageSetting ps = mSettings.mPackages.get(packageName);
4417        if (ps != null) {
4418            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4419                return null;
4420            }
4421            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4422                return null;
4423            }
4424            if (ps.pkg == null) {
4425                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4426                if (pInfo != null) {
4427                    return pInfo.applicationInfo;
4428                }
4429                return null;
4430            }
4431            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4432                    ps.readUserState(userId), userId);
4433            if (ai != null) {
4434                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4435            }
4436            return ai;
4437        }
4438        return null;
4439    }
4440
4441    @Override
4442    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4443        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4444    }
4445
4446    /**
4447     * Important: The provided filterCallingUid is used exclusively to filter out applications
4448     * that can be seen based on user state. It's typically the original caller uid prior
4449     * to clearing. Because it can only be provided by trusted code, it's value can be
4450     * trusted and will be used as-is; unlike userId which will be validated by this method.
4451     */
4452    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4453            int filterCallingUid, int userId) {
4454        if (!sUserManager.exists(userId)) return null;
4455        flags = updateFlagsForApplication(flags, userId, packageName);
4456        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4457                false /* requireFullPermission */, false /* checkShell */, "get application info");
4458
4459        // writer
4460        synchronized (mPackages) {
4461            // Normalize package name to handle renamed packages and static libs
4462            packageName = resolveInternalPackageNameLPr(packageName,
4463                    PackageManager.VERSION_CODE_HIGHEST);
4464
4465            PackageParser.Package p = mPackages.get(packageName);
4466            if (DEBUG_PACKAGE_INFO) Log.v(
4467                    TAG, "getApplicationInfo " + packageName
4468                    + ": " + p);
4469            if (p != null) {
4470                PackageSetting ps = mSettings.mPackages.get(packageName);
4471                if (ps == null) return null;
4472                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4473                    return null;
4474                }
4475                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4476                    return null;
4477                }
4478                // Note: isEnabledLP() does not apply here - always return info
4479                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4480                        p, flags, ps.readUserState(userId), userId);
4481                if (ai != null) {
4482                    ai.packageName = resolveExternalPackageNameLPr(p);
4483                }
4484                return ai;
4485            }
4486            if ("android".equals(packageName)||"system".equals(packageName)) {
4487                return mAndroidApplication;
4488            }
4489            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4490                // Already generates the external package name
4491                return generateApplicationInfoFromSettingsLPw(packageName,
4492                        flags, filterCallingUid, userId);
4493            }
4494        }
4495        return null;
4496    }
4497
4498    private String normalizePackageNameLPr(String packageName) {
4499        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4500        return normalizedPackageName != null ? normalizedPackageName : packageName;
4501    }
4502
4503    @Override
4504    public void deletePreloadsFileCache() {
4505        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4506            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4507        }
4508        File dir = Environment.getDataPreloadsFileCacheDirectory();
4509        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4510        FileUtils.deleteContents(dir);
4511    }
4512
4513    @Override
4514    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4515            final int storageFlags, final IPackageDataObserver observer) {
4516        mContext.enforceCallingOrSelfPermission(
4517                android.Manifest.permission.CLEAR_APP_CACHE, null);
4518        mHandler.post(() -> {
4519            boolean success = false;
4520            try {
4521                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4522                success = true;
4523            } catch (IOException e) {
4524                Slog.w(TAG, e);
4525            }
4526            if (observer != null) {
4527                try {
4528                    observer.onRemoveCompleted(null, success);
4529                } catch (RemoteException e) {
4530                    Slog.w(TAG, e);
4531                }
4532            }
4533        });
4534    }
4535
4536    @Override
4537    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4538            final int storageFlags, final IntentSender pi) {
4539        mContext.enforceCallingOrSelfPermission(
4540                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4541        mHandler.post(() -> {
4542            boolean success = false;
4543            try {
4544                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4545                success = true;
4546            } catch (IOException e) {
4547                Slog.w(TAG, e);
4548            }
4549            if (pi != null) {
4550                try {
4551                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4552                } catch (SendIntentException e) {
4553                    Slog.w(TAG, e);
4554                }
4555            }
4556        });
4557    }
4558
4559    /**
4560     * Blocking call to clear various types of cached data across the system
4561     * until the requested bytes are available.
4562     */
4563    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4564        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4565        final File file = storage.findPathForUuid(volumeUuid);
4566        if (file.getUsableSpace() >= bytes) return;
4567
4568        if (ENABLE_FREE_CACHE_V2) {
4569            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4570                    volumeUuid);
4571            final boolean aggressive = (storageFlags
4572                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4573            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4574
4575            // 1. Pre-flight to determine if we have any chance to succeed
4576            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4577            if (internalVolume && (aggressive || SystemProperties
4578                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4579                deletePreloadsFileCache();
4580                if (file.getUsableSpace() >= bytes) return;
4581            }
4582
4583            // 3. Consider parsed APK data (aggressive only)
4584            if (internalVolume && aggressive) {
4585                FileUtils.deleteContents(mCacheDir);
4586                if (file.getUsableSpace() >= bytes) return;
4587            }
4588
4589            // 4. Consider cached app data (above quotas)
4590            try {
4591                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4592                        Installer.FLAG_FREE_CACHE_V2);
4593            } catch (InstallerException ignored) {
4594            }
4595            if (file.getUsableSpace() >= bytes) return;
4596
4597            // 5. Consider shared libraries with refcount=0 and age>min cache period
4598            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4599                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4600                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4601                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4602                return;
4603            }
4604
4605            // 6. Consider dexopt output (aggressive only)
4606            // TODO: Implement
4607
4608            // 7. Consider installed instant apps unused longer than min cache period
4609            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4610                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4611                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4612                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4613                return;
4614            }
4615
4616            // 8. Consider cached app data (below quotas)
4617            try {
4618                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4619                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4620            } catch (InstallerException ignored) {
4621            }
4622            if (file.getUsableSpace() >= bytes) return;
4623
4624            // 9. Consider DropBox entries
4625            // TODO: Implement
4626
4627            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4628            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4629                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4630                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4631                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4632                return;
4633            }
4634        } else {
4635            try {
4636                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4637            } catch (InstallerException ignored) {
4638            }
4639            if (file.getUsableSpace() >= bytes) return;
4640        }
4641
4642        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4643    }
4644
4645    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4646            throws IOException {
4647        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4648        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4649
4650        List<VersionedPackage> packagesToDelete = null;
4651        final long now = System.currentTimeMillis();
4652
4653        synchronized (mPackages) {
4654            final int[] allUsers = sUserManager.getUserIds();
4655            final int libCount = mSharedLibraries.size();
4656            for (int i = 0; i < libCount; i++) {
4657                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4658                if (versionedLib == null) {
4659                    continue;
4660                }
4661                final int versionCount = versionedLib.size();
4662                for (int j = 0; j < versionCount; j++) {
4663                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4664                    // Skip packages that are not static shared libs.
4665                    if (!libInfo.isStatic()) {
4666                        break;
4667                    }
4668                    // Important: We skip static shared libs used for some user since
4669                    // in such a case we need to keep the APK on the device. The check for
4670                    // a lib being used for any user is performed by the uninstall call.
4671                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4672                    // Resolve the package name - we use synthetic package names internally
4673                    final String internalPackageName = resolveInternalPackageNameLPr(
4674                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4675                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4676                    // Skip unused static shared libs cached less than the min period
4677                    // to prevent pruning a lib needed by a subsequently installed package.
4678                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4679                        continue;
4680                    }
4681                    if (packagesToDelete == null) {
4682                        packagesToDelete = new ArrayList<>();
4683                    }
4684                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4685                            declaringPackage.getVersionCode()));
4686                }
4687            }
4688        }
4689
4690        if (packagesToDelete != null) {
4691            final int packageCount = packagesToDelete.size();
4692            for (int i = 0; i < packageCount; i++) {
4693                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4694                // Delete the package synchronously (will fail of the lib used for any user).
4695                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4696                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4697                                == PackageManager.DELETE_SUCCEEDED) {
4698                    if (volume.getUsableSpace() >= neededSpace) {
4699                        return true;
4700                    }
4701                }
4702            }
4703        }
4704
4705        return false;
4706    }
4707
4708    /**
4709     * Update given flags based on encryption status of current user.
4710     */
4711    private int updateFlags(int flags, int userId) {
4712        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4713                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4714            // Caller expressed an explicit opinion about what encryption
4715            // aware/unaware components they want to see, so fall through and
4716            // give them what they want
4717        } else {
4718            // Caller expressed no opinion, so match based on user state
4719            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4720                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4721            } else {
4722                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4723            }
4724        }
4725        return flags;
4726    }
4727
4728    private UserManagerInternal getUserManagerInternal() {
4729        if (mUserManagerInternal == null) {
4730            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4731        }
4732        return mUserManagerInternal;
4733    }
4734
4735    private DeviceIdleController.LocalService getDeviceIdleController() {
4736        if (mDeviceIdleController == null) {
4737            mDeviceIdleController =
4738                    LocalServices.getService(DeviceIdleController.LocalService.class);
4739        }
4740        return mDeviceIdleController;
4741    }
4742
4743    /**
4744     * Update given flags when being used to request {@link PackageInfo}.
4745     */
4746    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4747        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4748        boolean triaged = true;
4749        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4750                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4751            // Caller is asking for component details, so they'd better be
4752            // asking for specific encryption matching behavior, or be triaged
4753            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4754                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4755                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4756                triaged = false;
4757            }
4758        }
4759        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4760                | PackageManager.MATCH_SYSTEM_ONLY
4761                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4762            triaged = false;
4763        }
4764        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4765            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4766                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4767                    + Debug.getCallers(5));
4768        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4769                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4770            // If the caller wants all packages and has a restricted profile associated with it,
4771            // then match all users. This is to make sure that launchers that need to access work
4772            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4773            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4774            flags |= PackageManager.MATCH_ANY_USER;
4775        }
4776        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4777            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4778                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4779        }
4780        return updateFlags(flags, userId);
4781    }
4782
4783    /**
4784     * Update given flags when being used to request {@link ApplicationInfo}.
4785     */
4786    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4787        return updateFlagsForPackage(flags, userId, cookie);
4788    }
4789
4790    /**
4791     * Update given flags when being used to request {@link ComponentInfo}.
4792     */
4793    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4794        if (cookie instanceof Intent) {
4795            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4796                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4797            }
4798        }
4799
4800        boolean triaged = true;
4801        // Caller is asking for component details, so they'd better be
4802        // asking for specific encryption matching behavior, or be triaged
4803        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4804                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4805                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4806            triaged = false;
4807        }
4808        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4809            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4810                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4811        }
4812
4813        return updateFlags(flags, userId);
4814    }
4815
4816    /**
4817     * Update given intent when being used to request {@link ResolveInfo}.
4818     */
4819    private Intent updateIntentForResolve(Intent intent) {
4820        if (intent.getSelector() != null) {
4821            intent = intent.getSelector();
4822        }
4823        if (DEBUG_PREFERRED) {
4824            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4825        }
4826        return intent;
4827    }
4828
4829    /**
4830     * Update given flags when being used to request {@link ResolveInfo}.
4831     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4832     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4833     * flag set. However, this flag is only honoured in three circumstances:
4834     * <ul>
4835     * <li>when called from a system process</li>
4836     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4837     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4838     * action and a {@code android.intent.category.BROWSABLE} category</li>
4839     * </ul>
4840     */
4841    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4842        return updateFlagsForResolve(flags, userId, intent, callingUid,
4843                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4844    }
4845    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4846            boolean wantInstantApps) {
4847        return updateFlagsForResolve(flags, userId, intent, callingUid,
4848                wantInstantApps, false /*onlyExposedExplicitly*/);
4849    }
4850    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4851            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4852        // Safe mode means we shouldn't match any third-party components
4853        if (mSafeMode) {
4854            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4855        }
4856        if (getInstantAppPackageName(callingUid) != null) {
4857            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4858            if (onlyExposedExplicitly) {
4859                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4860            }
4861            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4862            flags |= PackageManager.MATCH_INSTANT;
4863        } else {
4864            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4865            final boolean allowMatchInstant =
4866                    (wantInstantApps
4867                            && Intent.ACTION_VIEW.equals(intent.getAction())
4868                            && hasWebURI(intent))
4869                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4870            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4871                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4872            if (!allowMatchInstant) {
4873                flags &= ~PackageManager.MATCH_INSTANT;
4874            }
4875        }
4876        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4877    }
4878
4879    @Override
4880    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4881        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4882    }
4883
4884    /**
4885     * Important: The provided filterCallingUid is used exclusively to filter out activities
4886     * that can be seen based on user state. It's typically the original caller uid prior
4887     * to clearing. Because it can only be provided by trusted code, it's value can be
4888     * trusted and will be used as-is; unlike userId which will be validated by this method.
4889     */
4890    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4891            int filterCallingUid, int userId) {
4892        if (!sUserManager.exists(userId)) return null;
4893        flags = updateFlagsForComponent(flags, userId, component);
4894        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4895                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4896        synchronized (mPackages) {
4897            PackageParser.Activity a = mActivities.mActivities.get(component);
4898
4899            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4900            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4901                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4902                if (ps == null) return null;
4903                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4904                    return null;
4905                }
4906                return PackageParser.generateActivityInfo(
4907                        a, flags, ps.readUserState(userId), userId);
4908            }
4909            if (mResolveComponentName.equals(component)) {
4910                return PackageParser.generateActivityInfo(
4911                        mResolveActivity, flags, new PackageUserState(), userId);
4912            }
4913        }
4914        return null;
4915    }
4916
4917    @Override
4918    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4919            String resolvedType) {
4920        synchronized (mPackages) {
4921            if (component.equals(mResolveComponentName)) {
4922                // The resolver supports EVERYTHING!
4923                return true;
4924            }
4925            final int callingUid = Binder.getCallingUid();
4926            final int callingUserId = UserHandle.getUserId(callingUid);
4927            PackageParser.Activity a = mActivities.mActivities.get(component);
4928            if (a == null) {
4929                return false;
4930            }
4931            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4932            if (ps == null) {
4933                return false;
4934            }
4935            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4936                return false;
4937            }
4938            for (int i=0; i<a.intents.size(); i++) {
4939                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4940                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4941                    return true;
4942                }
4943            }
4944            return false;
4945        }
4946    }
4947
4948    @Override
4949    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4950        if (!sUserManager.exists(userId)) return null;
4951        final int callingUid = Binder.getCallingUid();
4952        flags = updateFlagsForComponent(flags, userId, component);
4953        enforceCrossUserPermission(callingUid, userId,
4954                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4955        synchronized (mPackages) {
4956            PackageParser.Activity a = mReceivers.mActivities.get(component);
4957            if (DEBUG_PACKAGE_INFO) Log.v(
4958                TAG, "getReceiverInfo " + component + ": " + a);
4959            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4960                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4961                if (ps == null) return null;
4962                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4963                    return null;
4964                }
4965                return PackageParser.generateActivityInfo(
4966                        a, flags, ps.readUserState(userId), userId);
4967            }
4968        }
4969        return null;
4970    }
4971
4972    @Override
4973    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4974            int flags, int userId) {
4975        if (!sUserManager.exists(userId)) return null;
4976        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4977        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4978            return null;
4979        }
4980
4981        flags = updateFlagsForPackage(flags, userId, null);
4982
4983        final boolean canSeeStaticLibraries =
4984                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4985                        == PERMISSION_GRANTED
4986                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4987                        == PERMISSION_GRANTED
4988                || canRequestPackageInstallsInternal(packageName,
4989                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4990                        false  /* throwIfPermNotDeclared*/)
4991                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4992                        == PERMISSION_GRANTED;
4993
4994        synchronized (mPackages) {
4995            List<SharedLibraryInfo> result = null;
4996
4997            final int libCount = mSharedLibraries.size();
4998            for (int i = 0; i < libCount; i++) {
4999                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5000                if (versionedLib == null) {
5001                    continue;
5002                }
5003
5004                final int versionCount = versionedLib.size();
5005                for (int j = 0; j < versionCount; j++) {
5006                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
5007                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
5008                        break;
5009                    }
5010                    final long identity = Binder.clearCallingIdentity();
5011                    try {
5012                        PackageInfo packageInfo = getPackageInfoVersioned(
5013                                libInfo.getDeclaringPackage(), flags
5014                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
5015                        if (packageInfo == null) {
5016                            continue;
5017                        }
5018                    } finally {
5019                        Binder.restoreCallingIdentity(identity);
5020                    }
5021
5022                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
5023                            libInfo.getVersion(), libInfo.getType(),
5024                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
5025                            flags, userId));
5026
5027                    if (result == null) {
5028                        result = new ArrayList<>();
5029                    }
5030                    result.add(resLibInfo);
5031                }
5032            }
5033
5034            return result != null ? new ParceledListSlice<>(result) : null;
5035        }
5036    }
5037
5038    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
5039            SharedLibraryInfo libInfo, int flags, int userId) {
5040        List<VersionedPackage> versionedPackages = null;
5041        final int packageCount = mSettings.mPackages.size();
5042        for (int i = 0; i < packageCount; i++) {
5043            PackageSetting ps = mSettings.mPackages.valueAt(i);
5044
5045            if (ps == null) {
5046                continue;
5047            }
5048
5049            if (!ps.getUserState().get(userId).isAvailable(flags)) {
5050                continue;
5051            }
5052
5053            final String libName = libInfo.getName();
5054            if (libInfo.isStatic()) {
5055                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
5056                if (libIdx < 0) {
5057                    continue;
5058                }
5059                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
5060                    continue;
5061                }
5062                if (versionedPackages == null) {
5063                    versionedPackages = new ArrayList<>();
5064                }
5065                // If the dependent is a static shared lib, use the public package name
5066                String dependentPackageName = ps.name;
5067                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
5068                    dependentPackageName = ps.pkg.manifestPackageName;
5069                }
5070                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
5071            } else if (ps.pkg != null) {
5072                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5073                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5074                    if (versionedPackages == null) {
5075                        versionedPackages = new ArrayList<>();
5076                    }
5077                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5078                }
5079            }
5080        }
5081
5082        return versionedPackages;
5083    }
5084
5085    @Override
5086    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5087        if (!sUserManager.exists(userId)) return null;
5088        final int callingUid = Binder.getCallingUid();
5089        flags = updateFlagsForComponent(flags, userId, component);
5090        enforceCrossUserPermission(callingUid, userId,
5091                false /* requireFullPermission */, false /* checkShell */, "get service info");
5092        synchronized (mPackages) {
5093            PackageParser.Service s = mServices.mServices.get(component);
5094            if (DEBUG_PACKAGE_INFO) Log.v(
5095                TAG, "getServiceInfo " + component + ": " + s);
5096            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5097                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5098                if (ps == null) return null;
5099                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5100                    return null;
5101                }
5102                return PackageParser.generateServiceInfo(
5103                        s, flags, ps.readUserState(userId), userId);
5104            }
5105        }
5106        return null;
5107    }
5108
5109    @Override
5110    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5111        if (!sUserManager.exists(userId)) return null;
5112        final int callingUid = Binder.getCallingUid();
5113        flags = updateFlagsForComponent(flags, userId, component);
5114        enforceCrossUserPermission(callingUid, userId,
5115                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5116        synchronized (mPackages) {
5117            PackageParser.Provider p = mProviders.mProviders.get(component);
5118            if (DEBUG_PACKAGE_INFO) Log.v(
5119                TAG, "getProviderInfo " + component + ": " + p);
5120            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5121                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5122                if (ps == null) return null;
5123                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5124                    return null;
5125                }
5126                return PackageParser.generateProviderInfo(
5127                        p, flags, ps.readUserState(userId), userId);
5128            }
5129        }
5130        return null;
5131    }
5132
5133    @Override
5134    public String[] getSystemSharedLibraryNames() {
5135        // allow instant applications
5136        synchronized (mPackages) {
5137            Set<String> libs = null;
5138            final int libCount = mSharedLibraries.size();
5139            for (int i = 0; i < libCount; i++) {
5140                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5141                if (versionedLib == null) {
5142                    continue;
5143                }
5144                final int versionCount = versionedLib.size();
5145                for (int j = 0; j < versionCount; j++) {
5146                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5147                    if (!libEntry.info.isStatic()) {
5148                        if (libs == null) {
5149                            libs = new ArraySet<>();
5150                        }
5151                        libs.add(libEntry.info.getName());
5152                        break;
5153                    }
5154                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5155                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5156                            UserHandle.getUserId(Binder.getCallingUid()),
5157                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5158                        if (libs == null) {
5159                            libs = new ArraySet<>();
5160                        }
5161                        libs.add(libEntry.info.getName());
5162                        break;
5163                    }
5164                }
5165            }
5166
5167            if (libs != null) {
5168                String[] libsArray = new String[libs.size()];
5169                libs.toArray(libsArray);
5170                return libsArray;
5171            }
5172
5173            return null;
5174        }
5175    }
5176
5177    @Override
5178    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5179        // allow instant applications
5180        synchronized (mPackages) {
5181            return mServicesSystemSharedLibraryPackageName;
5182        }
5183    }
5184
5185    @Override
5186    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5187        // allow instant applications
5188        synchronized (mPackages) {
5189            return mSharedSystemSharedLibraryPackageName;
5190        }
5191    }
5192
5193    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5194        for (int i = userList.length - 1; i >= 0; --i) {
5195            final int userId = userList[i];
5196            // don't add instant app to the list of updates
5197            if (pkgSetting.getInstantApp(userId)) {
5198                continue;
5199            }
5200            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5201            if (changedPackages == null) {
5202                changedPackages = new SparseArray<>();
5203                mChangedPackages.put(userId, changedPackages);
5204            }
5205            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5206            if (sequenceNumbers == null) {
5207                sequenceNumbers = new HashMap<>();
5208                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5209            }
5210            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5211            if (sequenceNumber != null) {
5212                changedPackages.remove(sequenceNumber);
5213            }
5214            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5215            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5216        }
5217        mChangedPackagesSequenceNumber++;
5218    }
5219
5220    @Override
5221    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5222        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5223            return null;
5224        }
5225        synchronized (mPackages) {
5226            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5227                return null;
5228            }
5229            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5230            if (changedPackages == null) {
5231                return null;
5232            }
5233            final List<String> packageNames =
5234                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5235            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5236                final String packageName = changedPackages.get(i);
5237                if (packageName != null) {
5238                    packageNames.add(packageName);
5239                }
5240            }
5241            return packageNames.isEmpty()
5242                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5243        }
5244    }
5245
5246    @Override
5247    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5248        // allow instant applications
5249        ArrayList<FeatureInfo> res;
5250        synchronized (mAvailableFeatures) {
5251            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5252            res.addAll(mAvailableFeatures.values());
5253        }
5254        final FeatureInfo fi = new FeatureInfo();
5255        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5256                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5257        res.add(fi);
5258
5259        return new ParceledListSlice<>(res);
5260    }
5261
5262    @Override
5263    public boolean hasSystemFeature(String name, int version) {
5264        // allow instant applications
5265        synchronized (mAvailableFeatures) {
5266            final FeatureInfo feat = mAvailableFeatures.get(name);
5267            if (feat == null) {
5268                return false;
5269            } else {
5270                return feat.version >= version;
5271            }
5272        }
5273    }
5274
5275    @Override
5276    public int checkPermission(String permName, String pkgName, int userId) {
5277        if (!sUserManager.exists(userId)) {
5278            return PackageManager.PERMISSION_DENIED;
5279        }
5280        final int callingUid = Binder.getCallingUid();
5281
5282        synchronized (mPackages) {
5283            final PackageParser.Package p = mPackages.get(pkgName);
5284            if (p != null && p.mExtras != null) {
5285                final PackageSetting ps = (PackageSetting) p.mExtras;
5286                if (filterAppAccessLPr(ps, callingUid, userId)) {
5287                    return PackageManager.PERMISSION_DENIED;
5288                }
5289                final boolean instantApp = ps.getInstantApp(userId);
5290                final PermissionsState permissionsState = ps.getPermissionsState();
5291                if (permissionsState.hasPermission(permName, userId)) {
5292                    if (instantApp) {
5293                        BasePermission bp = mSettings.mPermissions.get(permName);
5294                        if (bp != null && bp.isInstant()) {
5295                            return PackageManager.PERMISSION_GRANTED;
5296                        }
5297                    } else {
5298                        return PackageManager.PERMISSION_GRANTED;
5299                    }
5300                }
5301                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5302                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5303                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5304                    return PackageManager.PERMISSION_GRANTED;
5305                }
5306            }
5307        }
5308
5309        return PackageManager.PERMISSION_DENIED;
5310    }
5311
5312    @Override
5313    public int checkUidPermission(String permName, int uid) {
5314        final int callingUid = Binder.getCallingUid();
5315        final int callingUserId = UserHandle.getUserId(callingUid);
5316        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5317        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
5318        final int userId = UserHandle.getUserId(uid);
5319        if (!sUserManager.exists(userId)) {
5320            return PackageManager.PERMISSION_DENIED;
5321        }
5322
5323        synchronized (mPackages) {
5324            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5325            if (obj != null) {
5326                if (obj instanceof SharedUserSetting) {
5327                    if (isCallerInstantApp) {
5328                        return PackageManager.PERMISSION_DENIED;
5329                    }
5330                } else if (obj instanceof PackageSetting) {
5331                    final PackageSetting ps = (PackageSetting) obj;
5332                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5333                        return PackageManager.PERMISSION_DENIED;
5334                    }
5335                }
5336                final SettingBase settingBase = (SettingBase) obj;
5337                final PermissionsState permissionsState = settingBase.getPermissionsState();
5338                if (permissionsState.hasPermission(permName, userId)) {
5339                    if (isUidInstantApp) {
5340                        BasePermission bp = mSettings.mPermissions.get(permName);
5341                        if (bp != null && bp.isInstant()) {
5342                            return PackageManager.PERMISSION_GRANTED;
5343                        }
5344                    } else {
5345                        return PackageManager.PERMISSION_GRANTED;
5346                    }
5347                }
5348                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5349                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5350                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5351                    return PackageManager.PERMISSION_GRANTED;
5352                }
5353            } else {
5354                ArraySet<String> perms = mSystemPermissions.get(uid);
5355                if (perms != null) {
5356                    if (perms.contains(permName)) {
5357                        return PackageManager.PERMISSION_GRANTED;
5358                    }
5359                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5360                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5361                        return PackageManager.PERMISSION_GRANTED;
5362                    }
5363                }
5364            }
5365        }
5366
5367        return PackageManager.PERMISSION_DENIED;
5368    }
5369
5370    @Override
5371    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5372        if (UserHandle.getCallingUserId() != userId) {
5373            mContext.enforceCallingPermission(
5374                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5375                    "isPermissionRevokedByPolicy for user " + userId);
5376        }
5377
5378        if (checkPermission(permission, packageName, userId)
5379                == PackageManager.PERMISSION_GRANTED) {
5380            return false;
5381        }
5382
5383        final int callingUid = Binder.getCallingUid();
5384        if (getInstantAppPackageName(callingUid) != null) {
5385            if (!isCallerSameApp(packageName, callingUid)) {
5386                return false;
5387            }
5388        } else {
5389            if (isInstantApp(packageName, userId)) {
5390                return false;
5391            }
5392        }
5393
5394        final long identity = Binder.clearCallingIdentity();
5395        try {
5396            final int flags = getPermissionFlags(permission, packageName, userId);
5397            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5398        } finally {
5399            Binder.restoreCallingIdentity(identity);
5400        }
5401    }
5402
5403    @Override
5404    public String getPermissionControllerPackageName() {
5405        synchronized (mPackages) {
5406            return mRequiredInstallerPackage;
5407        }
5408    }
5409
5410    /**
5411     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
5412     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
5413     * @param checkShell whether to prevent shell from access if there's a debugging restriction
5414     * @param message the message to log on security exception
5415     */
5416    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
5417            boolean checkShell, String message) {
5418        if (userId < 0) {
5419            throw new IllegalArgumentException("Invalid userId " + userId);
5420        }
5421        if (checkShell) {
5422            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
5423        }
5424        if (userId == UserHandle.getUserId(callingUid)) return;
5425        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5426            if (requireFullPermission) {
5427                mContext.enforceCallingOrSelfPermission(
5428                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5429            } else {
5430                try {
5431                    mContext.enforceCallingOrSelfPermission(
5432                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5433                } catch (SecurityException se) {
5434                    mContext.enforceCallingOrSelfPermission(
5435                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5436                }
5437            }
5438        }
5439    }
5440
5441    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5442        if (callingUid == Process.SHELL_UID) {
5443            if (userHandle >= 0
5444                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
5445                throw new SecurityException("Shell does not have permission to access user "
5446                        + userHandle);
5447            } else if (userHandle < 0) {
5448                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5449                        + Debug.getCallers(3));
5450            }
5451        }
5452    }
5453
5454    private BasePermission findPermissionTreeLP(String permName) {
5455        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
5456            if (permName.startsWith(bp.name) &&
5457                    permName.length() > bp.name.length() &&
5458                    permName.charAt(bp.name.length()) == '.') {
5459                return bp;
5460            }
5461        }
5462        return null;
5463    }
5464
5465    private BasePermission checkPermissionTreeLP(String permName) {
5466        if (permName != null) {
5467            BasePermission bp = findPermissionTreeLP(permName);
5468            if (bp != null) {
5469                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
5470                    return bp;
5471                }
5472                throw new SecurityException("Calling uid "
5473                        + Binder.getCallingUid()
5474                        + " is not allowed to add to permission tree "
5475                        + bp.name + " owned by uid " + bp.uid);
5476            }
5477        }
5478        throw new SecurityException("No permission tree found for " + permName);
5479    }
5480
5481    static boolean compareStrings(CharSequence s1, CharSequence s2) {
5482        if (s1 == null) {
5483            return s2 == null;
5484        }
5485        if (s2 == null) {
5486            return false;
5487        }
5488        if (s1.getClass() != s2.getClass()) {
5489            return false;
5490        }
5491        return s1.equals(s2);
5492    }
5493
5494    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5495        if (pi1.icon != pi2.icon) return false;
5496        if (pi1.logo != pi2.logo) return false;
5497        if (pi1.protectionLevel != pi2.protectionLevel) return false;
5498        if (!compareStrings(pi1.name, pi2.name)) return false;
5499        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5500        // We'll take care of setting this one.
5501        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5502        // These are not currently stored in settings.
5503        //if (!compareStrings(pi1.group, pi2.group)) return false;
5504        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5505        //if (pi1.labelRes != pi2.labelRes) return false;
5506        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5507        return true;
5508    }
5509
5510    int permissionInfoFootprint(PermissionInfo info) {
5511        int size = info.name.length();
5512        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5513        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5514        return size;
5515    }
5516
5517    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5518        int size = 0;
5519        for (BasePermission perm : mSettings.mPermissions.values()) {
5520            if (perm.uid == tree.uid) {
5521                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5522            }
5523        }
5524        return size;
5525    }
5526
5527    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5528        // We calculate the max size of permissions defined by this uid and throw
5529        // if that plus the size of 'info' would exceed our stated maximum.
5530        if (tree.uid != Process.SYSTEM_UID) {
5531            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5532            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5533                throw new SecurityException("Permission tree size cap exceeded");
5534            }
5535        }
5536    }
5537
5538    boolean addPermissionLocked(PermissionInfo info, boolean async) {
5539        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5540            throw new SecurityException("Instant apps can't add permissions");
5541        }
5542        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5543            throw new SecurityException("Label must be specified in permission");
5544        }
5545        BasePermission tree = checkPermissionTreeLP(info.name);
5546        BasePermission bp = mSettings.mPermissions.get(info.name);
5547        boolean added = bp == null;
5548        boolean changed = true;
5549        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5550        if (added) {
5551            enforcePermissionCapLocked(info, tree);
5552            bp = new BasePermission(info.name, tree.sourcePackage,
5553                    BasePermission.TYPE_DYNAMIC);
5554        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5555            throw new SecurityException(
5556                    "Not allowed to modify non-dynamic permission "
5557                    + info.name);
5558        } else {
5559            if (bp.protectionLevel == fixedLevel
5560                    && bp.perm.owner.equals(tree.perm.owner)
5561                    && bp.uid == tree.uid
5562                    && comparePermissionInfos(bp.perm.info, info)) {
5563                changed = false;
5564            }
5565        }
5566        bp.protectionLevel = fixedLevel;
5567        info = new PermissionInfo(info);
5568        info.protectionLevel = fixedLevel;
5569        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5570        bp.perm.info.packageName = tree.perm.info.packageName;
5571        bp.uid = tree.uid;
5572        if (added) {
5573            mSettings.mPermissions.put(info.name, bp);
5574        }
5575        if (changed) {
5576            if (!async) {
5577                mSettings.writeLPr();
5578            } else {
5579                scheduleWriteSettingsLocked();
5580            }
5581        }
5582        return added;
5583    }
5584
5585    @Override
5586    public boolean addPermission(PermissionInfo info) {
5587        synchronized (mPackages) {
5588            return addPermissionLocked(info, false);
5589        }
5590    }
5591
5592    @Override
5593    public boolean addPermissionAsync(PermissionInfo info) {
5594        synchronized (mPackages) {
5595            return addPermissionLocked(info, true);
5596        }
5597    }
5598
5599    @Override
5600    public void removePermission(String name) {
5601        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5602            throw new SecurityException("Instant applications don't have access to this method");
5603        }
5604        synchronized (mPackages) {
5605            checkPermissionTreeLP(name);
5606            BasePermission bp = mSettings.mPermissions.get(name);
5607            if (bp != null) {
5608                if (bp.type != BasePermission.TYPE_DYNAMIC) {
5609                    throw new SecurityException(
5610                            "Not allowed to modify non-dynamic permission "
5611                            + name);
5612                }
5613                mSettings.mPermissions.remove(name);
5614                mSettings.writeLPr();
5615            }
5616        }
5617    }
5618
5619    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5620            PackageParser.Package pkg, BasePermission bp) {
5621        int index = pkg.requestedPermissions.indexOf(bp.name);
5622        if (index == -1) {
5623            throw new SecurityException("Package " + pkg.packageName
5624                    + " has not requested permission " + bp.name);
5625        }
5626        if (!bp.isRuntime() && !bp.isDevelopment()) {
5627            throw new SecurityException("Permission " + bp.name
5628                    + " is not a changeable permission type");
5629        }
5630    }
5631
5632    @Override
5633    public void grantRuntimePermission(String packageName, String name, final int userId) {
5634        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5635    }
5636
5637    private void grantRuntimePermission(String packageName, String name, final int userId,
5638            boolean overridePolicy) {
5639        if (!sUserManager.exists(userId)) {
5640            Log.e(TAG, "No such user:" + userId);
5641            return;
5642        }
5643        final int callingUid = Binder.getCallingUid();
5644
5645        mContext.enforceCallingOrSelfPermission(
5646                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5647                "grantRuntimePermission");
5648
5649        enforceCrossUserPermission(callingUid, userId,
5650                true /* requireFullPermission */, true /* checkShell */,
5651                "grantRuntimePermission");
5652
5653        final int uid;
5654        final PackageSetting ps;
5655
5656        synchronized (mPackages) {
5657            final PackageParser.Package pkg = mPackages.get(packageName);
5658            if (pkg == null) {
5659                throw new IllegalArgumentException("Unknown package: " + packageName);
5660            }
5661            final BasePermission bp = mSettings.mPermissions.get(name);
5662            if (bp == null) {
5663                throw new IllegalArgumentException("Unknown permission: " + name);
5664            }
5665            ps = (PackageSetting) pkg.mExtras;
5666            if (ps == null
5667                    || filterAppAccessLPr(ps, callingUid, userId)) {
5668                throw new IllegalArgumentException("Unknown package: " + packageName);
5669            }
5670
5671            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5672
5673            // If a permission review is required for legacy apps we represent
5674            // their permissions as always granted runtime ones since we need
5675            // to keep the review required permission flag per user while an
5676            // install permission's state is shared across all users.
5677            if (mPermissionReviewRequired
5678                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5679                    && bp.isRuntime()) {
5680                return;
5681            }
5682
5683            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5684
5685            final PermissionsState permissionsState = ps.getPermissionsState();
5686
5687            final int flags = permissionsState.getPermissionFlags(name, userId);
5688            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5689                throw new SecurityException("Cannot grant system fixed permission "
5690                        + name + " for package " + packageName);
5691            }
5692            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5693                throw new SecurityException("Cannot grant policy fixed permission "
5694                        + name + " for package " + packageName);
5695            }
5696
5697            if (bp.isDevelopment()) {
5698                // Development permissions must be handled specially, since they are not
5699                // normal runtime permissions.  For now they apply to all users.
5700                if (permissionsState.grantInstallPermission(bp) !=
5701                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5702                    scheduleWriteSettingsLocked();
5703                }
5704                return;
5705            }
5706
5707            if (ps.getInstantApp(userId) && !bp.isInstant()) {
5708                throw new SecurityException("Cannot grant non-ephemeral permission"
5709                        + name + " for package " + packageName);
5710            }
5711
5712            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5713                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5714                return;
5715            }
5716
5717            final int result = permissionsState.grantRuntimePermission(bp, userId);
5718            switch (result) {
5719                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5720                    return;
5721                }
5722
5723                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5724                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5725                    mHandler.post(new Runnable() {
5726                        @Override
5727                        public void run() {
5728                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5729                        }
5730                    });
5731                }
5732                break;
5733            }
5734
5735            if (bp.isRuntime()) {
5736                logPermissionGranted(mContext, name, packageName);
5737            }
5738
5739            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5740
5741            // Not critical if that is lost - app has to request again.
5742            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5743        }
5744
5745        // Only need to do this if user is initialized. Otherwise it's a new user
5746        // and there are no processes running as the user yet and there's no need
5747        // to make an expensive call to remount processes for the changed permissions.
5748        if (READ_EXTERNAL_STORAGE.equals(name)
5749                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5750            final long token = Binder.clearCallingIdentity();
5751            try {
5752                if (sUserManager.isInitialized(userId)) {
5753                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5754                            StorageManagerInternal.class);
5755                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5756                }
5757            } finally {
5758                Binder.restoreCallingIdentity(token);
5759            }
5760        }
5761    }
5762
5763    @Override
5764    public void revokeRuntimePermission(String packageName, String name, int userId) {
5765        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5766    }
5767
5768    private void revokeRuntimePermission(String packageName, String name, int userId,
5769            boolean overridePolicy) {
5770        if (!sUserManager.exists(userId)) {
5771            Log.e(TAG, "No such user:" + userId);
5772            return;
5773        }
5774
5775        mContext.enforceCallingOrSelfPermission(
5776                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5777                "revokeRuntimePermission");
5778
5779        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5780                true /* requireFullPermission */, true /* checkShell */,
5781                "revokeRuntimePermission");
5782
5783        final int appId;
5784
5785        synchronized (mPackages) {
5786            final PackageParser.Package pkg = mPackages.get(packageName);
5787            if (pkg == null) {
5788                throw new IllegalArgumentException("Unknown package: " + packageName);
5789            }
5790            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5791            if (ps == null
5792                    || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
5793                throw new IllegalArgumentException("Unknown package: " + packageName);
5794            }
5795            final BasePermission bp = mSettings.mPermissions.get(name);
5796            if (bp == null) {
5797                throw new IllegalArgumentException("Unknown permission: " + name);
5798            }
5799
5800            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5801
5802            // If a permission review is required for legacy apps we represent
5803            // their permissions as always granted runtime ones since we need
5804            // to keep the review required permission flag per user while an
5805            // install permission's state is shared across all users.
5806            if (mPermissionReviewRequired
5807                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5808                    && bp.isRuntime()) {
5809                return;
5810            }
5811
5812            final PermissionsState permissionsState = ps.getPermissionsState();
5813
5814            final int flags = permissionsState.getPermissionFlags(name, userId);
5815            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5816                throw new SecurityException("Cannot revoke system fixed permission "
5817                        + name + " for package " + packageName);
5818            }
5819            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5820                throw new SecurityException("Cannot revoke policy fixed permission "
5821                        + name + " for package " + packageName);
5822            }
5823
5824            if (bp.isDevelopment()) {
5825                // Development permissions must be handled specially, since they are not
5826                // normal runtime permissions.  For now they apply to all users.
5827                if (permissionsState.revokeInstallPermission(bp) !=
5828                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5829                    scheduleWriteSettingsLocked();
5830                }
5831                return;
5832            }
5833
5834            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5835                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5836                return;
5837            }
5838
5839            if (bp.isRuntime()) {
5840                logPermissionRevoked(mContext, name, packageName);
5841            }
5842
5843            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5844
5845            // Critical, after this call app should never have the permission.
5846            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5847
5848            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5849        }
5850
5851        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5852    }
5853
5854    /**
5855     * Get the first event id for the permission.
5856     *
5857     * <p>There are four events for each permission: <ul>
5858     *     <li>Request permission: first id + 0</li>
5859     *     <li>Grant permission: first id + 1</li>
5860     *     <li>Request for permission denied: first id + 2</li>
5861     *     <li>Revoke permission: first id + 3</li>
5862     * </ul></p>
5863     *
5864     * @param name name of the permission
5865     *
5866     * @return The first event id for the permission
5867     */
5868    private static int getBaseEventId(@NonNull String name) {
5869        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5870
5871        if (eventIdIndex == -1) {
5872            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5873                    || Build.IS_USER) {
5874                Log.i(TAG, "Unknown permission " + name);
5875
5876                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5877            } else {
5878                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5879                //
5880                // Also update
5881                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5882                // - metrics_constants.proto
5883                throw new IllegalStateException("Unknown permission " + name);
5884            }
5885        }
5886
5887        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5888    }
5889
5890    /**
5891     * Log that a permission was revoked.
5892     *
5893     * @param context Context of the caller
5894     * @param name name of the permission
5895     * @param packageName package permission if for
5896     */
5897    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5898            @NonNull String packageName) {
5899        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5900    }
5901
5902    /**
5903     * Log that a permission request was granted.
5904     *
5905     * @param context Context of the caller
5906     * @param name name of the permission
5907     * @param packageName package permission if for
5908     */
5909    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5910            @NonNull String packageName) {
5911        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5912    }
5913
5914    @Override
5915    public void resetRuntimePermissions() {
5916        mContext.enforceCallingOrSelfPermission(
5917                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5918                "revokeRuntimePermission");
5919
5920        int callingUid = Binder.getCallingUid();
5921        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5922            mContext.enforceCallingOrSelfPermission(
5923                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5924                    "resetRuntimePermissions");
5925        }
5926
5927        synchronized (mPackages) {
5928            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5929            for (int userId : UserManagerService.getInstance().getUserIds()) {
5930                final int packageCount = mPackages.size();
5931                for (int i = 0; i < packageCount; i++) {
5932                    PackageParser.Package pkg = mPackages.valueAt(i);
5933                    if (!(pkg.mExtras instanceof PackageSetting)) {
5934                        continue;
5935                    }
5936                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5937                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5938                }
5939            }
5940        }
5941    }
5942
5943    @Override
5944    public int getPermissionFlags(String name, String packageName, int userId) {
5945        if (!sUserManager.exists(userId)) {
5946            return 0;
5947        }
5948
5949        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5950
5951        final int callingUid = Binder.getCallingUid();
5952        enforceCrossUserPermission(callingUid, userId,
5953                true /* requireFullPermission */, false /* checkShell */,
5954                "getPermissionFlags");
5955
5956        synchronized (mPackages) {
5957            final PackageParser.Package pkg = mPackages.get(packageName);
5958            if (pkg == null) {
5959                return 0;
5960            }
5961            final BasePermission bp = mSettings.mPermissions.get(name);
5962            if (bp == null) {
5963                return 0;
5964            }
5965            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5966            if (ps == null
5967                    || filterAppAccessLPr(ps, callingUid, userId)) {
5968                return 0;
5969            }
5970            PermissionsState permissionsState = ps.getPermissionsState();
5971            return permissionsState.getPermissionFlags(name, userId);
5972        }
5973    }
5974
5975    @Override
5976    public void updatePermissionFlags(String name, String packageName, int flagMask,
5977            int flagValues, int userId) {
5978        if (!sUserManager.exists(userId)) {
5979            return;
5980        }
5981
5982        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5983
5984        final int callingUid = Binder.getCallingUid();
5985        enforceCrossUserPermission(callingUid, userId,
5986                true /* requireFullPermission */, true /* checkShell */,
5987                "updatePermissionFlags");
5988
5989        // Only the system can change these flags and nothing else.
5990        if (getCallingUid() != Process.SYSTEM_UID) {
5991            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5992            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5993            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5994            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5995            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5996        }
5997
5998        synchronized (mPackages) {
5999            final PackageParser.Package pkg = mPackages.get(packageName);
6000            if (pkg == null) {
6001                throw new IllegalArgumentException("Unknown package: " + packageName);
6002            }
6003            final PackageSetting ps = (PackageSetting) pkg.mExtras;
6004            if (ps == null
6005                    || filterAppAccessLPr(ps, callingUid, userId)) {
6006                throw new IllegalArgumentException("Unknown package: " + packageName);
6007            }
6008
6009            final BasePermission bp = mSettings.mPermissions.get(name);
6010            if (bp == null) {
6011                throw new IllegalArgumentException("Unknown permission: " + name);
6012            }
6013
6014            PermissionsState permissionsState = ps.getPermissionsState();
6015
6016            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
6017
6018            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
6019                // Install and runtime permissions are stored in different places,
6020                // so figure out what permission changed and persist the change.
6021                if (permissionsState.getInstallPermissionState(name) != null) {
6022                    scheduleWriteSettingsLocked();
6023                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
6024                        || hadState) {
6025                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
6026                }
6027            }
6028        }
6029    }
6030
6031    /**
6032     * Update the permission flags for all packages and runtime permissions of a user in order
6033     * to allow device or profile owner to remove POLICY_FIXED.
6034     */
6035    @Override
6036    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
6037        if (!sUserManager.exists(userId)) {
6038            return;
6039        }
6040
6041        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
6042
6043        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6044                true /* requireFullPermission */, true /* checkShell */,
6045                "updatePermissionFlagsForAllApps");
6046
6047        // Only the system can change system fixed flags.
6048        if (getCallingUid() != Process.SYSTEM_UID) {
6049            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
6050            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
6051        }
6052
6053        synchronized (mPackages) {
6054            boolean changed = false;
6055            final int packageCount = mPackages.size();
6056            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
6057                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
6058                final PackageSetting ps = (PackageSetting) pkg.mExtras;
6059                if (ps == null) {
6060                    continue;
6061                }
6062                PermissionsState permissionsState = ps.getPermissionsState();
6063                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
6064                        userId, flagMask, flagValues);
6065            }
6066            if (changed) {
6067                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
6068            }
6069        }
6070    }
6071
6072    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
6073        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
6074                != PackageManager.PERMISSION_GRANTED
6075            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
6076                != PackageManager.PERMISSION_GRANTED) {
6077            throw new SecurityException(message + " requires "
6078                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
6079                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
6080        }
6081    }
6082
6083    @Override
6084    public boolean shouldShowRequestPermissionRationale(String permissionName,
6085            String packageName, int userId) {
6086        if (UserHandle.getCallingUserId() != userId) {
6087            mContext.enforceCallingPermission(
6088                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
6089                    "canShowRequestPermissionRationale for user " + userId);
6090        }
6091
6092        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
6093        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
6094            return false;
6095        }
6096
6097        if (checkPermission(permissionName, packageName, userId)
6098                == PackageManager.PERMISSION_GRANTED) {
6099            return false;
6100        }
6101
6102        final int flags;
6103
6104        final long identity = Binder.clearCallingIdentity();
6105        try {
6106            flags = getPermissionFlags(permissionName,
6107                    packageName, userId);
6108        } finally {
6109            Binder.restoreCallingIdentity(identity);
6110        }
6111
6112        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
6113                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
6114                | PackageManager.FLAG_PERMISSION_USER_FIXED;
6115
6116        if ((flags & fixedFlags) != 0) {
6117            return false;
6118        }
6119
6120        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
6121    }
6122
6123    @Override
6124    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6125        mContext.enforceCallingOrSelfPermission(
6126                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
6127                "addOnPermissionsChangeListener");
6128
6129        synchronized (mPackages) {
6130            mOnPermissionChangeListeners.addListenerLocked(listener);
6131        }
6132    }
6133
6134    @Override
6135    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6136        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6137            throw new SecurityException("Instant applications don't have access to this method");
6138        }
6139        synchronized (mPackages) {
6140            mOnPermissionChangeListeners.removeListenerLocked(listener);
6141        }
6142    }
6143
6144    @Override
6145    public boolean isProtectedBroadcast(String actionName) {
6146        // allow instant applications
6147        synchronized (mProtectedBroadcasts) {
6148            if (mProtectedBroadcasts.contains(actionName)) {
6149                return true;
6150            } else if (actionName != null) {
6151                // TODO: remove these terrible hacks
6152                if (actionName.startsWith("android.net.netmon.lingerExpired")
6153                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
6154                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
6155                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
6156                    return true;
6157                }
6158            }
6159        }
6160        return false;
6161    }
6162
6163    @Override
6164    public int checkSignatures(String pkg1, String pkg2) {
6165        synchronized (mPackages) {
6166            final PackageParser.Package p1 = mPackages.get(pkg1);
6167            final PackageParser.Package p2 = mPackages.get(pkg2);
6168            if (p1 == null || p1.mExtras == null
6169                    || p2 == null || p2.mExtras == null) {
6170                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6171            }
6172            final int callingUid = Binder.getCallingUid();
6173            final int callingUserId = UserHandle.getUserId(callingUid);
6174            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
6175            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
6176            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
6177                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
6178                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6179            }
6180            return compareSignatures(p1.mSignatures, p2.mSignatures);
6181        }
6182    }
6183
6184    @Override
6185    public int checkUidSignatures(int uid1, int uid2) {
6186        final int callingUid = Binder.getCallingUid();
6187        final int callingUserId = UserHandle.getUserId(callingUid);
6188        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6189        // Map to base uids.
6190        uid1 = UserHandle.getAppId(uid1);
6191        uid2 = UserHandle.getAppId(uid2);
6192        // reader
6193        synchronized (mPackages) {
6194            Signature[] s1;
6195            Signature[] s2;
6196            Object obj = mSettings.getUserIdLPr(uid1);
6197            if (obj != null) {
6198                if (obj instanceof SharedUserSetting) {
6199                    if (isCallerInstantApp) {
6200                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6201                    }
6202                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
6203                } else if (obj instanceof PackageSetting) {
6204                    final PackageSetting ps = (PackageSetting) obj;
6205                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6206                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6207                    }
6208                    s1 = ps.signatures.mSignatures;
6209                } else {
6210                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6211                }
6212            } else {
6213                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6214            }
6215            obj = mSettings.getUserIdLPr(uid2);
6216            if (obj != null) {
6217                if (obj instanceof SharedUserSetting) {
6218                    if (isCallerInstantApp) {
6219                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6220                    }
6221                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
6222                } else if (obj instanceof PackageSetting) {
6223                    final PackageSetting ps = (PackageSetting) obj;
6224                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6225                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6226                    }
6227                    s2 = ps.signatures.mSignatures;
6228                } else {
6229                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6230                }
6231            } else {
6232                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6233            }
6234            return compareSignatures(s1, s2);
6235        }
6236    }
6237
6238    /**
6239     * This method should typically only be used when granting or revoking
6240     * permissions, since the app may immediately restart after this call.
6241     * <p>
6242     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
6243     * guard your work against the app being relaunched.
6244     */
6245    private void killUid(int appId, int userId, String reason) {
6246        final long identity = Binder.clearCallingIdentity();
6247        try {
6248            IActivityManager am = ActivityManager.getService();
6249            if (am != null) {
6250                try {
6251                    am.killUid(appId, userId, reason);
6252                } catch (RemoteException e) {
6253                    /* ignore - same process */
6254                }
6255            }
6256        } finally {
6257            Binder.restoreCallingIdentity(identity);
6258        }
6259    }
6260
6261    /**
6262     * Compares two sets of signatures. Returns:
6263     * <br />
6264     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
6265     * <br />
6266     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
6267     * <br />
6268     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
6269     * <br />
6270     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
6271     * <br />
6272     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
6273     */
6274    static int compareSignatures(Signature[] s1, Signature[] s2) {
6275        if (s1 == null) {
6276            return s2 == null
6277                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
6278                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
6279        }
6280
6281        if (s2 == null) {
6282            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
6283        }
6284
6285        if (s1.length != s2.length) {
6286            return PackageManager.SIGNATURE_NO_MATCH;
6287        }
6288
6289        // Since both signature sets are of size 1, we can compare without HashSets.
6290        if (s1.length == 1) {
6291            return s1[0].equals(s2[0]) ?
6292                    PackageManager.SIGNATURE_MATCH :
6293                    PackageManager.SIGNATURE_NO_MATCH;
6294        }
6295
6296        ArraySet<Signature> set1 = new ArraySet<Signature>();
6297        for (Signature sig : s1) {
6298            set1.add(sig);
6299        }
6300        ArraySet<Signature> set2 = new ArraySet<Signature>();
6301        for (Signature sig : s2) {
6302            set2.add(sig);
6303        }
6304        // Make sure s2 contains all signatures in s1.
6305        if (set1.equals(set2)) {
6306            return PackageManager.SIGNATURE_MATCH;
6307        }
6308        return PackageManager.SIGNATURE_NO_MATCH;
6309    }
6310
6311    /**
6312     * If the database version for this type of package (internal storage or
6313     * external storage) is less than the version where package signatures
6314     * were updated, return true.
6315     */
6316    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6317        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6318        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
6319    }
6320
6321    /**
6322     * Used for backward compatibility to make sure any packages with
6323     * certificate chains get upgraded to the new style. {@code existingSigs}
6324     * will be in the old format (since they were stored on disk from before the
6325     * system upgrade) and {@code scannedSigs} will be in the newer format.
6326     */
6327    private int compareSignaturesCompat(PackageSignatures existingSigs,
6328            PackageParser.Package scannedPkg) {
6329        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
6330            return PackageManager.SIGNATURE_NO_MATCH;
6331        }
6332
6333        ArraySet<Signature> existingSet = new ArraySet<Signature>();
6334        for (Signature sig : existingSigs.mSignatures) {
6335            existingSet.add(sig);
6336        }
6337        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
6338        for (Signature sig : scannedPkg.mSignatures) {
6339            try {
6340                Signature[] chainSignatures = sig.getChainSignatures();
6341                for (Signature chainSig : chainSignatures) {
6342                    scannedCompatSet.add(chainSig);
6343                }
6344            } catch (CertificateEncodingException e) {
6345                scannedCompatSet.add(sig);
6346            }
6347        }
6348        /*
6349         * Make sure the expanded scanned set contains all signatures in the
6350         * existing one.
6351         */
6352        if (scannedCompatSet.equals(existingSet)) {
6353            // Migrate the old signatures to the new scheme.
6354            existingSigs.assignSignatures(scannedPkg.mSignatures);
6355            // The new KeySets will be re-added later in the scanning process.
6356            synchronized (mPackages) {
6357                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
6358            }
6359            return PackageManager.SIGNATURE_MATCH;
6360        }
6361        return PackageManager.SIGNATURE_NO_MATCH;
6362    }
6363
6364    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6365        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6366        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6367    }
6368
6369    private int compareSignaturesRecover(PackageSignatures existingSigs,
6370            PackageParser.Package scannedPkg) {
6371        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
6372            return PackageManager.SIGNATURE_NO_MATCH;
6373        }
6374
6375        String msg = null;
6376        try {
6377            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
6378                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
6379                        + scannedPkg.packageName);
6380                return PackageManager.SIGNATURE_MATCH;
6381            }
6382        } catch (CertificateException e) {
6383            msg = e.getMessage();
6384        }
6385
6386        logCriticalInfo(Log.INFO,
6387                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
6388        return PackageManager.SIGNATURE_NO_MATCH;
6389    }
6390
6391    @Override
6392    public List<String> getAllPackages() {
6393        final int callingUid = Binder.getCallingUid();
6394        final int callingUserId = UserHandle.getUserId(callingUid);
6395        synchronized (mPackages) {
6396            if (canViewInstantApps(callingUid, callingUserId)) {
6397                return new ArrayList<String>(mPackages.keySet());
6398            }
6399            final String instantAppPkgName = getInstantAppPackageName(callingUid);
6400            final List<String> result = new ArrayList<>();
6401            if (instantAppPkgName != null) {
6402                // caller is an instant application; filter unexposed applications
6403                for (PackageParser.Package pkg : mPackages.values()) {
6404                    if (!pkg.visibleToInstantApps) {
6405                        continue;
6406                    }
6407                    result.add(pkg.packageName);
6408                }
6409            } else {
6410                // caller is a normal application; filter instant applications
6411                for (PackageParser.Package pkg : mPackages.values()) {
6412                    final PackageSetting ps =
6413                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6414                    if (ps != null
6415                            && ps.getInstantApp(callingUserId)
6416                            && !mInstantAppRegistry.isInstantAccessGranted(
6417                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6418                        continue;
6419                    }
6420                    result.add(pkg.packageName);
6421                }
6422            }
6423            return result;
6424        }
6425    }
6426
6427    @Override
6428    public String[] getPackagesForUid(int uid) {
6429        final int callingUid = Binder.getCallingUid();
6430        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6431        final int userId = UserHandle.getUserId(uid);
6432        uid = UserHandle.getAppId(uid);
6433        // reader
6434        synchronized (mPackages) {
6435            Object obj = mSettings.getUserIdLPr(uid);
6436            if (obj instanceof SharedUserSetting) {
6437                if (isCallerInstantApp) {
6438                    return null;
6439                }
6440                final SharedUserSetting sus = (SharedUserSetting) obj;
6441                final int N = sus.packages.size();
6442                String[] res = new String[N];
6443                final Iterator<PackageSetting> it = sus.packages.iterator();
6444                int i = 0;
6445                while (it.hasNext()) {
6446                    PackageSetting ps = it.next();
6447                    if (ps.getInstalled(userId)) {
6448                        res[i++] = ps.name;
6449                    } else {
6450                        res = ArrayUtils.removeElement(String.class, res, res[i]);
6451                    }
6452                }
6453                return res;
6454            } else if (obj instanceof PackageSetting) {
6455                final PackageSetting ps = (PackageSetting) obj;
6456                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6457                    return new String[]{ps.name};
6458                }
6459            }
6460        }
6461        return null;
6462    }
6463
6464    @Override
6465    public String getNameForUid(int uid) {
6466        final int callingUid = Binder.getCallingUid();
6467        if (getInstantAppPackageName(callingUid) != null) {
6468            return null;
6469        }
6470        synchronized (mPackages) {
6471            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6472            if (obj instanceof SharedUserSetting) {
6473                final SharedUserSetting sus = (SharedUserSetting) obj;
6474                return sus.name + ":" + sus.userId;
6475            } else if (obj instanceof PackageSetting) {
6476                final PackageSetting ps = (PackageSetting) obj;
6477                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6478                    return null;
6479                }
6480                return ps.name;
6481            }
6482            return null;
6483        }
6484    }
6485
6486    @Override
6487    public String[] getNamesForUids(int[] uids) {
6488        if (uids == null || uids.length == 0) {
6489            return null;
6490        }
6491        final int callingUid = Binder.getCallingUid();
6492        if (getInstantAppPackageName(callingUid) != null) {
6493            return null;
6494        }
6495        final String[] names = new String[uids.length];
6496        synchronized (mPackages) {
6497            for (int i = uids.length - 1; i >= 0; i--) {
6498                final int uid = uids[i];
6499                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6500                if (obj instanceof SharedUserSetting) {
6501                    final SharedUserSetting sus = (SharedUserSetting) obj;
6502                    names[i] = "shared:" + sus.name;
6503                } else if (obj instanceof PackageSetting) {
6504                    final PackageSetting ps = (PackageSetting) obj;
6505                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6506                        names[i] = null;
6507                    } else {
6508                        names[i] = ps.name;
6509                    }
6510                } else {
6511                    names[i] = null;
6512                }
6513            }
6514        }
6515        return names;
6516    }
6517
6518    @Override
6519    public int getUidForSharedUser(String sharedUserName) {
6520        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6521            return -1;
6522        }
6523        if (sharedUserName == null) {
6524            return -1;
6525        }
6526        // reader
6527        synchronized (mPackages) {
6528            SharedUserSetting suid;
6529            try {
6530                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6531                if (suid != null) {
6532                    return suid.userId;
6533                }
6534            } catch (PackageManagerException ignore) {
6535                // can't happen, but, still need to catch it
6536            }
6537            return -1;
6538        }
6539    }
6540
6541    @Override
6542    public int getFlagsForUid(int uid) {
6543        final int callingUid = Binder.getCallingUid();
6544        if (getInstantAppPackageName(callingUid) != null) {
6545            return 0;
6546        }
6547        synchronized (mPackages) {
6548            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6549            if (obj instanceof SharedUserSetting) {
6550                final SharedUserSetting sus = (SharedUserSetting) obj;
6551                return sus.pkgFlags;
6552            } else if (obj instanceof PackageSetting) {
6553                final PackageSetting ps = (PackageSetting) obj;
6554                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6555                    return 0;
6556                }
6557                return ps.pkgFlags;
6558            }
6559        }
6560        return 0;
6561    }
6562
6563    @Override
6564    public int getPrivateFlagsForUid(int uid) {
6565        final int callingUid = Binder.getCallingUid();
6566        if (getInstantAppPackageName(callingUid) != null) {
6567            return 0;
6568        }
6569        synchronized (mPackages) {
6570            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6571            if (obj instanceof SharedUserSetting) {
6572                final SharedUserSetting sus = (SharedUserSetting) obj;
6573                return sus.pkgPrivateFlags;
6574            } else if (obj instanceof PackageSetting) {
6575                final PackageSetting ps = (PackageSetting) obj;
6576                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6577                    return 0;
6578                }
6579                return ps.pkgPrivateFlags;
6580            }
6581        }
6582        return 0;
6583    }
6584
6585    @Override
6586    public boolean isUidPrivileged(int uid) {
6587        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6588            return false;
6589        }
6590        uid = UserHandle.getAppId(uid);
6591        // reader
6592        synchronized (mPackages) {
6593            Object obj = mSettings.getUserIdLPr(uid);
6594            if (obj instanceof SharedUserSetting) {
6595                final SharedUserSetting sus = (SharedUserSetting) obj;
6596                final Iterator<PackageSetting> it = sus.packages.iterator();
6597                while (it.hasNext()) {
6598                    if (it.next().isPrivileged()) {
6599                        return true;
6600                    }
6601                }
6602            } else if (obj instanceof PackageSetting) {
6603                final PackageSetting ps = (PackageSetting) obj;
6604                return ps.isPrivileged();
6605            }
6606        }
6607        return false;
6608    }
6609
6610    @Override
6611    public String[] getAppOpPermissionPackages(String permissionName) {
6612        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6613            return null;
6614        }
6615        synchronized (mPackages) {
6616            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6617            if (pkgs == null) {
6618                return null;
6619            }
6620            return pkgs.toArray(new String[pkgs.size()]);
6621        }
6622    }
6623
6624    @Override
6625    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6626            int flags, int userId) {
6627        return resolveIntentInternal(
6628                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6629    }
6630
6631    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6632            int flags, int userId, boolean resolveForStart) {
6633        try {
6634            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6635
6636            if (!sUserManager.exists(userId)) return null;
6637            final int callingUid = Binder.getCallingUid();
6638            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6639            enforceCrossUserPermission(callingUid, userId,
6640                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6641
6642            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6643            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6644                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
6645            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6646
6647            final ResolveInfo bestChoice =
6648                    chooseBestActivity(intent, resolvedType, flags, query, userId);
6649            return bestChoice;
6650        } finally {
6651            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6652        }
6653    }
6654
6655    @Override
6656    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6657        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6658            throw new SecurityException(
6659                    "findPersistentPreferredActivity can only be run by the system");
6660        }
6661        if (!sUserManager.exists(userId)) {
6662            return null;
6663        }
6664        final int callingUid = Binder.getCallingUid();
6665        intent = updateIntentForResolve(intent);
6666        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6667        final int flags = updateFlagsForResolve(
6668                0, userId, intent, callingUid, false /*includeInstantApps*/);
6669        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6670                userId);
6671        synchronized (mPackages) {
6672            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6673                    userId);
6674        }
6675    }
6676
6677    @Override
6678    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6679            IntentFilter filter, int match, ComponentName activity) {
6680        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6681            return;
6682        }
6683        final int userId = UserHandle.getCallingUserId();
6684        if (DEBUG_PREFERRED) {
6685            Log.v(TAG, "setLastChosenActivity intent=" + intent
6686                + " resolvedType=" + resolvedType
6687                + " flags=" + flags
6688                + " filter=" + filter
6689                + " match=" + match
6690                + " activity=" + activity);
6691            filter.dump(new PrintStreamPrinter(System.out), "    ");
6692        }
6693        intent.setComponent(null);
6694        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6695                userId);
6696        // Find any earlier preferred or last chosen entries and nuke them
6697        findPreferredActivity(intent, resolvedType,
6698                flags, query, 0, false, true, false, userId);
6699        // Add the new activity as the last chosen for this filter
6700        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6701                "Setting last chosen");
6702    }
6703
6704    @Override
6705    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6706        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6707            return null;
6708        }
6709        final int userId = UserHandle.getCallingUserId();
6710        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6711        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6712                userId);
6713        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6714                false, false, false, userId);
6715    }
6716
6717    /**
6718     * Returns whether or not instant apps have been disabled remotely.
6719     */
6720    private boolean isEphemeralDisabled() {
6721        return mEphemeralAppsDisabled;
6722    }
6723
6724    private boolean isInstantAppAllowed(
6725            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6726            boolean skipPackageCheck) {
6727        if (mInstantAppResolverConnection == null) {
6728            return false;
6729        }
6730        if (mInstantAppInstallerActivity == null) {
6731            return false;
6732        }
6733        if (intent.getComponent() != null) {
6734            return false;
6735        }
6736        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6737            return false;
6738        }
6739        if (!skipPackageCheck && intent.getPackage() != null) {
6740            return false;
6741        }
6742        final boolean isWebUri = hasWebURI(intent);
6743        if (!isWebUri || intent.getData().getHost() == null) {
6744            return false;
6745        }
6746        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6747        // Or if there's already an ephemeral app installed that handles the action
6748        synchronized (mPackages) {
6749            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6750            for (int n = 0; n < count; n++) {
6751                final ResolveInfo info = resolvedActivities.get(n);
6752                final String packageName = info.activityInfo.packageName;
6753                final PackageSetting ps = mSettings.mPackages.get(packageName);
6754                if (ps != null) {
6755                    // only check domain verification status if the app is not a browser
6756                    if (!info.handleAllWebDataURI) {
6757                        // Try to get the status from User settings first
6758                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6759                        final int status = (int) (packedStatus >> 32);
6760                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6761                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6762                            if (DEBUG_EPHEMERAL) {
6763                                Slog.v(TAG, "DENY instant app;"
6764                                    + " pkg: " + packageName + ", status: " + status);
6765                            }
6766                            return false;
6767                        }
6768                    }
6769                    if (ps.getInstantApp(userId)) {
6770                        if (DEBUG_EPHEMERAL) {
6771                            Slog.v(TAG, "DENY instant app installed;"
6772                                    + " pkg: " + packageName);
6773                        }
6774                        return false;
6775                    }
6776                }
6777            }
6778        }
6779        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6780        return true;
6781    }
6782
6783    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6784            Intent origIntent, String resolvedType, String callingPackage,
6785            Bundle verificationBundle, int userId) {
6786        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6787                new InstantAppRequest(responseObj, origIntent, resolvedType,
6788                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
6789        mHandler.sendMessage(msg);
6790    }
6791
6792    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6793            int flags, List<ResolveInfo> query, int userId) {
6794        if (query != null) {
6795            final int N = query.size();
6796            if (N == 1) {
6797                return query.get(0);
6798            } else if (N > 1) {
6799                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6800                // If there is more than one activity with the same priority,
6801                // then let the user decide between them.
6802                ResolveInfo r0 = query.get(0);
6803                ResolveInfo r1 = query.get(1);
6804                if (DEBUG_INTENT_MATCHING || debug) {
6805                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6806                            + r1.activityInfo.name + "=" + r1.priority);
6807                }
6808                // If the first activity has a higher priority, or a different
6809                // default, then it is always desirable to pick it.
6810                if (r0.priority != r1.priority
6811                        || r0.preferredOrder != r1.preferredOrder
6812                        || r0.isDefault != r1.isDefault) {
6813                    return query.get(0);
6814                }
6815                // If we have saved a preference for a preferred activity for
6816                // this Intent, use that.
6817                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6818                        flags, query, r0.priority, true, false, debug, userId);
6819                if (ri != null) {
6820                    return ri;
6821                }
6822                // If we have an ephemeral app, use it
6823                for (int i = 0; i < N; i++) {
6824                    ri = query.get(i);
6825                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6826                        final String packageName = ri.activityInfo.packageName;
6827                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6828                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6829                        final int status = (int)(packedStatus >> 32);
6830                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6831                            return ri;
6832                        }
6833                    }
6834                }
6835                ri = new ResolveInfo(mResolveInfo);
6836                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6837                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6838                // If all of the options come from the same package, show the application's
6839                // label and icon instead of the generic resolver's.
6840                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6841                // and then throw away the ResolveInfo itself, meaning that the caller loses
6842                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6843                // a fallback for this case; we only set the target package's resources on
6844                // the ResolveInfo, not the ActivityInfo.
6845                final String intentPackage = intent.getPackage();
6846                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6847                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6848                    ri.resolvePackageName = intentPackage;
6849                    if (userNeedsBadging(userId)) {
6850                        ri.noResourceId = true;
6851                    } else {
6852                        ri.icon = appi.icon;
6853                    }
6854                    ri.iconResourceId = appi.icon;
6855                    ri.labelRes = appi.labelRes;
6856                }
6857                ri.activityInfo.applicationInfo = new ApplicationInfo(
6858                        ri.activityInfo.applicationInfo);
6859                if (userId != 0) {
6860                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6861                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6862                }
6863                // Make sure that the resolver is displayable in car mode
6864                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6865                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6866                return ri;
6867            }
6868        }
6869        return null;
6870    }
6871
6872    /**
6873     * Return true if the given list is not empty and all of its contents have
6874     * an activityInfo with the given package name.
6875     */
6876    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6877        if (ArrayUtils.isEmpty(list)) {
6878            return false;
6879        }
6880        for (int i = 0, N = list.size(); i < N; i++) {
6881            final ResolveInfo ri = list.get(i);
6882            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6883            if (ai == null || !packageName.equals(ai.packageName)) {
6884                return false;
6885            }
6886        }
6887        return true;
6888    }
6889
6890    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6891            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6892        final int N = query.size();
6893        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6894                .get(userId);
6895        // Get the list of persistent preferred activities that handle the intent
6896        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6897        List<PersistentPreferredActivity> pprefs = ppir != null
6898                ? ppir.queryIntent(intent, resolvedType,
6899                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6900                        userId)
6901                : null;
6902        if (pprefs != null && pprefs.size() > 0) {
6903            final int M = pprefs.size();
6904            for (int i=0; i<M; i++) {
6905                final PersistentPreferredActivity ppa = pprefs.get(i);
6906                if (DEBUG_PREFERRED || debug) {
6907                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6908                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6909                            + "\n  component=" + ppa.mComponent);
6910                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6911                }
6912                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6913                        flags | MATCH_DISABLED_COMPONENTS, userId);
6914                if (DEBUG_PREFERRED || debug) {
6915                    Slog.v(TAG, "Found persistent preferred activity:");
6916                    if (ai != null) {
6917                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6918                    } else {
6919                        Slog.v(TAG, "  null");
6920                    }
6921                }
6922                if (ai == null) {
6923                    // This previously registered persistent preferred activity
6924                    // component is no longer known. Ignore it and do NOT remove it.
6925                    continue;
6926                }
6927                for (int j=0; j<N; j++) {
6928                    final ResolveInfo ri = query.get(j);
6929                    if (!ri.activityInfo.applicationInfo.packageName
6930                            .equals(ai.applicationInfo.packageName)) {
6931                        continue;
6932                    }
6933                    if (!ri.activityInfo.name.equals(ai.name)) {
6934                        continue;
6935                    }
6936                    //  Found a persistent preference that can handle the intent.
6937                    if (DEBUG_PREFERRED || debug) {
6938                        Slog.v(TAG, "Returning persistent preferred activity: " +
6939                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6940                    }
6941                    return ri;
6942                }
6943            }
6944        }
6945        return null;
6946    }
6947
6948    // TODO: handle preferred activities missing while user has amnesia
6949    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6950            List<ResolveInfo> query, int priority, boolean always,
6951            boolean removeMatches, boolean debug, int userId) {
6952        if (!sUserManager.exists(userId)) return null;
6953        final int callingUid = Binder.getCallingUid();
6954        flags = updateFlagsForResolve(
6955                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6956        intent = updateIntentForResolve(intent);
6957        // writer
6958        synchronized (mPackages) {
6959            // Try to find a matching persistent preferred activity.
6960            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6961                    debug, userId);
6962
6963            // If a persistent preferred activity matched, use it.
6964            if (pri != null) {
6965                return pri;
6966            }
6967
6968            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6969            // Get the list of preferred activities that handle the intent
6970            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6971            List<PreferredActivity> prefs = pir != null
6972                    ? pir.queryIntent(intent, resolvedType,
6973                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6974                            userId)
6975                    : null;
6976            if (prefs != null && prefs.size() > 0) {
6977                boolean changed = false;
6978                try {
6979                    // First figure out how good the original match set is.
6980                    // We will only allow preferred activities that came
6981                    // from the same match quality.
6982                    int match = 0;
6983
6984                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6985
6986                    final int N = query.size();
6987                    for (int j=0; j<N; j++) {
6988                        final ResolveInfo ri = query.get(j);
6989                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6990                                + ": 0x" + Integer.toHexString(match));
6991                        if (ri.match > match) {
6992                            match = ri.match;
6993                        }
6994                    }
6995
6996                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6997                            + Integer.toHexString(match));
6998
6999                    match &= IntentFilter.MATCH_CATEGORY_MASK;
7000                    final int M = prefs.size();
7001                    for (int i=0; i<M; i++) {
7002                        final PreferredActivity pa = prefs.get(i);
7003                        if (DEBUG_PREFERRED || debug) {
7004                            Slog.v(TAG, "Checking PreferredActivity ds="
7005                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
7006                                    + "\n  component=" + pa.mPref.mComponent);
7007                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
7008                        }
7009                        if (pa.mPref.mMatch != match) {
7010                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
7011                                    + Integer.toHexString(pa.mPref.mMatch));
7012                            continue;
7013                        }
7014                        // If it's not an "always" type preferred activity and that's what we're
7015                        // looking for, skip it.
7016                        if (always && !pa.mPref.mAlways) {
7017                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
7018                            continue;
7019                        }
7020                        final ActivityInfo ai = getActivityInfo(
7021                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
7022                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
7023                                userId);
7024                        if (DEBUG_PREFERRED || debug) {
7025                            Slog.v(TAG, "Found preferred activity:");
7026                            if (ai != null) {
7027                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
7028                            } else {
7029                                Slog.v(TAG, "  null");
7030                            }
7031                        }
7032                        if (ai == null) {
7033                            // This previously registered preferred activity
7034                            // component is no longer known.  Most likely an update
7035                            // to the app was installed and in the new version this
7036                            // component no longer exists.  Clean it up by removing
7037                            // it from the preferred activities list, and skip it.
7038                            Slog.w(TAG, "Removing dangling preferred activity: "
7039                                    + pa.mPref.mComponent);
7040                            pir.removeFilter(pa);
7041                            changed = true;
7042                            continue;
7043                        }
7044                        for (int j=0; j<N; j++) {
7045                            final ResolveInfo ri = query.get(j);
7046                            if (!ri.activityInfo.applicationInfo.packageName
7047                                    .equals(ai.applicationInfo.packageName)) {
7048                                continue;
7049                            }
7050                            if (!ri.activityInfo.name.equals(ai.name)) {
7051                                continue;
7052                            }
7053
7054                            if (removeMatches) {
7055                                pir.removeFilter(pa);
7056                                changed = true;
7057                                if (DEBUG_PREFERRED) {
7058                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
7059                                }
7060                                break;
7061                            }
7062
7063                            // Okay we found a previously set preferred or last chosen app.
7064                            // If the result set is different from when this
7065                            // was created, and is not a subset of the preferred set, we need to
7066                            // clear it and re-ask the user their preference, if we're looking for
7067                            // an "always" type entry.
7068                            if (always && !pa.mPref.sameSet(query)) {
7069                                if (pa.mPref.isSuperset(query)) {
7070                                    // some components of the set are no longer present in
7071                                    // the query, but the preferred activity can still be reused
7072                                    if (DEBUG_PREFERRED) {
7073                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
7074                                                + " still valid as only non-preferred components"
7075                                                + " were removed for " + intent + " type "
7076                                                + resolvedType);
7077                                    }
7078                                    // remove obsolete components and re-add the up-to-date filter
7079                                    PreferredActivity freshPa = new PreferredActivity(pa,
7080                                            pa.mPref.mMatch,
7081                                            pa.mPref.discardObsoleteComponents(query),
7082                                            pa.mPref.mComponent,
7083                                            pa.mPref.mAlways);
7084                                    pir.removeFilter(pa);
7085                                    pir.addFilter(freshPa);
7086                                    changed = true;
7087                                } else {
7088                                    Slog.i(TAG,
7089                                            "Result set changed, dropping preferred activity for "
7090                                                    + intent + " type " + resolvedType);
7091                                    if (DEBUG_PREFERRED) {
7092                                        Slog.v(TAG, "Removing preferred activity since set changed "
7093                                                + pa.mPref.mComponent);
7094                                    }
7095                                    pir.removeFilter(pa);
7096                                    // Re-add the filter as a "last chosen" entry (!always)
7097                                    PreferredActivity lastChosen = new PreferredActivity(
7098                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
7099                                    pir.addFilter(lastChosen);
7100                                    changed = true;
7101                                    return null;
7102                                }
7103                            }
7104
7105                            // Yay! Either the set matched or we're looking for the last chosen
7106                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
7107                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
7108                            return ri;
7109                        }
7110                    }
7111                } finally {
7112                    if (changed) {
7113                        if (DEBUG_PREFERRED) {
7114                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
7115                        }
7116                        scheduleWritePackageRestrictionsLocked(userId);
7117                    }
7118                }
7119            }
7120        }
7121        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
7122        return null;
7123    }
7124
7125    /*
7126     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
7127     */
7128    @Override
7129    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
7130            int targetUserId) {
7131        mContext.enforceCallingOrSelfPermission(
7132                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
7133        List<CrossProfileIntentFilter> matches =
7134                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
7135        if (matches != null) {
7136            int size = matches.size();
7137            for (int i = 0; i < size; i++) {
7138                if (matches.get(i).getTargetUserId() == targetUserId) return true;
7139            }
7140        }
7141        if (hasWebURI(intent)) {
7142            // cross-profile app linking works only towards the parent.
7143            final int callingUid = Binder.getCallingUid();
7144            final UserInfo parent = getProfileParent(sourceUserId);
7145            synchronized(mPackages) {
7146                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
7147                        false /*includeInstantApps*/);
7148                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
7149                        intent, resolvedType, flags, sourceUserId, parent.id);
7150                return xpDomainInfo != null;
7151            }
7152        }
7153        return false;
7154    }
7155
7156    private UserInfo getProfileParent(int userId) {
7157        final long identity = Binder.clearCallingIdentity();
7158        try {
7159            return sUserManager.getProfileParent(userId);
7160        } finally {
7161            Binder.restoreCallingIdentity(identity);
7162        }
7163    }
7164
7165    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
7166            String resolvedType, int userId) {
7167        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
7168        if (resolver != null) {
7169            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
7170        }
7171        return null;
7172    }
7173
7174    @Override
7175    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
7176            String resolvedType, int flags, int userId) {
7177        try {
7178            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
7179
7180            return new ParceledListSlice<>(
7181                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
7182        } finally {
7183            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7184        }
7185    }
7186
7187    /**
7188     * Returns the package name of the calling Uid if it's an instant app. If it isn't
7189     * instant, returns {@code null}.
7190     */
7191    private String getInstantAppPackageName(int callingUid) {
7192        synchronized (mPackages) {
7193            // If the caller is an isolated app use the owner's uid for the lookup.
7194            if (Process.isIsolated(callingUid)) {
7195                callingUid = mIsolatedOwners.get(callingUid);
7196            }
7197            final int appId = UserHandle.getAppId(callingUid);
7198            final Object obj = mSettings.getUserIdLPr(appId);
7199            if (obj instanceof PackageSetting) {
7200                final PackageSetting ps = (PackageSetting) obj;
7201                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
7202                return isInstantApp ? ps.pkg.packageName : null;
7203            }
7204        }
7205        return null;
7206    }
7207
7208    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7209            String resolvedType, int flags, int userId) {
7210        return queryIntentActivitiesInternal(
7211                intent, resolvedType, flags, Binder.getCallingUid(), userId,
7212                false /*resolveForStart*/, true /*allowDynamicSplits*/);
7213    }
7214
7215    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7216            String resolvedType, int flags, int filterCallingUid, int userId,
7217            boolean resolveForStart, boolean allowDynamicSplits) {
7218        if (!sUserManager.exists(userId)) return Collections.emptyList();
7219        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
7220        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7221                false /* requireFullPermission */, false /* checkShell */,
7222                "query intent activities");
7223        final String pkgName = intent.getPackage();
7224        ComponentName comp = intent.getComponent();
7225        if (comp == null) {
7226            if (intent.getSelector() != null) {
7227                intent = intent.getSelector();
7228                comp = intent.getComponent();
7229            }
7230        }
7231
7232        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
7233                comp != null || pkgName != null /*onlyExposedExplicitly*/);
7234        if (comp != null) {
7235            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7236            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
7237            if (ai != null) {
7238                // When specifying an explicit component, we prevent the activity from being
7239                // used when either 1) the calling package is normal and the activity is within
7240                // an ephemeral application or 2) the calling package is ephemeral and the
7241                // activity is not visible to ephemeral applications.
7242                final boolean matchInstantApp =
7243                        (flags & PackageManager.MATCH_INSTANT) != 0;
7244                final boolean matchVisibleToInstantAppOnly =
7245                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7246                final boolean matchExplicitlyVisibleOnly =
7247                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7248                final boolean isCallerInstantApp =
7249                        instantAppPkgName != null;
7250                final boolean isTargetSameInstantApp =
7251                        comp.getPackageName().equals(instantAppPkgName);
7252                final boolean isTargetInstantApp =
7253                        (ai.applicationInfo.privateFlags
7254                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7255                final boolean isTargetVisibleToInstantApp =
7256                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7257                final boolean isTargetExplicitlyVisibleToInstantApp =
7258                        isTargetVisibleToInstantApp
7259                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7260                final boolean isTargetHiddenFromInstantApp =
7261                        !isTargetVisibleToInstantApp
7262                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7263                final boolean blockResolution =
7264                        !isTargetSameInstantApp
7265                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7266                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7267                                        && isTargetHiddenFromInstantApp));
7268                if (!blockResolution) {
7269                    final ResolveInfo ri = new ResolveInfo();
7270                    ri.activityInfo = ai;
7271                    list.add(ri);
7272                }
7273            }
7274            return applyPostResolutionFilter(
7275                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
7276        }
7277
7278        // reader
7279        boolean sortResult = false;
7280        boolean addEphemeral = false;
7281        List<ResolveInfo> result;
7282        final boolean ephemeralDisabled = isEphemeralDisabled();
7283        synchronized (mPackages) {
7284            if (pkgName == null) {
7285                List<CrossProfileIntentFilter> matchingFilters =
7286                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
7287                // Check for results that need to skip the current profile.
7288                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
7289                        resolvedType, flags, userId);
7290                if (xpResolveInfo != null) {
7291                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
7292                    xpResult.add(xpResolveInfo);
7293                    return applyPostResolutionFilter(
7294                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
7295                            allowDynamicSplits, filterCallingUid, userId);
7296                }
7297
7298                // Check for results in the current profile.
7299                result = filterIfNotSystemUser(mActivities.queryIntent(
7300                        intent, resolvedType, flags, userId), userId);
7301                addEphemeral = !ephemeralDisabled
7302                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
7303                // Check for cross profile results.
7304                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
7305                xpResolveInfo = queryCrossProfileIntents(
7306                        matchingFilters, intent, resolvedType, flags, userId,
7307                        hasNonNegativePriorityResult);
7308                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
7309                    boolean isVisibleToUser = filterIfNotSystemUser(
7310                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
7311                    if (isVisibleToUser) {
7312                        result.add(xpResolveInfo);
7313                        sortResult = true;
7314                    }
7315                }
7316                if (hasWebURI(intent)) {
7317                    CrossProfileDomainInfo xpDomainInfo = null;
7318                    final UserInfo parent = getProfileParent(userId);
7319                    if (parent != null) {
7320                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
7321                                flags, userId, parent.id);
7322                    }
7323                    if (xpDomainInfo != null) {
7324                        if (xpResolveInfo != null) {
7325                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
7326                            // in the result.
7327                            result.remove(xpResolveInfo);
7328                        }
7329                        if (result.size() == 0 && !addEphemeral) {
7330                            // No result in current profile, but found candidate in parent user.
7331                            // And we are not going to add emphemeral app, so we can return the
7332                            // result straight away.
7333                            result.add(xpDomainInfo.resolveInfo);
7334                            return applyPostResolutionFilter(result, instantAppPkgName,
7335                                    allowDynamicSplits, filterCallingUid, userId);
7336                        }
7337                    } else if (result.size() <= 1 && !addEphemeral) {
7338                        // No result in parent user and <= 1 result in current profile, and we
7339                        // are not going to add emphemeral app, so we can return the result without
7340                        // further processing.
7341                        return applyPostResolutionFilter(result, instantAppPkgName,
7342                                allowDynamicSplits, filterCallingUid, userId);
7343                    }
7344                    // We have more than one candidate (combining results from current and parent
7345                    // profile), so we need filtering and sorting.
7346                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
7347                            intent, flags, result, xpDomainInfo, userId);
7348                    sortResult = true;
7349                }
7350            } else {
7351                final PackageParser.Package pkg = mPackages.get(pkgName);
7352                result = null;
7353                if (pkg != null) {
7354                    result = filterIfNotSystemUser(
7355                            mActivities.queryIntentForPackage(
7356                                    intent, resolvedType, flags, pkg.activities, userId),
7357                            userId);
7358                }
7359                if (result == null || result.size() == 0) {
7360                    // the caller wants to resolve for a particular package; however, there
7361                    // were no installed results, so, try to find an ephemeral result
7362                    addEphemeral = !ephemeralDisabled
7363                            && isInstantAppAllowed(
7364                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
7365                    if (result == null) {
7366                        result = new ArrayList<>();
7367                    }
7368                }
7369            }
7370        }
7371        if (addEphemeral) {
7372            result = maybeAddInstantAppInstaller(
7373                    result, intent, resolvedType, flags, userId, resolveForStart);
7374        }
7375        if (sortResult) {
7376            Collections.sort(result, mResolvePrioritySorter);
7377        }
7378        return applyPostResolutionFilter(
7379                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
7380    }
7381
7382    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
7383            String resolvedType, int flags, int userId, boolean resolveForStart) {
7384        // first, check to see if we've got an instant app already installed
7385        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
7386        ResolveInfo localInstantApp = null;
7387        boolean blockResolution = false;
7388        if (!alreadyResolvedLocally) {
7389            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
7390                    flags
7391                        | PackageManager.GET_RESOLVED_FILTER
7392                        | PackageManager.MATCH_INSTANT
7393                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
7394                    userId);
7395            for (int i = instantApps.size() - 1; i >= 0; --i) {
7396                final ResolveInfo info = instantApps.get(i);
7397                final String packageName = info.activityInfo.packageName;
7398                final PackageSetting ps = mSettings.mPackages.get(packageName);
7399                if (ps.getInstantApp(userId)) {
7400                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7401                    final int status = (int)(packedStatus >> 32);
7402                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7403                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7404                        // there's a local instant application installed, but, the user has
7405                        // chosen to never use it; skip resolution and don't acknowledge
7406                        // an instant application is even available
7407                        if (DEBUG_EPHEMERAL) {
7408                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7409                        }
7410                        blockResolution = true;
7411                        break;
7412                    } else {
7413                        // we have a locally installed instant application; skip resolution
7414                        // but acknowledge there's an instant application available
7415                        if (DEBUG_EPHEMERAL) {
7416                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7417                        }
7418                        localInstantApp = info;
7419                        break;
7420                    }
7421                }
7422            }
7423        }
7424        // no app installed, let's see if one's available
7425        AuxiliaryResolveInfo auxiliaryResponse = null;
7426        if (!blockResolution) {
7427            if (localInstantApp == null) {
7428                // we don't have an instant app locally, resolve externally
7429                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7430                final InstantAppRequest requestObject = new InstantAppRequest(
7431                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
7432                        null /*callingPackage*/, userId, null /*verificationBundle*/,
7433                        resolveForStart);
7434                auxiliaryResponse =
7435                        InstantAppResolver.doInstantAppResolutionPhaseOne(
7436                                mContext, mInstantAppResolverConnection, requestObject);
7437                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7438            } else {
7439                // we have an instant application locally, but, we can't admit that since
7440                // callers shouldn't be able to determine prior browsing. create a dummy
7441                // auxiliary response so the downstream code behaves as if there's an
7442                // instant application available externally. when it comes time to start
7443                // the instant application, we'll do the right thing.
7444                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7445                auxiliaryResponse = new AuxiliaryResolveInfo(
7446                        ai.packageName, null /*splitName*/, null /*failureActivity*/,
7447                        ai.versionCode, null /*failureIntent*/);
7448            }
7449        }
7450        if (auxiliaryResponse != null) {
7451            if (DEBUG_EPHEMERAL) {
7452                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7453            }
7454            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7455            final PackageSetting ps =
7456                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7457            if (ps != null) {
7458                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7459                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7460                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
7461                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7462                // make sure this resolver is the default
7463                ephemeralInstaller.isDefault = true;
7464                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7465                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7466                // add a non-generic filter
7467                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
7468                ephemeralInstaller.filter.addDataPath(
7469                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7470                ephemeralInstaller.isInstantAppAvailable = true;
7471                result.add(ephemeralInstaller);
7472            }
7473        }
7474        return result;
7475    }
7476
7477    private static class CrossProfileDomainInfo {
7478        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7479        ResolveInfo resolveInfo;
7480        /* Best domain verification status of the activities found in the other profile */
7481        int bestDomainVerificationStatus;
7482    }
7483
7484    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7485            String resolvedType, int flags, int sourceUserId, int parentUserId) {
7486        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7487                sourceUserId)) {
7488            return null;
7489        }
7490        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7491                resolvedType, flags, parentUserId);
7492
7493        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7494            return null;
7495        }
7496        CrossProfileDomainInfo result = null;
7497        int size = resultTargetUser.size();
7498        for (int i = 0; i < size; i++) {
7499            ResolveInfo riTargetUser = resultTargetUser.get(i);
7500            // Intent filter verification is only for filters that specify a host. So don't return
7501            // those that handle all web uris.
7502            if (riTargetUser.handleAllWebDataURI) {
7503                continue;
7504            }
7505            String packageName = riTargetUser.activityInfo.packageName;
7506            PackageSetting ps = mSettings.mPackages.get(packageName);
7507            if (ps == null) {
7508                continue;
7509            }
7510            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7511            int status = (int)(verificationState >> 32);
7512            if (result == null) {
7513                result = new CrossProfileDomainInfo();
7514                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7515                        sourceUserId, parentUserId);
7516                result.bestDomainVerificationStatus = status;
7517            } else {
7518                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7519                        result.bestDomainVerificationStatus);
7520            }
7521        }
7522        // Don't consider matches with status NEVER across profiles.
7523        if (result != null && result.bestDomainVerificationStatus
7524                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7525            return null;
7526        }
7527        return result;
7528    }
7529
7530    /**
7531     * Verification statuses are ordered from the worse to the best, except for
7532     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7533     */
7534    private int bestDomainVerificationStatus(int status1, int status2) {
7535        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7536            return status2;
7537        }
7538        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7539            return status1;
7540        }
7541        return (int) MathUtils.max(status1, status2);
7542    }
7543
7544    private boolean isUserEnabled(int userId) {
7545        long callingId = Binder.clearCallingIdentity();
7546        try {
7547            UserInfo userInfo = sUserManager.getUserInfo(userId);
7548            return userInfo != null && userInfo.isEnabled();
7549        } finally {
7550            Binder.restoreCallingIdentity(callingId);
7551        }
7552    }
7553
7554    /**
7555     * Filter out activities with systemUserOnly flag set, when current user is not System.
7556     *
7557     * @return filtered list
7558     */
7559    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7560        if (userId == UserHandle.USER_SYSTEM) {
7561            return resolveInfos;
7562        }
7563        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7564            ResolveInfo info = resolveInfos.get(i);
7565            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7566                resolveInfos.remove(i);
7567            }
7568        }
7569        return resolveInfos;
7570    }
7571
7572    /**
7573     * Filters out ephemeral activities.
7574     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7575     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7576     *
7577     * @param resolveInfos The pre-filtered list of resolved activities
7578     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7579     *          is performed.
7580     * @return A filtered list of resolved activities.
7581     */
7582    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7583            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) {
7584        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7585            final ResolveInfo info = resolveInfos.get(i);
7586            // allow activities that are defined in the provided package
7587            if (allowDynamicSplits
7588                    && info.activityInfo.splitName != null
7589                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7590                            info.activityInfo.splitName)) {
7591                // requested activity is defined in a split that hasn't been installed yet.
7592                // add the installer to the resolve list
7593                if (DEBUG_INSTALL) {
7594                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
7595                }
7596                final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7597                final ComponentName installFailureActivity = findInstallFailureActivity(
7598                        info.activityInfo.packageName,  filterCallingUid, userId);
7599                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7600                        info.activityInfo.packageName, info.activityInfo.splitName,
7601                        installFailureActivity,
7602                        info.activityInfo.applicationInfo.versionCode,
7603                        null /*failureIntent*/);
7604                // make sure this resolver is the default
7605                installerInfo.isDefault = true;
7606                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7607                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7608                // add a non-generic filter
7609                installerInfo.filter = new IntentFilter();
7610                // load resources from the correct package
7611                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7612                resolveInfos.set(i, installerInfo);
7613                continue;
7614            }
7615            // caller is a full app, don't need to apply any other filtering
7616            if (ephemeralPkgName == null) {
7617                continue;
7618            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
7619                // caller is same app; don't need to apply any other filtering
7620                continue;
7621            }
7622            // allow activities that have been explicitly exposed to ephemeral apps
7623            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7624            if (!isEphemeralApp
7625                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7626                continue;
7627            }
7628            resolveInfos.remove(i);
7629        }
7630        return resolveInfos;
7631    }
7632
7633    /**
7634     * Returns the activity component that can handle install failures.
7635     * <p>By default, the instant application installer handles failures. However, an
7636     * application may want to handle failures on its own. Applications do this by
7637     * creating an activity with an intent filter that handles the action
7638     * {@link Intent#ACTION_INSTALL_FAILURE}.
7639     */
7640    private @Nullable ComponentName findInstallFailureActivity(
7641            String packageName, int filterCallingUid, int userId) {
7642        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
7643        failureActivityIntent.setPackage(packageName);
7644        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
7645        final List<ResolveInfo> result = queryIntentActivitiesInternal(
7646                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
7647                false /*resolveForStart*/, false /*allowDynamicSplits*/);
7648        final int NR = result.size();
7649        if (NR > 0) {
7650            for (int i = 0; i < NR; i++) {
7651                final ResolveInfo info = result.get(i);
7652                if (info.activityInfo.splitName != null) {
7653                    continue;
7654                }
7655                return new ComponentName(packageName, info.activityInfo.name);
7656            }
7657        }
7658        return null;
7659    }
7660
7661    /**
7662     * @param resolveInfos list of resolve infos in descending priority order
7663     * @return if the list contains a resolve info with non-negative priority
7664     */
7665    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7666        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7667    }
7668
7669    private static boolean hasWebURI(Intent intent) {
7670        if (intent.getData() == null) {
7671            return false;
7672        }
7673        final String scheme = intent.getScheme();
7674        if (TextUtils.isEmpty(scheme)) {
7675            return false;
7676        }
7677        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7678    }
7679
7680    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7681            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7682            int userId) {
7683        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7684
7685        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7686            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7687                    candidates.size());
7688        }
7689
7690        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7691        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7692        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7693        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7694        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7695        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7696
7697        synchronized (mPackages) {
7698            final int count = candidates.size();
7699            // First, try to use linked apps. Partition the candidates into four lists:
7700            // one for the final results, one for the "do not use ever", one for "undefined status"
7701            // and finally one for "browser app type".
7702            for (int n=0; n<count; n++) {
7703                ResolveInfo info = candidates.get(n);
7704                String packageName = info.activityInfo.packageName;
7705                PackageSetting ps = mSettings.mPackages.get(packageName);
7706                if (ps != null) {
7707                    // Add to the special match all list (Browser use case)
7708                    if (info.handleAllWebDataURI) {
7709                        matchAllList.add(info);
7710                        continue;
7711                    }
7712                    // Try to get the status from User settings first
7713                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7714                    int status = (int)(packedStatus >> 32);
7715                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7716                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7717                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7718                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7719                                    + " : linkgen=" + linkGeneration);
7720                        }
7721                        // Use link-enabled generation as preferredOrder, i.e.
7722                        // prefer newly-enabled over earlier-enabled.
7723                        info.preferredOrder = linkGeneration;
7724                        alwaysList.add(info);
7725                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7726                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7727                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7728                        }
7729                        neverList.add(info);
7730                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7731                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7732                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7733                        }
7734                        alwaysAskList.add(info);
7735                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7736                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7737                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7738                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7739                        }
7740                        undefinedList.add(info);
7741                    }
7742                }
7743            }
7744
7745            // We'll want to include browser possibilities in a few cases
7746            boolean includeBrowser = false;
7747
7748            // First try to add the "always" resolution(s) for the current user, if any
7749            if (alwaysList.size() > 0) {
7750                result.addAll(alwaysList);
7751            } else {
7752                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7753                result.addAll(undefinedList);
7754                // Maybe add one for the other profile.
7755                if (xpDomainInfo != null && (
7756                        xpDomainInfo.bestDomainVerificationStatus
7757                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7758                    result.add(xpDomainInfo.resolveInfo);
7759                }
7760                includeBrowser = true;
7761            }
7762
7763            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7764            // If there were 'always' entries their preferred order has been set, so we also
7765            // back that off to make the alternatives equivalent
7766            if (alwaysAskList.size() > 0) {
7767                for (ResolveInfo i : result) {
7768                    i.preferredOrder = 0;
7769                }
7770                result.addAll(alwaysAskList);
7771                includeBrowser = true;
7772            }
7773
7774            if (includeBrowser) {
7775                // Also add browsers (all of them or only the default one)
7776                if (DEBUG_DOMAIN_VERIFICATION) {
7777                    Slog.v(TAG, "   ...including browsers in candidate set");
7778                }
7779                if ((matchFlags & MATCH_ALL) != 0) {
7780                    result.addAll(matchAllList);
7781                } else {
7782                    // Browser/generic handling case.  If there's a default browser, go straight
7783                    // to that (but only if there is no other higher-priority match).
7784                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7785                    int maxMatchPrio = 0;
7786                    ResolveInfo defaultBrowserMatch = null;
7787                    final int numCandidates = matchAllList.size();
7788                    for (int n = 0; n < numCandidates; n++) {
7789                        ResolveInfo info = matchAllList.get(n);
7790                        // track the highest overall match priority...
7791                        if (info.priority > maxMatchPrio) {
7792                            maxMatchPrio = info.priority;
7793                        }
7794                        // ...and the highest-priority default browser match
7795                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7796                            if (defaultBrowserMatch == null
7797                                    || (defaultBrowserMatch.priority < info.priority)) {
7798                                if (debug) {
7799                                    Slog.v(TAG, "Considering default browser match " + info);
7800                                }
7801                                defaultBrowserMatch = info;
7802                            }
7803                        }
7804                    }
7805                    if (defaultBrowserMatch != null
7806                            && defaultBrowserMatch.priority >= maxMatchPrio
7807                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7808                    {
7809                        if (debug) {
7810                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7811                        }
7812                        result.add(defaultBrowserMatch);
7813                    } else {
7814                        result.addAll(matchAllList);
7815                    }
7816                }
7817
7818                // If there is nothing selected, add all candidates and remove the ones that the user
7819                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7820                if (result.size() == 0) {
7821                    result.addAll(candidates);
7822                    result.removeAll(neverList);
7823                }
7824            }
7825        }
7826        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7827            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7828                    result.size());
7829            for (ResolveInfo info : result) {
7830                Slog.v(TAG, "  + " + info.activityInfo);
7831            }
7832        }
7833        return result;
7834    }
7835
7836    // Returns a packed value as a long:
7837    //
7838    // high 'int'-sized word: link status: undefined/ask/never/always.
7839    // low 'int'-sized word: relative priority among 'always' results.
7840    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7841        long result = ps.getDomainVerificationStatusForUser(userId);
7842        // if none available, get the master status
7843        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7844            if (ps.getIntentFilterVerificationInfo() != null) {
7845                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7846            }
7847        }
7848        return result;
7849    }
7850
7851    private ResolveInfo querySkipCurrentProfileIntents(
7852            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7853            int flags, int sourceUserId) {
7854        if (matchingFilters != null) {
7855            int size = matchingFilters.size();
7856            for (int i = 0; i < size; i ++) {
7857                CrossProfileIntentFilter filter = matchingFilters.get(i);
7858                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7859                    // Checking if there are activities in the target user that can handle the
7860                    // intent.
7861                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7862                            resolvedType, flags, sourceUserId);
7863                    if (resolveInfo != null) {
7864                        return resolveInfo;
7865                    }
7866                }
7867            }
7868        }
7869        return null;
7870    }
7871
7872    // Return matching ResolveInfo in target user if any.
7873    private ResolveInfo queryCrossProfileIntents(
7874            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7875            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7876        if (matchingFilters != null) {
7877            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7878            // match the same intent. For performance reasons, it is better not to
7879            // run queryIntent twice for the same userId
7880            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7881            int size = matchingFilters.size();
7882            for (int i = 0; i < size; i++) {
7883                CrossProfileIntentFilter filter = matchingFilters.get(i);
7884                int targetUserId = filter.getTargetUserId();
7885                boolean skipCurrentProfile =
7886                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7887                boolean skipCurrentProfileIfNoMatchFound =
7888                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7889                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7890                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7891                    // Checking if there are activities in the target user that can handle the
7892                    // intent.
7893                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7894                            resolvedType, flags, sourceUserId);
7895                    if (resolveInfo != null) return resolveInfo;
7896                    alreadyTriedUserIds.put(targetUserId, true);
7897                }
7898            }
7899        }
7900        return null;
7901    }
7902
7903    /**
7904     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7905     * will forward the intent to the filter's target user.
7906     * Otherwise, returns null.
7907     */
7908    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7909            String resolvedType, int flags, int sourceUserId) {
7910        int targetUserId = filter.getTargetUserId();
7911        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7912                resolvedType, flags, targetUserId);
7913        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7914            // If all the matches in the target profile are suspended, return null.
7915            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7916                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7917                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7918                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7919                            targetUserId);
7920                }
7921            }
7922        }
7923        return null;
7924    }
7925
7926    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7927            int sourceUserId, int targetUserId) {
7928        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7929        long ident = Binder.clearCallingIdentity();
7930        boolean targetIsProfile;
7931        try {
7932            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7933        } finally {
7934            Binder.restoreCallingIdentity(ident);
7935        }
7936        String className;
7937        if (targetIsProfile) {
7938            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7939        } else {
7940            className = FORWARD_INTENT_TO_PARENT;
7941        }
7942        ComponentName forwardingActivityComponentName = new ComponentName(
7943                mAndroidApplication.packageName, className);
7944        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7945                sourceUserId);
7946        if (!targetIsProfile) {
7947            forwardingActivityInfo.showUserIcon = targetUserId;
7948            forwardingResolveInfo.noResourceId = true;
7949        }
7950        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7951        forwardingResolveInfo.priority = 0;
7952        forwardingResolveInfo.preferredOrder = 0;
7953        forwardingResolveInfo.match = 0;
7954        forwardingResolveInfo.isDefault = true;
7955        forwardingResolveInfo.filter = filter;
7956        forwardingResolveInfo.targetUserId = targetUserId;
7957        return forwardingResolveInfo;
7958    }
7959
7960    @Override
7961    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7962            Intent[] specifics, String[] specificTypes, Intent intent,
7963            String resolvedType, int flags, int userId) {
7964        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7965                specificTypes, intent, resolvedType, flags, userId));
7966    }
7967
7968    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7969            Intent[] specifics, String[] specificTypes, Intent intent,
7970            String resolvedType, int flags, int userId) {
7971        if (!sUserManager.exists(userId)) return Collections.emptyList();
7972        final int callingUid = Binder.getCallingUid();
7973        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7974                false /*includeInstantApps*/);
7975        enforceCrossUserPermission(callingUid, userId,
7976                false /*requireFullPermission*/, false /*checkShell*/,
7977                "query intent activity options");
7978        final String resultsAction = intent.getAction();
7979
7980        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7981                | PackageManager.GET_RESOLVED_FILTER, userId);
7982
7983        if (DEBUG_INTENT_MATCHING) {
7984            Log.v(TAG, "Query " + intent + ": " + results);
7985        }
7986
7987        int specificsPos = 0;
7988        int N;
7989
7990        // todo: note that the algorithm used here is O(N^2).  This
7991        // isn't a problem in our current environment, but if we start running
7992        // into situations where we have more than 5 or 10 matches then this
7993        // should probably be changed to something smarter...
7994
7995        // First we go through and resolve each of the specific items
7996        // that were supplied, taking care of removing any corresponding
7997        // duplicate items in the generic resolve list.
7998        if (specifics != null) {
7999            for (int i=0; i<specifics.length; i++) {
8000                final Intent sintent = specifics[i];
8001                if (sintent == null) {
8002                    continue;
8003                }
8004
8005                if (DEBUG_INTENT_MATCHING) {
8006                    Log.v(TAG, "Specific #" + i + ": " + sintent);
8007                }
8008
8009                String action = sintent.getAction();
8010                if (resultsAction != null && resultsAction.equals(action)) {
8011                    // If this action was explicitly requested, then don't
8012                    // remove things that have it.
8013                    action = null;
8014                }
8015
8016                ResolveInfo ri = null;
8017                ActivityInfo ai = null;
8018
8019                ComponentName comp = sintent.getComponent();
8020                if (comp == null) {
8021                    ri = resolveIntent(
8022                        sintent,
8023                        specificTypes != null ? specificTypes[i] : null,
8024                            flags, userId);
8025                    if (ri == null) {
8026                        continue;
8027                    }
8028                    if (ri == mResolveInfo) {
8029                        // ACK!  Must do something better with this.
8030                    }
8031                    ai = ri.activityInfo;
8032                    comp = new ComponentName(ai.applicationInfo.packageName,
8033                            ai.name);
8034                } else {
8035                    ai = getActivityInfo(comp, flags, userId);
8036                    if (ai == null) {
8037                        continue;
8038                    }
8039                }
8040
8041                // Look for any generic query activities that are duplicates
8042                // of this specific one, and remove them from the results.
8043                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
8044                N = results.size();
8045                int j;
8046                for (j=specificsPos; j<N; j++) {
8047                    ResolveInfo sri = results.get(j);
8048                    if ((sri.activityInfo.name.equals(comp.getClassName())
8049                            && sri.activityInfo.applicationInfo.packageName.equals(
8050                                    comp.getPackageName()))
8051                        || (action != null && sri.filter.matchAction(action))) {
8052                        results.remove(j);
8053                        if (DEBUG_INTENT_MATCHING) Log.v(
8054                            TAG, "Removing duplicate item from " + j
8055                            + " due to specific " + specificsPos);
8056                        if (ri == null) {
8057                            ri = sri;
8058                        }
8059                        j--;
8060                        N--;
8061                    }
8062                }
8063
8064                // Add this specific item to its proper place.
8065                if (ri == null) {
8066                    ri = new ResolveInfo();
8067                    ri.activityInfo = ai;
8068                }
8069                results.add(specificsPos, ri);
8070                ri.specificIndex = i;
8071                specificsPos++;
8072            }
8073        }
8074
8075        // Now we go through the remaining generic results and remove any
8076        // duplicate actions that are found here.
8077        N = results.size();
8078        for (int i=specificsPos; i<N-1; i++) {
8079            final ResolveInfo rii = results.get(i);
8080            if (rii.filter == null) {
8081                continue;
8082            }
8083
8084            // Iterate over all of the actions of this result's intent
8085            // filter...  typically this should be just one.
8086            final Iterator<String> it = rii.filter.actionsIterator();
8087            if (it == null) {
8088                continue;
8089            }
8090            while (it.hasNext()) {
8091                final String action = it.next();
8092                if (resultsAction != null && resultsAction.equals(action)) {
8093                    // If this action was explicitly requested, then don't
8094                    // remove things that have it.
8095                    continue;
8096                }
8097                for (int j=i+1; j<N; j++) {
8098                    final ResolveInfo rij = results.get(j);
8099                    if (rij.filter != null && rij.filter.hasAction(action)) {
8100                        results.remove(j);
8101                        if (DEBUG_INTENT_MATCHING) Log.v(
8102                            TAG, "Removing duplicate item from " + j
8103                            + " due to action " + action + " at " + i);
8104                        j--;
8105                        N--;
8106                    }
8107                }
8108            }
8109
8110            // If the caller didn't request filter information, drop it now
8111            // so we don't have to marshall/unmarshall it.
8112            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
8113                rii.filter = null;
8114            }
8115        }
8116
8117        // Filter out the caller activity if so requested.
8118        if (caller != null) {
8119            N = results.size();
8120            for (int i=0; i<N; i++) {
8121                ActivityInfo ainfo = results.get(i).activityInfo;
8122                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
8123                        && caller.getClassName().equals(ainfo.name)) {
8124                    results.remove(i);
8125                    break;
8126                }
8127            }
8128        }
8129
8130        // If the caller didn't request filter information,
8131        // drop them now so we don't have to
8132        // marshall/unmarshall it.
8133        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
8134            N = results.size();
8135            for (int i=0; i<N; i++) {
8136                results.get(i).filter = null;
8137            }
8138        }
8139
8140        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
8141        return results;
8142    }
8143
8144    @Override
8145    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
8146            String resolvedType, int flags, int userId) {
8147        return new ParceledListSlice<>(
8148                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
8149                        false /*allowDynamicSplits*/));
8150    }
8151
8152    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
8153            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
8154        if (!sUserManager.exists(userId)) return Collections.emptyList();
8155        final int callingUid = Binder.getCallingUid();
8156        enforceCrossUserPermission(callingUid, userId,
8157                false /*requireFullPermission*/, false /*checkShell*/,
8158                "query intent receivers");
8159        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8160        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8161                false /*includeInstantApps*/);
8162        ComponentName comp = intent.getComponent();
8163        if (comp == null) {
8164            if (intent.getSelector() != null) {
8165                intent = intent.getSelector();
8166                comp = intent.getComponent();
8167            }
8168        }
8169        if (comp != null) {
8170            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8171            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
8172            if (ai != null) {
8173                // When specifying an explicit component, we prevent the activity from being
8174                // used when either 1) the calling package is normal and the activity is within
8175                // an instant application or 2) the calling package is ephemeral and the
8176                // activity is not visible to instant applications.
8177                final boolean matchInstantApp =
8178                        (flags & PackageManager.MATCH_INSTANT) != 0;
8179                final boolean matchVisibleToInstantAppOnly =
8180                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8181                final boolean matchExplicitlyVisibleOnly =
8182                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
8183                final boolean isCallerInstantApp =
8184                        instantAppPkgName != null;
8185                final boolean isTargetSameInstantApp =
8186                        comp.getPackageName().equals(instantAppPkgName);
8187                final boolean isTargetInstantApp =
8188                        (ai.applicationInfo.privateFlags
8189                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8190                final boolean isTargetVisibleToInstantApp =
8191                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
8192                final boolean isTargetExplicitlyVisibleToInstantApp =
8193                        isTargetVisibleToInstantApp
8194                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
8195                final boolean isTargetHiddenFromInstantApp =
8196                        !isTargetVisibleToInstantApp
8197                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
8198                final boolean blockResolution =
8199                        !isTargetSameInstantApp
8200                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8201                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8202                                        && isTargetHiddenFromInstantApp));
8203                if (!blockResolution) {
8204                    ResolveInfo ri = new ResolveInfo();
8205                    ri.activityInfo = ai;
8206                    list.add(ri);
8207                }
8208            }
8209            return applyPostResolutionFilter(
8210                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8211        }
8212
8213        // reader
8214        synchronized (mPackages) {
8215            String pkgName = intent.getPackage();
8216            if (pkgName == null) {
8217                final List<ResolveInfo> result =
8218                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
8219                return applyPostResolutionFilter(
8220                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8221            }
8222            final PackageParser.Package pkg = mPackages.get(pkgName);
8223            if (pkg != null) {
8224                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
8225                        intent, resolvedType, flags, pkg.receivers, userId);
8226                return applyPostResolutionFilter(
8227                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8228            }
8229            return Collections.emptyList();
8230        }
8231    }
8232
8233    @Override
8234    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
8235        final int callingUid = Binder.getCallingUid();
8236        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
8237    }
8238
8239    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
8240            int userId, int callingUid) {
8241        if (!sUserManager.exists(userId)) return null;
8242        flags = updateFlagsForResolve(
8243                flags, userId, intent, callingUid, false /*includeInstantApps*/);
8244        List<ResolveInfo> query = queryIntentServicesInternal(
8245                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
8246        if (query != null) {
8247            if (query.size() >= 1) {
8248                // If there is more than one service with the same priority,
8249                // just arbitrarily pick the first one.
8250                return query.get(0);
8251            }
8252        }
8253        return null;
8254    }
8255
8256    @Override
8257    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
8258            String resolvedType, int flags, int userId) {
8259        final int callingUid = Binder.getCallingUid();
8260        return new ParceledListSlice<>(queryIntentServicesInternal(
8261                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
8262    }
8263
8264    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
8265            String resolvedType, int flags, int userId, int callingUid,
8266            boolean includeInstantApps) {
8267        if (!sUserManager.exists(userId)) return Collections.emptyList();
8268        enforceCrossUserPermission(callingUid, userId,
8269                false /*requireFullPermission*/, false /*checkShell*/,
8270                "query intent receivers");
8271        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8272        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
8273        ComponentName comp = intent.getComponent();
8274        if (comp == null) {
8275            if (intent.getSelector() != null) {
8276                intent = intent.getSelector();
8277                comp = intent.getComponent();
8278            }
8279        }
8280        if (comp != null) {
8281            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8282            final ServiceInfo si = getServiceInfo(comp, flags, userId);
8283            if (si != null) {
8284                // When specifying an explicit component, we prevent the service from being
8285                // used when either 1) the service is in an instant application and the
8286                // caller is not the same instant application or 2) the calling package is
8287                // ephemeral and the activity is not visible to ephemeral applications.
8288                final boolean matchInstantApp =
8289                        (flags & PackageManager.MATCH_INSTANT) != 0;
8290                final boolean matchVisibleToInstantAppOnly =
8291                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8292                final boolean isCallerInstantApp =
8293                        instantAppPkgName != null;
8294                final boolean isTargetSameInstantApp =
8295                        comp.getPackageName().equals(instantAppPkgName);
8296                final boolean isTargetInstantApp =
8297                        (si.applicationInfo.privateFlags
8298                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8299                final boolean isTargetHiddenFromInstantApp =
8300                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8301                final boolean blockResolution =
8302                        !isTargetSameInstantApp
8303                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8304                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8305                                        && isTargetHiddenFromInstantApp));
8306                if (!blockResolution) {
8307                    final ResolveInfo ri = new ResolveInfo();
8308                    ri.serviceInfo = si;
8309                    list.add(ri);
8310                }
8311            }
8312            return list;
8313        }
8314
8315        // reader
8316        synchronized (mPackages) {
8317            String pkgName = intent.getPackage();
8318            if (pkgName == null) {
8319                return applyPostServiceResolutionFilter(
8320                        mServices.queryIntent(intent, resolvedType, flags, userId),
8321                        instantAppPkgName);
8322            }
8323            final PackageParser.Package pkg = mPackages.get(pkgName);
8324            if (pkg != null) {
8325                return applyPostServiceResolutionFilter(
8326                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
8327                                userId),
8328                        instantAppPkgName);
8329            }
8330            return Collections.emptyList();
8331        }
8332    }
8333
8334    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
8335            String instantAppPkgName) {
8336        if (instantAppPkgName == null) {
8337            return resolveInfos;
8338        }
8339        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8340            final ResolveInfo info = resolveInfos.get(i);
8341            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
8342            // allow services that are defined in the provided package
8343            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
8344                if (info.serviceInfo.splitName != null
8345                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
8346                                info.serviceInfo.splitName)) {
8347                    // requested service is defined in a split that hasn't been installed yet.
8348                    // add the installer to the resolve list
8349                    if (DEBUG_EPHEMERAL) {
8350                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8351                    }
8352                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8353                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8354                            info.serviceInfo.packageName, info.serviceInfo.splitName,
8355                            null /*failureActivity*/, info.serviceInfo.applicationInfo.versionCode,
8356                            null /*failureIntent*/);
8357                    // make sure this resolver is the default
8358                    installerInfo.isDefault = true;
8359                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8360                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8361                    // add a non-generic filter
8362                    installerInfo.filter = new IntentFilter();
8363                    // load resources from the correct package
8364                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8365                    resolveInfos.set(i, installerInfo);
8366                }
8367                continue;
8368            }
8369            // allow services that have been explicitly exposed to ephemeral apps
8370            if (!isEphemeralApp
8371                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8372                continue;
8373            }
8374            resolveInfos.remove(i);
8375        }
8376        return resolveInfos;
8377    }
8378
8379    @Override
8380    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
8381            String resolvedType, int flags, int userId) {
8382        return new ParceledListSlice<>(
8383                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
8384    }
8385
8386    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
8387            Intent intent, String resolvedType, int flags, int userId) {
8388        if (!sUserManager.exists(userId)) return Collections.emptyList();
8389        final int callingUid = Binder.getCallingUid();
8390        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8391        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8392                false /*includeInstantApps*/);
8393        ComponentName comp = intent.getComponent();
8394        if (comp == null) {
8395            if (intent.getSelector() != null) {
8396                intent = intent.getSelector();
8397                comp = intent.getComponent();
8398            }
8399        }
8400        if (comp != null) {
8401            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8402            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
8403            if (pi != null) {
8404                // When specifying an explicit component, we prevent the provider from being
8405                // used when either 1) the provider is in an instant application and the
8406                // caller is not the same instant application or 2) the calling package is an
8407                // instant application and the provider is not visible to instant applications.
8408                final boolean matchInstantApp =
8409                        (flags & PackageManager.MATCH_INSTANT) != 0;
8410                final boolean matchVisibleToInstantAppOnly =
8411                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8412                final boolean isCallerInstantApp =
8413                        instantAppPkgName != null;
8414                final boolean isTargetSameInstantApp =
8415                        comp.getPackageName().equals(instantAppPkgName);
8416                final boolean isTargetInstantApp =
8417                        (pi.applicationInfo.privateFlags
8418                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8419                final boolean isTargetHiddenFromInstantApp =
8420                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8421                final boolean blockResolution =
8422                        !isTargetSameInstantApp
8423                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8424                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8425                                        && isTargetHiddenFromInstantApp));
8426                if (!blockResolution) {
8427                    final ResolveInfo ri = new ResolveInfo();
8428                    ri.providerInfo = pi;
8429                    list.add(ri);
8430                }
8431            }
8432            return list;
8433        }
8434
8435        // reader
8436        synchronized (mPackages) {
8437            String pkgName = intent.getPackage();
8438            if (pkgName == null) {
8439                return applyPostContentProviderResolutionFilter(
8440                        mProviders.queryIntent(intent, resolvedType, flags, userId),
8441                        instantAppPkgName);
8442            }
8443            final PackageParser.Package pkg = mPackages.get(pkgName);
8444            if (pkg != null) {
8445                return applyPostContentProviderResolutionFilter(
8446                        mProviders.queryIntentForPackage(
8447                        intent, resolvedType, flags, pkg.providers, userId),
8448                        instantAppPkgName);
8449            }
8450            return Collections.emptyList();
8451        }
8452    }
8453
8454    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8455            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8456        if (instantAppPkgName == null) {
8457            return resolveInfos;
8458        }
8459        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8460            final ResolveInfo info = resolveInfos.get(i);
8461            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8462            // allow providers that are defined in the provided package
8463            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8464                if (info.providerInfo.splitName != null
8465                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8466                                info.providerInfo.splitName)) {
8467                    // requested provider is defined in a split that hasn't been installed yet.
8468                    // add the installer to the resolve list
8469                    if (DEBUG_EPHEMERAL) {
8470                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8471                    }
8472                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8473                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8474                            info.providerInfo.packageName, info.providerInfo.splitName,
8475                            null /*failureActivity*/, info.providerInfo.applicationInfo.versionCode,
8476                            null /*failureIntent*/);
8477                    // make sure this resolver is the default
8478                    installerInfo.isDefault = true;
8479                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8480                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8481                    // add a non-generic filter
8482                    installerInfo.filter = new IntentFilter();
8483                    // load resources from the correct package
8484                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8485                    resolveInfos.set(i, installerInfo);
8486                }
8487                continue;
8488            }
8489            // allow providers that have been explicitly exposed to instant applications
8490            if (!isEphemeralApp
8491                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8492                continue;
8493            }
8494            resolveInfos.remove(i);
8495        }
8496        return resolveInfos;
8497    }
8498
8499    @Override
8500    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8501        final int callingUid = Binder.getCallingUid();
8502        if (getInstantAppPackageName(callingUid) != null) {
8503            return ParceledListSlice.emptyList();
8504        }
8505        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8506        flags = updateFlagsForPackage(flags, userId, null);
8507        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8508        enforceCrossUserPermission(callingUid, userId,
8509                true /* requireFullPermission */, false /* checkShell */,
8510                "get installed packages");
8511
8512        // writer
8513        synchronized (mPackages) {
8514            ArrayList<PackageInfo> list;
8515            if (listUninstalled) {
8516                list = new ArrayList<>(mSettings.mPackages.size());
8517                for (PackageSetting ps : mSettings.mPackages.values()) {
8518                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8519                        continue;
8520                    }
8521                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8522                        continue;
8523                    }
8524                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8525                    if (pi != null) {
8526                        list.add(pi);
8527                    }
8528                }
8529            } else {
8530                list = new ArrayList<>(mPackages.size());
8531                for (PackageParser.Package p : mPackages.values()) {
8532                    final PackageSetting ps = (PackageSetting) p.mExtras;
8533                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8534                        continue;
8535                    }
8536                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8537                        continue;
8538                    }
8539                    final PackageInfo pi = generatePackageInfo((PackageSetting)
8540                            p.mExtras, flags, userId);
8541                    if (pi != null) {
8542                        list.add(pi);
8543                    }
8544                }
8545            }
8546
8547            return new ParceledListSlice<>(list);
8548        }
8549    }
8550
8551    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8552            String[] permissions, boolean[] tmp, int flags, int userId) {
8553        int numMatch = 0;
8554        final PermissionsState permissionsState = ps.getPermissionsState();
8555        for (int i=0; i<permissions.length; i++) {
8556            final String permission = permissions[i];
8557            if (permissionsState.hasPermission(permission, userId)) {
8558                tmp[i] = true;
8559                numMatch++;
8560            } else {
8561                tmp[i] = false;
8562            }
8563        }
8564        if (numMatch == 0) {
8565            return;
8566        }
8567        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8568
8569        // The above might return null in cases of uninstalled apps or install-state
8570        // skew across users/profiles.
8571        if (pi != null) {
8572            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8573                if (numMatch == permissions.length) {
8574                    pi.requestedPermissions = permissions;
8575                } else {
8576                    pi.requestedPermissions = new String[numMatch];
8577                    numMatch = 0;
8578                    for (int i=0; i<permissions.length; i++) {
8579                        if (tmp[i]) {
8580                            pi.requestedPermissions[numMatch] = permissions[i];
8581                            numMatch++;
8582                        }
8583                    }
8584                }
8585            }
8586            list.add(pi);
8587        }
8588    }
8589
8590    @Override
8591    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8592            String[] permissions, int flags, int userId) {
8593        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8594        flags = updateFlagsForPackage(flags, userId, permissions);
8595        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8596                true /* requireFullPermission */, false /* checkShell */,
8597                "get packages holding permissions");
8598        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8599
8600        // writer
8601        synchronized (mPackages) {
8602            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8603            boolean[] tmpBools = new boolean[permissions.length];
8604            if (listUninstalled) {
8605                for (PackageSetting ps : mSettings.mPackages.values()) {
8606                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8607                            userId);
8608                }
8609            } else {
8610                for (PackageParser.Package pkg : mPackages.values()) {
8611                    PackageSetting ps = (PackageSetting)pkg.mExtras;
8612                    if (ps != null) {
8613                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8614                                userId);
8615                    }
8616                }
8617            }
8618
8619            return new ParceledListSlice<PackageInfo>(list);
8620        }
8621    }
8622
8623    @Override
8624    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8625        final int callingUid = Binder.getCallingUid();
8626        if (getInstantAppPackageName(callingUid) != null) {
8627            return ParceledListSlice.emptyList();
8628        }
8629        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8630        flags = updateFlagsForApplication(flags, userId, null);
8631        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8632
8633        // writer
8634        synchronized (mPackages) {
8635            ArrayList<ApplicationInfo> list;
8636            if (listUninstalled) {
8637                list = new ArrayList<>(mSettings.mPackages.size());
8638                for (PackageSetting ps : mSettings.mPackages.values()) {
8639                    ApplicationInfo ai;
8640                    int effectiveFlags = flags;
8641                    if (ps.isSystem()) {
8642                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8643                    }
8644                    if (ps.pkg != null) {
8645                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8646                            continue;
8647                        }
8648                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8649                            continue;
8650                        }
8651                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8652                                ps.readUserState(userId), userId);
8653                        if (ai != null) {
8654                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8655                        }
8656                    } else {
8657                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8658                        // and already converts to externally visible package name
8659                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8660                                callingUid, effectiveFlags, userId);
8661                    }
8662                    if (ai != null) {
8663                        list.add(ai);
8664                    }
8665                }
8666            } else {
8667                list = new ArrayList<>(mPackages.size());
8668                for (PackageParser.Package p : mPackages.values()) {
8669                    if (p.mExtras != null) {
8670                        PackageSetting ps = (PackageSetting) p.mExtras;
8671                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8672                            continue;
8673                        }
8674                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8675                            continue;
8676                        }
8677                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8678                                ps.readUserState(userId), userId);
8679                        if (ai != null) {
8680                            ai.packageName = resolveExternalPackageNameLPr(p);
8681                            list.add(ai);
8682                        }
8683                    }
8684                }
8685            }
8686
8687            return new ParceledListSlice<>(list);
8688        }
8689    }
8690
8691    @Override
8692    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8693        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8694            return null;
8695        }
8696        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8697            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8698                    "getEphemeralApplications");
8699        }
8700        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8701                true /* requireFullPermission */, false /* checkShell */,
8702                "getEphemeralApplications");
8703        synchronized (mPackages) {
8704            List<InstantAppInfo> instantApps = mInstantAppRegistry
8705                    .getInstantAppsLPr(userId);
8706            if (instantApps != null) {
8707                return new ParceledListSlice<>(instantApps);
8708            }
8709        }
8710        return null;
8711    }
8712
8713    @Override
8714    public boolean isInstantApp(String packageName, int userId) {
8715        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8716                true /* requireFullPermission */, false /* checkShell */,
8717                "isInstantApp");
8718        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8719            return false;
8720        }
8721
8722        synchronized (mPackages) {
8723            int callingUid = Binder.getCallingUid();
8724            if (Process.isIsolated(callingUid)) {
8725                callingUid = mIsolatedOwners.get(callingUid);
8726            }
8727            final PackageSetting ps = mSettings.mPackages.get(packageName);
8728            PackageParser.Package pkg = mPackages.get(packageName);
8729            final boolean returnAllowed =
8730                    ps != null
8731                    && (isCallerSameApp(packageName, callingUid)
8732                            || canViewInstantApps(callingUid, userId)
8733                            || mInstantAppRegistry.isInstantAccessGranted(
8734                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8735            if (returnAllowed) {
8736                return ps.getInstantApp(userId);
8737            }
8738        }
8739        return false;
8740    }
8741
8742    @Override
8743    public byte[] getInstantAppCookie(String packageName, int userId) {
8744        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8745            return null;
8746        }
8747
8748        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8749                true /* requireFullPermission */, false /* checkShell */,
8750                "getInstantAppCookie");
8751        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8752            return null;
8753        }
8754        synchronized (mPackages) {
8755            return mInstantAppRegistry.getInstantAppCookieLPw(
8756                    packageName, userId);
8757        }
8758    }
8759
8760    @Override
8761    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8762        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8763            return true;
8764        }
8765
8766        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8767                true /* requireFullPermission */, true /* checkShell */,
8768                "setInstantAppCookie");
8769        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8770            return false;
8771        }
8772        synchronized (mPackages) {
8773            return mInstantAppRegistry.setInstantAppCookieLPw(
8774                    packageName, cookie, userId);
8775        }
8776    }
8777
8778    @Override
8779    public Bitmap getInstantAppIcon(String packageName, int userId) {
8780        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8781            return null;
8782        }
8783
8784        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8785            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8786                    "getInstantAppIcon");
8787        }
8788        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8789                true /* requireFullPermission */, false /* checkShell */,
8790                "getInstantAppIcon");
8791
8792        synchronized (mPackages) {
8793            return mInstantAppRegistry.getInstantAppIconLPw(
8794                    packageName, userId);
8795        }
8796    }
8797
8798    private boolean isCallerSameApp(String packageName, int uid) {
8799        PackageParser.Package pkg = mPackages.get(packageName);
8800        return pkg != null
8801                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8802    }
8803
8804    @Override
8805    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8806        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8807            return ParceledListSlice.emptyList();
8808        }
8809        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8810    }
8811
8812    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8813        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8814
8815        // reader
8816        synchronized (mPackages) {
8817            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8818            final int userId = UserHandle.getCallingUserId();
8819            while (i.hasNext()) {
8820                final PackageParser.Package p = i.next();
8821                if (p.applicationInfo == null) continue;
8822
8823                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8824                        && !p.applicationInfo.isDirectBootAware();
8825                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8826                        && p.applicationInfo.isDirectBootAware();
8827
8828                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8829                        && (!mSafeMode || isSystemApp(p))
8830                        && (matchesUnaware || matchesAware)) {
8831                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8832                    if (ps != null) {
8833                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8834                                ps.readUserState(userId), userId);
8835                        if (ai != null) {
8836                            finalList.add(ai);
8837                        }
8838                    }
8839                }
8840            }
8841        }
8842
8843        return finalList;
8844    }
8845
8846    @Override
8847    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8848        if (!sUserManager.exists(userId)) return null;
8849        flags = updateFlagsForComponent(flags, userId, name);
8850        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8851        // reader
8852        synchronized (mPackages) {
8853            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8854            PackageSetting ps = provider != null
8855                    ? mSettings.mPackages.get(provider.owner.packageName)
8856                    : null;
8857            if (ps != null) {
8858                final boolean isInstantApp = ps.getInstantApp(userId);
8859                // normal application; filter out instant application provider
8860                if (instantAppPkgName == null && isInstantApp) {
8861                    return null;
8862                }
8863                // instant application; filter out other instant applications
8864                if (instantAppPkgName != null
8865                        && isInstantApp
8866                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8867                    return null;
8868                }
8869                // instant application; filter out non-exposed provider
8870                if (instantAppPkgName != null
8871                        && !isInstantApp
8872                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8873                    return null;
8874                }
8875                // provider not enabled
8876                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8877                    return null;
8878                }
8879                return PackageParser.generateProviderInfo(
8880                        provider, flags, ps.readUserState(userId), userId);
8881            }
8882            return null;
8883        }
8884    }
8885
8886    /**
8887     * @deprecated
8888     */
8889    @Deprecated
8890    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8891        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8892            return;
8893        }
8894        // reader
8895        synchronized (mPackages) {
8896            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8897                    .entrySet().iterator();
8898            final int userId = UserHandle.getCallingUserId();
8899            while (i.hasNext()) {
8900                Map.Entry<String, PackageParser.Provider> entry = i.next();
8901                PackageParser.Provider p = entry.getValue();
8902                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8903
8904                if (ps != null && p.syncable
8905                        && (!mSafeMode || (p.info.applicationInfo.flags
8906                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8907                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8908                            ps.readUserState(userId), userId);
8909                    if (info != null) {
8910                        outNames.add(entry.getKey());
8911                        outInfo.add(info);
8912                    }
8913                }
8914            }
8915        }
8916    }
8917
8918    @Override
8919    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8920            int uid, int flags, String metaDataKey) {
8921        final int callingUid = Binder.getCallingUid();
8922        final int userId = processName != null ? UserHandle.getUserId(uid)
8923                : UserHandle.getCallingUserId();
8924        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8925        flags = updateFlagsForComponent(flags, userId, processName);
8926        ArrayList<ProviderInfo> finalList = null;
8927        // reader
8928        synchronized (mPackages) {
8929            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8930            while (i.hasNext()) {
8931                final PackageParser.Provider p = i.next();
8932                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8933                if (ps != null && p.info.authority != null
8934                        && (processName == null
8935                                || (p.info.processName.equals(processName)
8936                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8937                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8938
8939                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8940                    // parameter.
8941                    if (metaDataKey != null
8942                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8943                        continue;
8944                    }
8945                    final ComponentName component =
8946                            new ComponentName(p.info.packageName, p.info.name);
8947                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8948                        continue;
8949                    }
8950                    if (finalList == null) {
8951                        finalList = new ArrayList<ProviderInfo>(3);
8952                    }
8953                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8954                            ps.readUserState(userId), userId);
8955                    if (info != null) {
8956                        finalList.add(info);
8957                    }
8958                }
8959            }
8960        }
8961
8962        if (finalList != null) {
8963            Collections.sort(finalList, mProviderInitOrderSorter);
8964            return new ParceledListSlice<ProviderInfo>(finalList);
8965        }
8966
8967        return ParceledListSlice.emptyList();
8968    }
8969
8970    @Override
8971    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8972        // reader
8973        synchronized (mPackages) {
8974            final int callingUid = Binder.getCallingUid();
8975            final int callingUserId = UserHandle.getUserId(callingUid);
8976            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8977            if (ps == null) return null;
8978            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8979                return null;
8980            }
8981            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8982            return PackageParser.generateInstrumentationInfo(i, flags);
8983        }
8984    }
8985
8986    @Override
8987    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8988            String targetPackage, int flags) {
8989        final int callingUid = Binder.getCallingUid();
8990        final int callingUserId = UserHandle.getUserId(callingUid);
8991        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8992        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8993            return ParceledListSlice.emptyList();
8994        }
8995        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8996    }
8997
8998    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8999            int flags) {
9000        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
9001
9002        // reader
9003        synchronized (mPackages) {
9004            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
9005            while (i.hasNext()) {
9006                final PackageParser.Instrumentation p = i.next();
9007                if (targetPackage == null
9008                        || targetPackage.equals(p.info.targetPackage)) {
9009                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
9010                            flags);
9011                    if (ii != null) {
9012                        finalList.add(ii);
9013                    }
9014                }
9015            }
9016        }
9017
9018        return finalList;
9019    }
9020
9021    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
9022        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
9023        try {
9024            scanDirLI(dir, parseFlags, scanFlags, currentTime);
9025        } finally {
9026            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9027        }
9028    }
9029
9030    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
9031        final File[] files = dir.listFiles();
9032        if (ArrayUtils.isEmpty(files)) {
9033            Log.d(TAG, "No files in app dir " + dir);
9034            return;
9035        }
9036
9037        if (DEBUG_PACKAGE_SCANNING) {
9038            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
9039                    + " flags=0x" + Integer.toHexString(parseFlags));
9040        }
9041        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
9042                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
9043                mParallelPackageParserCallback);
9044
9045        // Submit files for parsing in parallel
9046        int fileCount = 0;
9047        for (File file : files) {
9048            final boolean isPackage = (isApkFile(file) || file.isDirectory())
9049                    && !PackageInstallerService.isStageName(file.getName());
9050            if (!isPackage) {
9051                // Ignore entries which are not packages
9052                continue;
9053            }
9054            parallelPackageParser.submit(file, parseFlags);
9055            fileCount++;
9056        }
9057
9058        // Process results one by one
9059        for (; fileCount > 0; fileCount--) {
9060            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
9061            Throwable throwable = parseResult.throwable;
9062            int errorCode = PackageManager.INSTALL_SUCCEEDED;
9063
9064            if (throwable == null) {
9065                // Static shared libraries have synthetic package names
9066                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
9067                    renameStaticSharedLibraryPackage(parseResult.pkg);
9068                }
9069                try {
9070                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
9071                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
9072                                currentTime, null);
9073                    }
9074                } catch (PackageManagerException e) {
9075                    errorCode = e.error;
9076                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
9077                }
9078            } else if (throwable instanceof PackageParser.PackageParserException) {
9079                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
9080                        throwable;
9081                errorCode = e.error;
9082                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
9083            } else {
9084                throw new IllegalStateException("Unexpected exception occurred while parsing "
9085                        + parseResult.scanFile, throwable);
9086            }
9087
9088            // Delete invalid userdata apps
9089            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
9090                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
9091                logCriticalInfo(Log.WARN,
9092                        "Deleting invalid package at " + parseResult.scanFile);
9093                removeCodePathLI(parseResult.scanFile);
9094            }
9095        }
9096        parallelPackageParser.close();
9097    }
9098
9099    private static File getSettingsProblemFile() {
9100        File dataDir = Environment.getDataDirectory();
9101        File systemDir = new File(dataDir, "system");
9102        File fname = new File(systemDir, "uiderrors.txt");
9103        return fname;
9104    }
9105
9106    static void reportSettingsProblem(int priority, String msg) {
9107        logCriticalInfo(priority, msg);
9108    }
9109
9110    public static void logCriticalInfo(int priority, String msg) {
9111        Slog.println(priority, TAG, msg);
9112        EventLogTags.writePmCriticalInfo(msg);
9113        try {
9114            File fname = getSettingsProblemFile();
9115            FileOutputStream out = new FileOutputStream(fname, true);
9116            PrintWriter pw = new FastPrintWriter(out);
9117            SimpleDateFormat formatter = new SimpleDateFormat();
9118            String dateString = formatter.format(new Date(System.currentTimeMillis()));
9119            pw.println(dateString + ": " + msg);
9120            pw.close();
9121            FileUtils.setPermissions(
9122                    fname.toString(),
9123                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
9124                    -1, -1);
9125        } catch (java.io.IOException e) {
9126        }
9127    }
9128
9129    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
9130        if (srcFile.isDirectory()) {
9131            final File baseFile = new File(pkg.baseCodePath);
9132            long maxModifiedTime = baseFile.lastModified();
9133            if (pkg.splitCodePaths != null) {
9134                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
9135                    final File splitFile = new File(pkg.splitCodePaths[i]);
9136                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
9137                }
9138            }
9139            return maxModifiedTime;
9140        }
9141        return srcFile.lastModified();
9142    }
9143
9144    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
9145            final int policyFlags) throws PackageManagerException {
9146        // When upgrading from pre-N MR1, verify the package time stamp using the package
9147        // directory and not the APK file.
9148        final long lastModifiedTime = mIsPreNMR1Upgrade
9149                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
9150        if (ps != null
9151                && ps.codePath.equals(srcFile)
9152                && ps.timeStamp == lastModifiedTime
9153                && !isCompatSignatureUpdateNeeded(pkg)
9154                && !isRecoverSignatureUpdateNeeded(pkg)) {
9155            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
9156            KeySetManagerService ksms = mSettings.mKeySetManagerService;
9157            ArraySet<PublicKey> signingKs;
9158            synchronized (mPackages) {
9159                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
9160            }
9161            if (ps.signatures.mSignatures != null
9162                    && ps.signatures.mSignatures.length != 0
9163                    && signingKs != null) {
9164                // Optimization: reuse the existing cached certificates
9165                // if the package appears to be unchanged.
9166                pkg.mSignatures = ps.signatures.mSignatures;
9167                pkg.mSigningKeys = signingKs;
9168                return;
9169            }
9170
9171            Slog.w(TAG, "PackageSetting for " + ps.name
9172                    + " is missing signatures.  Collecting certs again to recover them.");
9173        } else {
9174            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
9175        }
9176
9177        try {
9178            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
9179            PackageParser.collectCertificates(pkg, policyFlags);
9180        } catch (PackageParserException e) {
9181            throw PackageManagerException.from(e);
9182        } finally {
9183            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9184        }
9185    }
9186
9187    /**
9188     *  Traces a package scan.
9189     *  @see #scanPackageLI(File, int, int, long, UserHandle)
9190     */
9191    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
9192            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
9193        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
9194        try {
9195            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
9196        } finally {
9197            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9198        }
9199    }
9200
9201    /**
9202     *  Scans a package and returns the newly parsed package.
9203     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
9204     */
9205    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
9206            long currentTime, UserHandle user) throws PackageManagerException {
9207        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
9208        PackageParser pp = new PackageParser();
9209        pp.setSeparateProcesses(mSeparateProcesses);
9210        pp.setOnlyCoreApps(mOnlyCore);
9211        pp.setDisplayMetrics(mMetrics);
9212        pp.setCallback(mPackageParserCallback);
9213
9214        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
9215            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
9216        }
9217
9218        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
9219        final PackageParser.Package pkg;
9220        try {
9221            pkg = pp.parsePackage(scanFile, parseFlags);
9222        } catch (PackageParserException e) {
9223            throw PackageManagerException.from(e);
9224        } finally {
9225            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9226        }
9227
9228        // Static shared libraries have synthetic package names
9229        if (pkg.applicationInfo.isStaticSharedLibrary()) {
9230            renameStaticSharedLibraryPackage(pkg);
9231        }
9232
9233        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
9234    }
9235
9236    /**
9237     *  Scans a package and returns the newly parsed package.
9238     *  @throws PackageManagerException on a parse error.
9239     */
9240    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
9241            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9242            throws PackageManagerException {
9243        // If the package has children and this is the first dive in the function
9244        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
9245        // packages (parent and children) would be successfully scanned before the
9246        // actual scan since scanning mutates internal state and we want to atomically
9247        // install the package and its children.
9248        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9249            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9250                scanFlags |= SCAN_CHECK_ONLY;
9251            }
9252        } else {
9253            scanFlags &= ~SCAN_CHECK_ONLY;
9254        }
9255
9256        // Scan the parent
9257        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
9258                scanFlags, currentTime, user);
9259
9260        // Scan the children
9261        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9262        for (int i = 0; i < childCount; i++) {
9263            PackageParser.Package childPackage = pkg.childPackages.get(i);
9264            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
9265                    currentTime, user);
9266        }
9267
9268
9269        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9270            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
9271        }
9272
9273        return scannedPkg;
9274    }
9275
9276    /**
9277     *  Scans a package and returns the newly parsed package.
9278     *  @throws PackageManagerException on a parse error.
9279     */
9280    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
9281            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9282            throws PackageManagerException {
9283        PackageSetting ps = null;
9284        PackageSetting updatedPkg;
9285        // reader
9286        synchronized (mPackages) {
9287            // Look to see if we already know about this package.
9288            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
9289            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
9290                // This package has been renamed to its original name.  Let's
9291                // use that.
9292                ps = mSettings.getPackageLPr(oldName);
9293            }
9294            // If there was no original package, see one for the real package name.
9295            if (ps == null) {
9296                ps = mSettings.getPackageLPr(pkg.packageName);
9297            }
9298            // Check to see if this package could be hiding/updating a system
9299            // package.  Must look for it either under the original or real
9300            // package name depending on our state.
9301            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
9302            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
9303
9304            // If this is a package we don't know about on the system partition, we
9305            // may need to remove disabled child packages on the system partition
9306            // or may need to not add child packages if the parent apk is updated
9307            // on the data partition and no longer defines this child package.
9308            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
9309                // If this is a parent package for an updated system app and this system
9310                // app got an OTA update which no longer defines some of the child packages
9311                // we have to prune them from the disabled system packages.
9312                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9313                if (disabledPs != null) {
9314                    final int scannedChildCount = (pkg.childPackages != null)
9315                            ? pkg.childPackages.size() : 0;
9316                    final int disabledChildCount = disabledPs.childPackageNames != null
9317                            ? disabledPs.childPackageNames.size() : 0;
9318                    for (int i = 0; i < disabledChildCount; i++) {
9319                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
9320                        boolean disabledPackageAvailable = false;
9321                        for (int j = 0; j < scannedChildCount; j++) {
9322                            PackageParser.Package childPkg = pkg.childPackages.get(j);
9323                            if (childPkg.packageName.equals(disabledChildPackageName)) {
9324                                disabledPackageAvailable = true;
9325                                break;
9326                            }
9327                         }
9328                         if (!disabledPackageAvailable) {
9329                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
9330                         }
9331                    }
9332                }
9333            }
9334        }
9335
9336        final boolean isUpdatedPkg = updatedPkg != null;
9337        final boolean isUpdatedSystemPkg = isUpdatedPkg
9338                && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0;
9339        boolean isUpdatedPkgBetter = false;
9340        // First check if this is a system package that may involve an update
9341        if (isUpdatedSystemPkg) {
9342            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
9343            // it needs to drop FLAG_PRIVILEGED.
9344            if (locationIsPrivileged(scanFile)) {
9345                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9346            } else {
9347                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9348            }
9349
9350            if (ps != null && !ps.codePath.equals(scanFile)) {
9351                // The path has changed from what was last scanned...  check the
9352                // version of the new path against what we have stored to determine
9353                // what to do.
9354                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
9355                if (pkg.mVersionCode <= ps.versionCode) {
9356                    // The system package has been updated and the code path does not match
9357                    // Ignore entry. Skip it.
9358                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
9359                            + " ignored: updated version " + ps.versionCode
9360                            + " better than this " + pkg.mVersionCode);
9361                    if (!updatedPkg.codePath.equals(scanFile)) {
9362                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
9363                                + ps.name + " changing from " + updatedPkg.codePathString
9364                                + " to " + scanFile);
9365                        updatedPkg.codePath = scanFile;
9366                        updatedPkg.codePathString = scanFile.toString();
9367                        updatedPkg.resourcePath = scanFile;
9368                        updatedPkg.resourcePathString = scanFile.toString();
9369                    }
9370                    updatedPkg.pkg = pkg;
9371                    updatedPkg.versionCode = pkg.mVersionCode;
9372
9373                    // Update the disabled system child packages to point to the package too.
9374                    final int childCount = updatedPkg.childPackageNames != null
9375                            ? updatedPkg.childPackageNames.size() : 0;
9376                    for (int i = 0; i < childCount; i++) {
9377                        String childPackageName = updatedPkg.childPackageNames.get(i);
9378                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
9379                                childPackageName);
9380                        if (updatedChildPkg != null) {
9381                            updatedChildPkg.pkg = pkg;
9382                            updatedChildPkg.versionCode = pkg.mVersionCode;
9383                        }
9384                    }
9385                } else {
9386                    // The current app on the system partition is better than
9387                    // what we have updated to on the data partition; switch
9388                    // back to the system partition version.
9389                    // At this point, its safely assumed that package installation for
9390                    // apps in system partition will go through. If not there won't be a working
9391                    // version of the app
9392                    // writer
9393                    synchronized (mPackages) {
9394                        // Just remove the loaded entries from package lists.
9395                        mPackages.remove(ps.name);
9396                    }
9397
9398                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9399                            + " reverting from " + ps.codePathString
9400                            + ": new version " + pkg.mVersionCode
9401                            + " better than installed " + ps.versionCode);
9402
9403                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9404                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9405                    synchronized (mInstallLock) {
9406                        args.cleanUpResourcesLI();
9407                    }
9408                    synchronized (mPackages) {
9409                        mSettings.enableSystemPackageLPw(ps.name);
9410                    }
9411                    isUpdatedPkgBetter = true;
9412                }
9413            }
9414        }
9415
9416        String resourcePath = null;
9417        String baseResourcePath = null;
9418        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) {
9419            if (ps != null && ps.resourcePathString != null) {
9420                resourcePath = ps.resourcePathString;
9421                baseResourcePath = ps.resourcePathString;
9422            } else {
9423                // Should not happen at all. Just log an error.
9424                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9425            }
9426        } else {
9427            resourcePath = pkg.codePath;
9428            baseResourcePath = pkg.baseCodePath;
9429        }
9430
9431        // Set application objects path explicitly.
9432        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9433        pkg.setApplicationInfoCodePath(pkg.codePath);
9434        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9435        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9436        pkg.setApplicationInfoResourcePath(resourcePath);
9437        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9438        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9439
9440        // throw an exception if we have an update to a system application, but, it's not more
9441        // recent than the package we've already scanned
9442        if (isUpdatedSystemPkg && !isUpdatedPkgBetter) {
9443            // Set CPU Abis to application info.
9444            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9445                final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, updatedPkg);
9446                derivePackageAbi(pkg, scanFile, cpuAbiOverride, false, mAppLib32InstallDir);
9447            } else {
9448                pkg.applicationInfo.primaryCpuAbi = updatedPkg.primaryCpuAbiString;
9449                pkg.applicationInfo.secondaryCpuAbi = updatedPkg.secondaryCpuAbiString;
9450            }
9451
9452            throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
9453                    + scanFile + " ignored: updated version " + ps.versionCode
9454                    + " better than this " + pkg.mVersionCode);
9455        }
9456
9457        if (isUpdatedPkg) {
9458            // An updated system app will not have the PARSE_IS_SYSTEM flag set
9459            // initially
9460            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
9461
9462            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
9463            // flag set initially
9464            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9465                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9466            }
9467        }
9468
9469        // Verify certificates against what was last scanned
9470        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
9471
9472        /*
9473         * A new system app appeared, but we already had a non-system one of the
9474         * same name installed earlier.
9475         */
9476        boolean shouldHideSystemApp = false;
9477        if (!isUpdatedPkg && ps != null
9478                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
9479            /*
9480             * Check to make sure the signatures match first. If they don't,
9481             * wipe the installed application and its data.
9482             */
9483            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
9484                    != PackageManager.SIGNATURE_MATCH) {
9485                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
9486                        + " signatures don't match existing userdata copy; removing");
9487                try (PackageFreezer freezer = freezePackage(pkg.packageName,
9488                        "scanPackageInternalLI")) {
9489                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9490                }
9491                ps = null;
9492            } else {
9493                /*
9494                 * If the newly-added system app is an older version than the
9495                 * already installed version, hide it. It will be scanned later
9496                 * and re-added like an update.
9497                 */
9498                if (pkg.mVersionCode <= ps.versionCode) {
9499                    shouldHideSystemApp = true;
9500                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9501                            + " but new version " + pkg.mVersionCode + " better than installed "
9502                            + ps.versionCode + "; hiding system");
9503                } else {
9504                    /*
9505                     * The newly found system app is a newer version that the
9506                     * one previously installed. Simply remove the
9507                     * already-installed application and replace it with our own
9508                     * while keeping the application data.
9509                     */
9510                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9511                            + " reverting from " + ps.codePathString + ": new version "
9512                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
9513                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9514                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9515                    synchronized (mInstallLock) {
9516                        args.cleanUpResourcesLI();
9517                    }
9518                }
9519            }
9520        }
9521
9522        // The apk is forward locked (not public) if its code and resources
9523        // are kept in different files. (except for app in either system or
9524        // vendor path).
9525        // TODO grab this value from PackageSettings
9526        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9527            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9528                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9529            }
9530        }
9531
9532        final int userId = ((user == null) ? 0 : user.getIdentifier());
9533        if (ps != null && ps.getInstantApp(userId)) {
9534            scanFlags |= SCAN_AS_INSTANT_APP;
9535        }
9536        if (ps != null && ps.getVirtulalPreload(userId)) {
9537            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
9538        }
9539
9540        // Note that we invoke the following method only if we are about to unpack an application
9541        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9542                | SCAN_UPDATE_SIGNATURE, currentTime, user);
9543
9544        /*
9545         * If the system app should be overridden by a previously installed
9546         * data, hide the system app now and let the /data/app scan pick it up
9547         * again.
9548         */
9549        if (shouldHideSystemApp) {
9550            synchronized (mPackages) {
9551                mSettings.disableSystemPackageLPw(pkg.packageName, true);
9552            }
9553        }
9554
9555        return scannedPkg;
9556    }
9557
9558    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9559        // Derive the new package synthetic package name
9560        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9561                + pkg.staticSharedLibVersion);
9562    }
9563
9564    private static String fixProcessName(String defProcessName,
9565            String processName) {
9566        if (processName == null) {
9567            return defProcessName;
9568        }
9569        return processName;
9570    }
9571
9572    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9573            throws PackageManagerException {
9574        if (pkgSetting.signatures.mSignatures != null) {
9575            // Already existing package. Make sure signatures match
9576            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9577                    == PackageManager.SIGNATURE_MATCH;
9578            if (!match) {
9579                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9580                        == PackageManager.SIGNATURE_MATCH;
9581            }
9582            if (!match) {
9583                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9584                        == PackageManager.SIGNATURE_MATCH;
9585            }
9586            if (!match) {
9587                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9588                        + pkg.packageName + " signatures do not match the "
9589                        + "previously installed version; ignoring!");
9590            }
9591        }
9592
9593        // Check for shared user signatures
9594        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9595            // Already existing package. Make sure signatures match
9596            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9597                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9598            if (!match) {
9599                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9600                        == PackageManager.SIGNATURE_MATCH;
9601            }
9602            if (!match) {
9603                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9604                        == PackageManager.SIGNATURE_MATCH;
9605            }
9606            if (!match) {
9607                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9608                        "Package " + pkg.packageName
9609                        + " has no signatures that match those in shared user "
9610                        + pkgSetting.sharedUser.name + "; ignoring!");
9611            }
9612        }
9613    }
9614
9615    /**
9616     * Enforces that only the system UID or root's UID can call a method exposed
9617     * via Binder.
9618     *
9619     * @param message used as message if SecurityException is thrown
9620     * @throws SecurityException if the caller is not system or root
9621     */
9622    private static final void enforceSystemOrRoot(String message) {
9623        final int uid = Binder.getCallingUid();
9624        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9625            throw new SecurityException(message);
9626        }
9627    }
9628
9629    @Override
9630    public void performFstrimIfNeeded() {
9631        enforceSystemOrRoot("Only the system can request fstrim");
9632
9633        // Before everything else, see whether we need to fstrim.
9634        try {
9635            IStorageManager sm = PackageHelper.getStorageManager();
9636            if (sm != null) {
9637                boolean doTrim = false;
9638                final long interval = android.provider.Settings.Global.getLong(
9639                        mContext.getContentResolver(),
9640                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9641                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9642                if (interval > 0) {
9643                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9644                    if (timeSinceLast > interval) {
9645                        doTrim = true;
9646                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9647                                + "; running immediately");
9648                    }
9649                }
9650                if (doTrim) {
9651                    final boolean dexOptDialogShown;
9652                    synchronized (mPackages) {
9653                        dexOptDialogShown = mDexOptDialogShown;
9654                    }
9655                    if (!isFirstBoot() && dexOptDialogShown) {
9656                        try {
9657                            ActivityManager.getService().showBootMessage(
9658                                    mContext.getResources().getString(
9659                                            R.string.android_upgrading_fstrim), true);
9660                        } catch (RemoteException e) {
9661                        }
9662                    }
9663                    sm.runMaintenance();
9664                }
9665            } else {
9666                Slog.e(TAG, "storageManager service unavailable!");
9667            }
9668        } catch (RemoteException e) {
9669            // Can't happen; StorageManagerService is local
9670        }
9671    }
9672
9673    @Override
9674    public void updatePackagesIfNeeded() {
9675        enforceSystemOrRoot("Only the system can request package update");
9676
9677        // We need to re-extract after an OTA.
9678        boolean causeUpgrade = isUpgrade();
9679
9680        // First boot or factory reset.
9681        // Note: we also handle devices that are upgrading to N right now as if it is their
9682        //       first boot, as they do not have profile data.
9683        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9684
9685        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9686        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9687
9688        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9689            return;
9690        }
9691
9692        List<PackageParser.Package> pkgs;
9693        synchronized (mPackages) {
9694            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9695        }
9696
9697        final long startTime = System.nanoTime();
9698        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9699                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
9700                    false /* bootComplete */);
9701
9702        final int elapsedTimeSeconds =
9703                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9704
9705        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9706        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9707        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9708        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9709        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9710    }
9711
9712    /*
9713     * Return the prebuilt profile path given a package base code path.
9714     */
9715    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
9716        return pkg.baseCodePath + ".prof";
9717    }
9718
9719    /**
9720     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9721     * containing statistics about the invocation. The array consists of three elements,
9722     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9723     * and {@code numberOfPackagesFailed}.
9724     */
9725    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9726            String compilerFilter, boolean bootComplete) {
9727
9728        int numberOfPackagesVisited = 0;
9729        int numberOfPackagesOptimized = 0;
9730        int numberOfPackagesSkipped = 0;
9731        int numberOfPackagesFailed = 0;
9732        final int numberOfPackagesToDexopt = pkgs.size();
9733
9734        for (PackageParser.Package pkg : pkgs) {
9735            numberOfPackagesVisited++;
9736
9737            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9738                // Copy over initial preopt profiles since we won't get any JIT samples for methods
9739                // that are already compiled.
9740                File profileFile = new File(getPrebuildProfilePath(pkg));
9741                // Copy profile if it exists.
9742                if (profileFile.exists()) {
9743                    try {
9744                        // We could also do this lazily before calling dexopt in
9745                        // PackageDexOptimizer to prevent this happening on first boot. The issue
9746                        // is that we don't have a good way to say "do this only once".
9747                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9748                                pkg.applicationInfo.uid, pkg.packageName)) {
9749                            Log.e(TAG, "Installer failed to copy system profile!");
9750                        }
9751                    } catch (Exception e) {
9752                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9753                                e);
9754                    }
9755                }
9756            }
9757
9758            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9759                if (DEBUG_DEXOPT) {
9760                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9761                }
9762                numberOfPackagesSkipped++;
9763                continue;
9764            }
9765
9766            if (DEBUG_DEXOPT) {
9767                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9768                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9769            }
9770
9771            if (showDialog) {
9772                try {
9773                    ActivityManager.getService().showBootMessage(
9774                            mContext.getResources().getString(R.string.android_upgrading_apk,
9775                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9776                } catch (RemoteException e) {
9777                }
9778                synchronized (mPackages) {
9779                    mDexOptDialogShown = true;
9780                }
9781            }
9782
9783            // checkProfiles is false to avoid merging profiles during boot which
9784            // might interfere with background compilation (b/28612421).
9785            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9786            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9787            // trade-off worth doing to save boot time work.
9788            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9789            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9790                    pkg.packageName,
9791                    compilerFilter,
9792                    dexoptFlags));
9793
9794            if (pkg.isSystemApp()) {
9795                // Only dexopt shared secondary dex files belonging to system apps to not slow down
9796                // too much boot after an OTA.
9797                int secondaryDexoptFlags = dexoptFlags |
9798                        DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9799                        DexoptOptions.DEXOPT_ONLY_SHARED_DEX;
9800                mDexManager.dexoptSecondaryDex(new DexoptOptions(
9801                        pkg.packageName,
9802                        compilerFilter,
9803                        secondaryDexoptFlags));
9804            }
9805
9806            // TODO(shubhamajmera): Record secondary dexopt stats.
9807            switch (primaryDexOptStaus) {
9808                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9809                    numberOfPackagesOptimized++;
9810                    break;
9811                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9812                    numberOfPackagesSkipped++;
9813                    break;
9814                case PackageDexOptimizer.DEX_OPT_FAILED:
9815                    numberOfPackagesFailed++;
9816                    break;
9817                default:
9818                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9819                    break;
9820            }
9821        }
9822
9823        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9824                numberOfPackagesFailed };
9825    }
9826
9827    @Override
9828    public void notifyPackageUse(String packageName, int reason) {
9829        synchronized (mPackages) {
9830            final int callingUid = Binder.getCallingUid();
9831            final int callingUserId = UserHandle.getUserId(callingUid);
9832            if (getInstantAppPackageName(callingUid) != null) {
9833                if (!isCallerSameApp(packageName, callingUid)) {
9834                    return;
9835                }
9836            } else {
9837                if (isInstantApp(packageName, callingUserId)) {
9838                    return;
9839                }
9840            }
9841            notifyPackageUseLocked(packageName, reason);
9842        }
9843    }
9844
9845    private void notifyPackageUseLocked(String packageName, int reason) {
9846        final PackageParser.Package p = mPackages.get(packageName);
9847        if (p == null) {
9848            return;
9849        }
9850        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9851    }
9852
9853    @Override
9854    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9855            List<String> classPaths, String loaderIsa) {
9856        int userId = UserHandle.getCallingUserId();
9857        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9858        if (ai == null) {
9859            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9860                + loadingPackageName + ", user=" + userId);
9861            return;
9862        }
9863        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9864    }
9865
9866    @Override
9867    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9868            IDexModuleRegisterCallback callback) {
9869        int userId = UserHandle.getCallingUserId();
9870        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9871        DexManager.RegisterDexModuleResult result;
9872        if (ai == null) {
9873            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9874                     " calling user. package=" + packageName + ", user=" + userId);
9875            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9876        } else {
9877            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9878        }
9879
9880        if (callback != null) {
9881            mHandler.post(() -> {
9882                try {
9883                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9884                } catch (RemoteException e) {
9885                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9886                }
9887            });
9888        }
9889    }
9890
9891    /**
9892     * Ask the package manager to perform a dex-opt with the given compiler filter.
9893     *
9894     * Note: exposed only for the shell command to allow moving packages explicitly to a
9895     *       definite state.
9896     */
9897    @Override
9898    public boolean performDexOptMode(String packageName,
9899            boolean checkProfiles, String targetCompilerFilter, boolean force,
9900            boolean bootComplete, String splitName) {
9901        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9902                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9903                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9904        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
9905                splitName, flags));
9906    }
9907
9908    /**
9909     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9910     * secondary dex files belonging to the given package.
9911     *
9912     * Note: exposed only for the shell command to allow moving packages explicitly to a
9913     *       definite state.
9914     */
9915    @Override
9916    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9917            boolean force) {
9918        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9919                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9920                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9921                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9922        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9923    }
9924
9925    /*package*/ boolean performDexOpt(DexoptOptions options) {
9926        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9927            return false;
9928        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9929            return false;
9930        }
9931
9932        if (options.isDexoptOnlySecondaryDex()) {
9933            return mDexManager.dexoptSecondaryDex(options);
9934        } else {
9935            int dexoptStatus = performDexOptWithStatus(options);
9936            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9937        }
9938    }
9939
9940    /**
9941     * Perform dexopt on the given package and return one of following result:
9942     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9943     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9944     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9945     */
9946    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9947        return performDexOptTraced(options);
9948    }
9949
9950    private int performDexOptTraced(DexoptOptions options) {
9951        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9952        try {
9953            return performDexOptInternal(options);
9954        } finally {
9955            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9956        }
9957    }
9958
9959    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9960    // if the package can now be considered up to date for the given filter.
9961    private int performDexOptInternal(DexoptOptions options) {
9962        PackageParser.Package p;
9963        synchronized (mPackages) {
9964            p = mPackages.get(options.getPackageName());
9965            if (p == null) {
9966                // Package could not be found. Report failure.
9967                return PackageDexOptimizer.DEX_OPT_FAILED;
9968            }
9969            mPackageUsage.maybeWriteAsync(mPackages);
9970            mCompilerStats.maybeWriteAsync();
9971        }
9972        long callingId = Binder.clearCallingIdentity();
9973        try {
9974            synchronized (mInstallLock) {
9975                return performDexOptInternalWithDependenciesLI(p, options);
9976            }
9977        } finally {
9978            Binder.restoreCallingIdentity(callingId);
9979        }
9980    }
9981
9982    public ArraySet<String> getOptimizablePackages() {
9983        ArraySet<String> pkgs = new ArraySet<String>();
9984        synchronized (mPackages) {
9985            for (PackageParser.Package p : mPackages.values()) {
9986                if (PackageDexOptimizer.canOptimizePackage(p)) {
9987                    pkgs.add(p.packageName);
9988                }
9989            }
9990        }
9991        return pkgs;
9992    }
9993
9994    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9995            DexoptOptions options) {
9996        // Select the dex optimizer based on the force parameter.
9997        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9998        //       allocate an object here.
9999        PackageDexOptimizer pdo = options.isForce()
10000                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
10001                : mPackageDexOptimizer;
10002
10003        // Dexopt all dependencies first. Note: we ignore the return value and march on
10004        // on errors.
10005        // Note that we are going to call performDexOpt on those libraries as many times as
10006        // they are referenced in packages. When we do a batch of performDexOpt (for example
10007        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
10008        // and the first package that uses the library will dexopt it. The
10009        // others will see that the compiled code for the library is up to date.
10010        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
10011        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
10012        if (!deps.isEmpty()) {
10013            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
10014                    options.getCompilerFilter(), options.getSplitName(),
10015                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
10016            for (PackageParser.Package depPackage : deps) {
10017                // TODO: Analyze and investigate if we (should) profile libraries.
10018                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
10019                        getOrCreateCompilerPackageStats(depPackage),
10020                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
10021            }
10022        }
10023        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
10024                getOrCreateCompilerPackageStats(p),
10025                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
10026    }
10027
10028    /**
10029     * Reconcile the information we have about the secondary dex files belonging to
10030     * {@code packagName} and the actual dex files. For all dex files that were
10031     * deleted, update the internal records and delete the generated oat files.
10032     */
10033    @Override
10034    public void reconcileSecondaryDexFiles(String packageName) {
10035        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
10036            return;
10037        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
10038            return;
10039        }
10040        mDexManager.reconcileSecondaryDexFiles(packageName);
10041    }
10042
10043    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
10044    // a reference there.
10045    /*package*/ DexManager getDexManager() {
10046        return mDexManager;
10047    }
10048
10049    /**
10050     * Execute the background dexopt job immediately.
10051     */
10052    @Override
10053    public boolean runBackgroundDexoptJob() {
10054        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
10055            return false;
10056        }
10057        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
10058    }
10059
10060    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
10061        if (p.usesLibraries != null || p.usesOptionalLibraries != null
10062                || p.usesStaticLibraries != null) {
10063            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
10064            Set<String> collectedNames = new HashSet<>();
10065            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
10066
10067            retValue.remove(p);
10068
10069            return retValue;
10070        } else {
10071            return Collections.emptyList();
10072        }
10073    }
10074
10075    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
10076            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
10077        if (!collectedNames.contains(p.packageName)) {
10078            collectedNames.add(p.packageName);
10079            collected.add(p);
10080
10081            if (p.usesLibraries != null) {
10082                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
10083                        null, collected, collectedNames);
10084            }
10085            if (p.usesOptionalLibraries != null) {
10086                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
10087                        null, collected, collectedNames);
10088            }
10089            if (p.usesStaticLibraries != null) {
10090                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
10091                        p.usesStaticLibrariesVersions, collected, collectedNames);
10092            }
10093        }
10094    }
10095
10096    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
10097            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
10098        final int libNameCount = libs.size();
10099        for (int i = 0; i < libNameCount; i++) {
10100            String libName = libs.get(i);
10101            int version = (versions != null && versions.length == libNameCount)
10102                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
10103            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
10104            if (libPkg != null) {
10105                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
10106            }
10107        }
10108    }
10109
10110    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
10111        synchronized (mPackages) {
10112            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
10113            if (libEntry != null) {
10114                return mPackages.get(libEntry.apk);
10115            }
10116            return null;
10117        }
10118    }
10119
10120    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
10121        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10122        if (versionedLib == null) {
10123            return null;
10124        }
10125        return versionedLib.get(version);
10126    }
10127
10128    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
10129        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10130                pkg.staticSharedLibName);
10131        if (versionedLib == null) {
10132            return null;
10133        }
10134        int previousLibVersion = -1;
10135        final int versionCount = versionedLib.size();
10136        for (int i = 0; i < versionCount; i++) {
10137            final int libVersion = versionedLib.keyAt(i);
10138            if (libVersion < pkg.staticSharedLibVersion) {
10139                previousLibVersion = Math.max(previousLibVersion, libVersion);
10140            }
10141        }
10142        if (previousLibVersion >= 0) {
10143            return versionedLib.get(previousLibVersion);
10144        }
10145        return null;
10146    }
10147
10148    public void shutdown() {
10149        mPackageUsage.writeNow(mPackages);
10150        mCompilerStats.writeNow();
10151        mDexManager.writePackageDexUsageNow();
10152    }
10153
10154    @Override
10155    public void dumpProfiles(String packageName) {
10156        PackageParser.Package pkg;
10157        synchronized (mPackages) {
10158            pkg = mPackages.get(packageName);
10159            if (pkg == null) {
10160                throw new IllegalArgumentException("Unknown package: " + packageName);
10161            }
10162        }
10163        /* Only the shell, root, or the app user should be able to dump profiles. */
10164        int callingUid = Binder.getCallingUid();
10165        if (callingUid != Process.SHELL_UID &&
10166            callingUid != Process.ROOT_UID &&
10167            callingUid != pkg.applicationInfo.uid) {
10168            throw new SecurityException("dumpProfiles");
10169        }
10170
10171        synchronized (mInstallLock) {
10172            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
10173            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
10174            try {
10175                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
10176                String codePaths = TextUtils.join(";", allCodePaths);
10177                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
10178            } catch (InstallerException e) {
10179                Slog.w(TAG, "Failed to dump profiles", e);
10180            }
10181            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10182        }
10183    }
10184
10185    @Override
10186    public void forceDexOpt(String packageName) {
10187        enforceSystemOrRoot("forceDexOpt");
10188
10189        PackageParser.Package pkg;
10190        synchronized (mPackages) {
10191            pkg = mPackages.get(packageName);
10192            if (pkg == null) {
10193                throw new IllegalArgumentException("Unknown package: " + packageName);
10194            }
10195        }
10196
10197        synchronized (mInstallLock) {
10198            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
10199
10200            // Whoever is calling forceDexOpt wants a compiled package.
10201            // Don't use profiles since that may cause compilation to be skipped.
10202            final int res = performDexOptInternalWithDependenciesLI(
10203                    pkg,
10204                    new DexoptOptions(packageName,
10205                            getDefaultCompilerFilter(),
10206                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
10207
10208            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10209            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
10210                throw new IllegalStateException("Failed to dexopt: " + res);
10211            }
10212        }
10213    }
10214
10215    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
10216        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
10217            Slog.w(TAG, "Unable to update from " + oldPkg.name
10218                    + " to " + newPkg.packageName
10219                    + ": old package not in system partition");
10220            return false;
10221        } else if (mPackages.get(oldPkg.name) != null) {
10222            Slog.w(TAG, "Unable to update from " + oldPkg.name
10223                    + " to " + newPkg.packageName
10224                    + ": old package still exists");
10225            return false;
10226        }
10227        return true;
10228    }
10229
10230    void removeCodePathLI(File codePath) {
10231        if (codePath.isDirectory()) {
10232            try {
10233                mInstaller.rmPackageDir(codePath.getAbsolutePath());
10234            } catch (InstallerException e) {
10235                Slog.w(TAG, "Failed to remove code path", e);
10236            }
10237        } else {
10238            codePath.delete();
10239        }
10240    }
10241
10242    private int[] resolveUserIds(int userId) {
10243        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
10244    }
10245
10246    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10247        if (pkg == null) {
10248            Slog.wtf(TAG, "Package was null!", new Throwable());
10249            return;
10250        }
10251        clearAppDataLeafLIF(pkg, userId, flags);
10252        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10253        for (int i = 0; i < childCount; i++) {
10254            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10255        }
10256    }
10257
10258    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10259        final PackageSetting ps;
10260        synchronized (mPackages) {
10261            ps = mSettings.mPackages.get(pkg.packageName);
10262        }
10263        for (int realUserId : resolveUserIds(userId)) {
10264            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10265            try {
10266                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10267                        ceDataInode);
10268            } catch (InstallerException e) {
10269                Slog.w(TAG, String.valueOf(e));
10270            }
10271        }
10272    }
10273
10274    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10275        if (pkg == null) {
10276            Slog.wtf(TAG, "Package was null!", new Throwable());
10277            return;
10278        }
10279        destroyAppDataLeafLIF(pkg, userId, flags);
10280        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10281        for (int i = 0; i < childCount; i++) {
10282            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10283        }
10284    }
10285
10286    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10287        final PackageSetting ps;
10288        synchronized (mPackages) {
10289            ps = mSettings.mPackages.get(pkg.packageName);
10290        }
10291        for (int realUserId : resolveUserIds(userId)) {
10292            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10293            try {
10294                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10295                        ceDataInode);
10296            } catch (InstallerException e) {
10297                Slog.w(TAG, String.valueOf(e));
10298            }
10299            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
10300        }
10301    }
10302
10303    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
10304        if (pkg == null) {
10305            Slog.wtf(TAG, "Package was null!", new Throwable());
10306            return;
10307        }
10308        destroyAppProfilesLeafLIF(pkg);
10309        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10310        for (int i = 0; i < childCount; i++) {
10311            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
10312        }
10313    }
10314
10315    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
10316        try {
10317            mInstaller.destroyAppProfiles(pkg.packageName);
10318        } catch (InstallerException e) {
10319            Slog.w(TAG, String.valueOf(e));
10320        }
10321    }
10322
10323    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
10324        if (pkg == null) {
10325            Slog.wtf(TAG, "Package was null!", new Throwable());
10326            return;
10327        }
10328        clearAppProfilesLeafLIF(pkg);
10329        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10330        for (int i = 0; i < childCount; i++) {
10331            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
10332        }
10333    }
10334
10335    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
10336        try {
10337            mInstaller.clearAppProfiles(pkg.packageName);
10338        } catch (InstallerException e) {
10339            Slog.w(TAG, String.valueOf(e));
10340        }
10341    }
10342
10343    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
10344            long lastUpdateTime) {
10345        // Set parent install/update time
10346        PackageSetting ps = (PackageSetting) pkg.mExtras;
10347        if (ps != null) {
10348            ps.firstInstallTime = firstInstallTime;
10349            ps.lastUpdateTime = lastUpdateTime;
10350        }
10351        // Set children install/update time
10352        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10353        for (int i = 0; i < childCount; i++) {
10354            PackageParser.Package childPkg = pkg.childPackages.get(i);
10355            ps = (PackageSetting) childPkg.mExtras;
10356            if (ps != null) {
10357                ps.firstInstallTime = firstInstallTime;
10358                ps.lastUpdateTime = lastUpdateTime;
10359            }
10360        }
10361    }
10362
10363    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
10364            PackageParser.Package changingLib) {
10365        if (file.path != null) {
10366            usesLibraryFiles.add(file.path);
10367            return;
10368        }
10369        PackageParser.Package p = mPackages.get(file.apk);
10370        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
10371            // If we are doing this while in the middle of updating a library apk,
10372            // then we need to make sure to use that new apk for determining the
10373            // dependencies here.  (We haven't yet finished committing the new apk
10374            // to the package manager state.)
10375            if (p == null || p.packageName.equals(changingLib.packageName)) {
10376                p = changingLib;
10377            }
10378        }
10379        if (p != null) {
10380            usesLibraryFiles.addAll(p.getAllCodePaths());
10381            if (p.usesLibraryFiles != null) {
10382                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
10383            }
10384        }
10385    }
10386
10387    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
10388            PackageParser.Package changingLib) throws PackageManagerException {
10389        if (pkg == null) {
10390            return;
10391        }
10392        ArraySet<String> usesLibraryFiles = null;
10393        if (pkg.usesLibraries != null) {
10394            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
10395                    null, null, pkg.packageName, changingLib, true,
10396                    pkg.applicationInfo.targetSdkVersion, null);
10397        }
10398        if (pkg.usesStaticLibraries != null) {
10399            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
10400                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
10401                    pkg.packageName, changingLib, true,
10402                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
10403        }
10404        if (pkg.usesOptionalLibraries != null) {
10405            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
10406                    null, null, pkg.packageName, changingLib, false,
10407                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
10408        }
10409        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
10410            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
10411        } else {
10412            pkg.usesLibraryFiles = null;
10413        }
10414    }
10415
10416    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
10417            @Nullable int[] requiredVersions, @Nullable String[][] requiredCertDigests,
10418            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
10419            boolean required, int targetSdk, @Nullable ArraySet<String> outUsedLibraries)
10420            throws PackageManagerException {
10421        final int libCount = requestedLibraries.size();
10422        for (int i = 0; i < libCount; i++) {
10423            final String libName = requestedLibraries.get(i);
10424            final int libVersion = requiredVersions != null ? requiredVersions[i]
10425                    : SharedLibraryInfo.VERSION_UNDEFINED;
10426            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
10427            if (libEntry == null) {
10428                if (required) {
10429                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10430                            "Package " + packageName + " requires unavailable shared library "
10431                                    + libName + "; failing!");
10432                } else if (DEBUG_SHARED_LIBRARIES) {
10433                    Slog.i(TAG, "Package " + packageName
10434                            + " desires unavailable shared library "
10435                            + libName + "; ignoring!");
10436                }
10437            } else {
10438                if (requiredVersions != null && requiredCertDigests != null) {
10439                    if (libEntry.info.getVersion() != requiredVersions[i]) {
10440                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10441                            "Package " + packageName + " requires unavailable static shared"
10442                                    + " library " + libName + " version "
10443                                    + libEntry.info.getVersion() + "; failing!");
10444                    }
10445
10446                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
10447                    if (libPkg == null) {
10448                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10449                                "Package " + packageName + " requires unavailable static shared"
10450                                        + " library; failing!");
10451                    }
10452
10453                    final String[] expectedCertDigests = requiredCertDigests[i];
10454                    // For apps targeting O MR1 we require explicit enumeration of all certs.
10455                    final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
10456                            ? PackageUtils.computeSignaturesSha256Digests(libPkg.mSignatures)
10457                            : PackageUtils.computeSignaturesSha256Digests(
10458                                    new Signature[]{libPkg.mSignatures[0]});
10459
10460                    // Take a shortcut if sizes don't match. Note that if an app doesn't
10461                    // target O we don't parse the "additional-certificate" tags similarly
10462                    // how we only consider all certs only for apps targeting O (see above).
10463                    // Therefore, the size check is safe to make.
10464                    if (expectedCertDigests.length != libCertDigests.length) {
10465                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10466                                "Package " + packageName + " requires differently signed" +
10467                                        " static sDexLoadReporter.java:45.19hared library; failing!");
10468                    }
10469
10470                    // Use a predictable order as signature order may vary
10471                    Arrays.sort(libCertDigests);
10472                    Arrays.sort(expectedCertDigests);
10473
10474                    final int certCount = libCertDigests.length;
10475                    for (int j = 0; j < certCount; j++) {
10476                        if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
10477                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10478                                    "Package " + packageName + " requires differently signed" +
10479                                            " static shared library; failing!");
10480                        }
10481                    }
10482                }
10483
10484                if (outUsedLibraries == null) {
10485                    outUsedLibraries = new ArraySet<>();
10486                }
10487                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
10488            }
10489        }
10490        return outUsedLibraries;
10491    }
10492
10493    private static boolean hasString(List<String> list, List<String> which) {
10494        if (list == null) {
10495            return false;
10496        }
10497        for (int i=list.size()-1; i>=0; i--) {
10498            for (int j=which.size()-1; j>=0; j--) {
10499                if (which.get(j).equals(list.get(i))) {
10500                    return true;
10501                }
10502            }
10503        }
10504        return false;
10505    }
10506
10507    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
10508            PackageParser.Package changingPkg) {
10509        ArrayList<PackageParser.Package> res = null;
10510        for (PackageParser.Package pkg : mPackages.values()) {
10511            if (changingPkg != null
10512                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
10513                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
10514                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
10515                            changingPkg.staticSharedLibName)) {
10516                return null;
10517            }
10518            if (res == null) {
10519                res = new ArrayList<>();
10520            }
10521            res.add(pkg);
10522            try {
10523                updateSharedLibrariesLPr(pkg, changingPkg);
10524            } catch (PackageManagerException e) {
10525                // If a system app update or an app and a required lib missing we
10526                // delete the package and for updated system apps keep the data as
10527                // it is better for the user to reinstall than to be in an limbo
10528                // state. Also libs disappearing under an app should never happen
10529                // - just in case.
10530                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
10531                    final int flags = pkg.isUpdatedSystemApp()
10532                            ? PackageManager.DELETE_KEEP_DATA : 0;
10533                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
10534                            flags , null, true, null);
10535                }
10536                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
10537            }
10538        }
10539        return res;
10540    }
10541
10542    /**
10543     * Derive the value of the {@code cpuAbiOverride} based on the provided
10544     * value and an optional stored value from the package settings.
10545     */
10546    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
10547        String cpuAbiOverride = null;
10548
10549        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10550            cpuAbiOverride = null;
10551        } else if (abiOverride != null) {
10552            cpuAbiOverride = abiOverride;
10553        } else if (settings != null) {
10554            cpuAbiOverride = settings.cpuAbiOverrideString;
10555        }
10556
10557        return cpuAbiOverride;
10558    }
10559
10560    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10561            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10562                    throws PackageManagerException {
10563        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10564        // If the package has children and this is the first dive in the function
10565        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10566        // whether all packages (parent and children) would be successfully scanned
10567        // before the actual scan since scanning mutates internal state and we want
10568        // to atomically install the package and its children.
10569        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10570            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10571                scanFlags |= SCAN_CHECK_ONLY;
10572            }
10573        } else {
10574            scanFlags &= ~SCAN_CHECK_ONLY;
10575        }
10576
10577        final PackageParser.Package scannedPkg;
10578        try {
10579            // Scan the parent
10580            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10581            // Scan the children
10582            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10583            for (int i = 0; i < childCount; i++) {
10584                PackageParser.Package childPkg = pkg.childPackages.get(i);
10585                scanPackageLI(childPkg, policyFlags,
10586                        scanFlags, currentTime, user);
10587            }
10588        } finally {
10589            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10590        }
10591
10592        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10593            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10594        }
10595
10596        return scannedPkg;
10597    }
10598
10599    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10600            int scanFlags, long currentTime, @Nullable UserHandle user)
10601                    throws PackageManagerException {
10602        boolean success = false;
10603        try {
10604            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10605                    currentTime, user);
10606            success = true;
10607            return res;
10608        } finally {
10609            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10610                // DELETE_DATA_ON_FAILURES is only used by frozen paths
10611                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10612                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10613                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10614            }
10615        }
10616    }
10617
10618    /**
10619     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10620     */
10621    private static boolean apkHasCode(String fileName) {
10622        StrictJarFile jarFile = null;
10623        try {
10624            jarFile = new StrictJarFile(fileName,
10625                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10626            return jarFile.findEntry("classes.dex") != null;
10627        } catch (IOException ignore) {
10628        } finally {
10629            try {
10630                if (jarFile != null) {
10631                    jarFile.close();
10632                }
10633            } catch (IOException ignore) {}
10634        }
10635        return false;
10636    }
10637
10638    /**
10639     * Enforces code policy for the package. This ensures that if an APK has
10640     * declared hasCode="true" in its manifest that the APK actually contains
10641     * code.
10642     *
10643     * @throws PackageManagerException If bytecode could not be found when it should exist
10644     */
10645    private static void assertCodePolicy(PackageParser.Package pkg)
10646            throws PackageManagerException {
10647        final boolean shouldHaveCode =
10648                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10649        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10650            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10651                    "Package " + pkg.baseCodePath + " code is missing");
10652        }
10653
10654        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10655            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10656                final boolean splitShouldHaveCode =
10657                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10658                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10659                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10660                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10661                }
10662            }
10663        }
10664    }
10665
10666    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10667            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10668                    throws PackageManagerException {
10669        if (DEBUG_PACKAGE_SCANNING) {
10670            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10671                Log.d(TAG, "Scanning package " + pkg.packageName);
10672        }
10673
10674        applyPolicy(pkg, policyFlags);
10675
10676        assertPackageIsValid(pkg, policyFlags, scanFlags);
10677
10678        // Initialize package source and resource directories
10679        final File scanFile = new File(pkg.codePath);
10680        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10681        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10682
10683        SharedUserSetting suid = null;
10684        PackageSetting pkgSetting = null;
10685
10686        // Getting the package setting may have a side-effect, so if we
10687        // are only checking if scan would succeed, stash a copy of the
10688        // old setting to restore at the end.
10689        PackageSetting nonMutatedPs = null;
10690
10691        // We keep references to the derived CPU Abis from settings in oder to reuse
10692        // them in the case where we're not upgrading or booting for the first time.
10693        String primaryCpuAbiFromSettings = null;
10694        String secondaryCpuAbiFromSettings = null;
10695
10696        // writer
10697        synchronized (mPackages) {
10698            if (pkg.mSharedUserId != null) {
10699                // SIDE EFFECTS; may potentially allocate a new shared user
10700                suid = mSettings.getSharedUserLPw(
10701                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10702                if (DEBUG_PACKAGE_SCANNING) {
10703                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10704                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10705                                + "): packages=" + suid.packages);
10706                }
10707            }
10708
10709            // Check if we are renaming from an original package name.
10710            PackageSetting origPackage = null;
10711            String realName = null;
10712            if (pkg.mOriginalPackages != null) {
10713                // This package may need to be renamed to a previously
10714                // installed name.  Let's check on that...
10715                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10716                if (pkg.mOriginalPackages.contains(renamed)) {
10717                    // This package had originally been installed as the
10718                    // original name, and we have already taken care of
10719                    // transitioning to the new one.  Just update the new
10720                    // one to continue using the old name.
10721                    realName = pkg.mRealPackage;
10722                    if (!pkg.packageName.equals(renamed)) {
10723                        // Callers into this function may have already taken
10724                        // care of renaming the package; only do it here if
10725                        // it is not already done.
10726                        pkg.setPackageName(renamed);
10727                    }
10728                } else {
10729                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10730                        if ((origPackage = mSettings.getPackageLPr(
10731                                pkg.mOriginalPackages.get(i))) != null) {
10732                            // We do have the package already installed under its
10733                            // original name...  should we use it?
10734                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10735                                // New package is not compatible with original.
10736                                origPackage = null;
10737                                continue;
10738                            } else if (origPackage.sharedUser != null) {
10739                                // Make sure uid is compatible between packages.
10740                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10741                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10742                                            + " to " + pkg.packageName + ": old uid "
10743                                            + origPackage.sharedUser.name
10744                                            + " differs from " + pkg.mSharedUserId);
10745                                    origPackage = null;
10746                                    continue;
10747                                }
10748                                // TODO: Add case when shared user id is added [b/28144775]
10749                            } else {
10750                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10751                                        + pkg.packageName + " to old name " + origPackage.name);
10752                            }
10753                            break;
10754                        }
10755                    }
10756                }
10757            }
10758
10759            if (mTransferedPackages.contains(pkg.packageName)) {
10760                Slog.w(TAG, "Package " + pkg.packageName
10761                        + " was transferred to another, but its .apk remains");
10762            }
10763
10764            // See comments in nonMutatedPs declaration
10765            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10766                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10767                if (foundPs != null) {
10768                    nonMutatedPs = new PackageSetting(foundPs);
10769                }
10770            }
10771
10772            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10773                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10774                if (foundPs != null) {
10775                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10776                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10777                }
10778            }
10779
10780            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10781            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10782                PackageManagerService.reportSettingsProblem(Log.WARN,
10783                        "Package " + pkg.packageName + " shared user changed from "
10784                                + (pkgSetting.sharedUser != null
10785                                        ? pkgSetting.sharedUser.name : "<nothing>")
10786                                + " to "
10787                                + (suid != null ? suid.name : "<nothing>")
10788                                + "; replacing with new");
10789                pkgSetting = null;
10790            }
10791            final PackageSetting oldPkgSetting =
10792                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10793            final PackageSetting disabledPkgSetting =
10794                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10795
10796            String[] usesStaticLibraries = null;
10797            if (pkg.usesStaticLibraries != null) {
10798                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10799                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10800            }
10801
10802            if (pkgSetting == null) {
10803                final String parentPackageName = (pkg.parentPackage != null)
10804                        ? pkg.parentPackage.packageName : null;
10805                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10806                final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10807                // REMOVE SharedUserSetting from method; update in a separate call
10808                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10809                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10810                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10811                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10812                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10813                        true /*allowInstall*/, instantApp, virtualPreload,
10814                        parentPackageName, pkg.getChildPackageNames(),
10815                        UserManagerService.getInstance(), usesStaticLibraries,
10816                        pkg.usesStaticLibrariesVersions);
10817                // SIDE EFFECTS; updates system state; move elsewhere
10818                if (origPackage != null) {
10819                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10820                }
10821                mSettings.addUserToSettingLPw(pkgSetting);
10822            } else {
10823                // REMOVE SharedUserSetting from method; update in a separate call.
10824                //
10825                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10826                // secondaryCpuAbi are not known at this point so we always update them
10827                // to null here, only to reset them at a later point.
10828                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10829                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10830                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10831                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10832                        UserManagerService.getInstance(), usesStaticLibraries,
10833                        pkg.usesStaticLibrariesVersions);
10834            }
10835            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10836            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10837
10838            // SIDE EFFECTS; modifies system state; move elsewhere
10839            if (pkgSetting.origPackage != null) {
10840                // If we are first transitioning from an original package,
10841                // fix up the new package's name now.  We need to do this after
10842                // looking up the package under its new name, so getPackageLP
10843                // can take care of fiddling things correctly.
10844                pkg.setPackageName(origPackage.name);
10845
10846                // File a report about this.
10847                String msg = "New package " + pkgSetting.realName
10848                        + " renamed to replace old package " + pkgSetting.name;
10849                reportSettingsProblem(Log.WARN, msg);
10850
10851                // Make a note of it.
10852                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10853                    mTransferedPackages.add(origPackage.name);
10854                }
10855
10856                // No longer need to retain this.
10857                pkgSetting.origPackage = null;
10858            }
10859
10860            // SIDE EFFECTS; modifies system state; move elsewhere
10861            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10862                // Make a note of it.
10863                mTransferedPackages.add(pkg.packageName);
10864            }
10865
10866            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10867                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10868            }
10869
10870            if ((scanFlags & SCAN_BOOTING) == 0
10871                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10872                // Check all shared libraries and map to their actual file path.
10873                // We only do this here for apps not on a system dir, because those
10874                // are the only ones that can fail an install due to this.  We
10875                // will take care of the system apps by updating all of their
10876                // library paths after the scan is done. Also during the initial
10877                // scan don't update any libs as we do this wholesale after all
10878                // apps are scanned to avoid dependency based scanning.
10879                updateSharedLibrariesLPr(pkg, null);
10880            }
10881
10882            if (mFoundPolicyFile) {
10883                SELinuxMMAC.assignSeInfoValue(pkg);
10884            }
10885            pkg.applicationInfo.uid = pkgSetting.appId;
10886            pkg.mExtras = pkgSetting;
10887
10888
10889            // Static shared libs have same package with different versions where
10890            // we internally use a synthetic package name to allow multiple versions
10891            // of the same package, therefore we need to compare signatures against
10892            // the package setting for the latest library version.
10893            PackageSetting signatureCheckPs = pkgSetting;
10894            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10895                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10896                if (libraryEntry != null) {
10897                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10898                }
10899            }
10900
10901            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10902                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10903                    // We just determined the app is signed correctly, so bring
10904                    // over the latest parsed certs.
10905                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10906                } else {
10907                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10908                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10909                                "Package " + pkg.packageName + " upgrade keys do not match the "
10910                                + "previously installed version");
10911                    } else {
10912                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10913                        String msg = "System package " + pkg.packageName
10914                                + " signature changed; retaining data.";
10915                        reportSettingsProblem(Log.WARN, msg);
10916                    }
10917                }
10918            } else {
10919                try {
10920                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10921                    verifySignaturesLP(signatureCheckPs, pkg);
10922                    // We just determined the app is signed correctly, so bring
10923                    // over the latest parsed certs.
10924                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10925                } catch (PackageManagerException e) {
10926                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10927                        throw e;
10928                    }
10929                    // The signature has changed, but this package is in the system
10930                    // image...  let's recover!
10931                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10932                    // However...  if this package is part of a shared user, but it
10933                    // doesn't match the signature of the shared user, let's fail.
10934                    // What this means is that you can't change the signatures
10935                    // associated with an overall shared user, which doesn't seem all
10936                    // that unreasonable.
10937                    if (signatureCheckPs.sharedUser != null) {
10938                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10939                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10940                            throw new PackageManagerException(
10941                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10942                                    "Signature mismatch for shared user: "
10943                                            + pkgSetting.sharedUser);
10944                        }
10945                    }
10946                    // File a report about this.
10947                    String msg = "System package " + pkg.packageName
10948                            + " signature changed; retaining data.";
10949                    reportSettingsProblem(Log.WARN, msg);
10950                }
10951            }
10952
10953            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10954                // This package wants to adopt ownership of permissions from
10955                // another package.
10956                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10957                    final String origName = pkg.mAdoptPermissions.get(i);
10958                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10959                    if (orig != null) {
10960                        if (verifyPackageUpdateLPr(orig, pkg)) {
10961                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10962                                    + pkg.packageName);
10963                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10964                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
10965                        }
10966                    }
10967                }
10968            }
10969        }
10970
10971        pkg.applicationInfo.processName = fixProcessName(
10972                pkg.applicationInfo.packageName,
10973                pkg.applicationInfo.processName);
10974
10975        if (pkg != mPlatformPackage) {
10976            // Get all of our default paths setup
10977            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10978        }
10979
10980        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10981
10982        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10983            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10984                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10985                final boolean extractNativeLibs = !pkg.isLibrary();
10986                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
10987                        mAppLib32InstallDir);
10988                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10989
10990                // Some system apps still use directory structure for native libraries
10991                // in which case we might end up not detecting abi solely based on apk
10992                // structure. Try to detect abi based on directory structure.
10993                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10994                        pkg.applicationInfo.primaryCpuAbi == null) {
10995                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10996                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10997                }
10998            } else {
10999                // This is not a first boot or an upgrade, don't bother deriving the
11000                // ABI during the scan. Instead, trust the value that was stored in the
11001                // package setting.
11002                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
11003                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
11004
11005                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
11006
11007                if (DEBUG_ABI_SELECTION) {
11008                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
11009                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
11010                        pkg.applicationInfo.secondaryCpuAbi);
11011                }
11012            }
11013        } else {
11014            if ((scanFlags & SCAN_MOVE) != 0) {
11015                // We haven't run dex-opt for this move (since we've moved the compiled output too)
11016                // but we already have this packages package info in the PackageSetting. We just
11017                // use that and derive the native library path based on the new codepath.
11018                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
11019                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
11020            }
11021
11022            // Set native library paths again. For moves, the path will be updated based on the
11023            // ABIs we've determined above. For non-moves, the path will be updated based on the
11024            // ABIs we determined during compilation, but the path will depend on the final
11025            // package path (after the rename away from the stage path).
11026            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
11027        }
11028
11029        // This is a special case for the "system" package, where the ABI is
11030        // dictated by the zygote configuration (and init.rc). We should keep track
11031        // of this ABI so that we can deal with "normal" applications that run under
11032        // the same UID correctly.
11033        if (mPlatformPackage == pkg) {
11034            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
11035                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
11036        }
11037
11038        // If there's a mismatch between the abi-override in the package setting
11039        // and the abiOverride specified for the install. Warn about this because we
11040        // would've already compiled the app without taking the package setting into
11041        // account.
11042        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
11043            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
11044                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
11045                        " for package " + pkg.packageName);
11046            }
11047        }
11048
11049        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11050        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11051        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
11052
11053        // Copy the derived override back to the parsed package, so that we can
11054        // update the package settings accordingly.
11055        pkg.cpuAbiOverride = cpuAbiOverride;
11056
11057        if (DEBUG_ABI_SELECTION) {
11058            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
11059                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
11060                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
11061        }
11062
11063        // Push the derived path down into PackageSettings so we know what to
11064        // clean up at uninstall time.
11065        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
11066
11067        if (DEBUG_ABI_SELECTION) {
11068            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
11069                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
11070                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
11071        }
11072
11073        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
11074        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
11075            // We don't do this here during boot because we can do it all
11076            // at once after scanning all existing packages.
11077            //
11078            // We also do this *before* we perform dexopt on this package, so that
11079            // we can avoid redundant dexopts, and also to make sure we've got the
11080            // code and package path correct.
11081            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
11082        }
11083
11084        if (mFactoryTest && pkg.requestedPermissions.contains(
11085                android.Manifest.permission.FACTORY_TEST)) {
11086            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
11087        }
11088
11089        if (isSystemApp(pkg)) {
11090            pkgSetting.isOrphaned = true;
11091        }
11092
11093        // Take care of first install / last update times.
11094        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
11095        if (currentTime != 0) {
11096            if (pkgSetting.firstInstallTime == 0) {
11097                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
11098            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
11099                pkgSetting.lastUpdateTime = currentTime;
11100            }
11101        } else if (pkgSetting.firstInstallTime == 0) {
11102            // We need *something*.  Take time time stamp of the file.
11103            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
11104        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
11105            if (scanFileTime != pkgSetting.timeStamp) {
11106                // A package on the system image has changed; consider this
11107                // to be an update.
11108                pkgSetting.lastUpdateTime = scanFileTime;
11109            }
11110        }
11111        pkgSetting.setTimeStamp(scanFileTime);
11112
11113        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
11114            if (nonMutatedPs != null) {
11115                synchronized (mPackages) {
11116                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
11117                }
11118            }
11119        } else {
11120            final int userId = user == null ? 0 : user.getIdentifier();
11121            // Modify state for the given package setting
11122            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
11123                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
11124            if (pkgSetting.getInstantApp(userId)) {
11125                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
11126            }
11127        }
11128        return pkg;
11129    }
11130
11131    /**
11132     * Applies policy to the parsed package based upon the given policy flags.
11133     * Ensures the package is in a good state.
11134     * <p>
11135     * Implementation detail: This method must NOT have any side effect. It would
11136     * ideally be static, but, it requires locks to read system state.
11137     */
11138    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
11139        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
11140            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
11141            if (pkg.applicationInfo.isDirectBootAware()) {
11142                // we're direct boot aware; set for all components
11143                for (PackageParser.Service s : pkg.services) {
11144                    s.info.encryptionAware = s.info.directBootAware = true;
11145                }
11146                for (PackageParser.Provider p : pkg.providers) {
11147                    p.info.encryptionAware = p.info.directBootAware = true;
11148                }
11149                for (PackageParser.Activity a : pkg.activities) {
11150                    a.info.encryptionAware = a.info.directBootAware = true;
11151                }
11152                for (PackageParser.Activity r : pkg.receivers) {
11153                    r.info.encryptionAware = r.info.directBootAware = true;
11154                }
11155            }
11156            if (compressedFileExists(pkg.codePath)) {
11157                pkg.isStub = true;
11158            }
11159        } else {
11160            // Only allow system apps to be flagged as core apps.
11161            pkg.coreApp = false;
11162            // clear flags not applicable to regular apps
11163            pkg.applicationInfo.privateFlags &=
11164                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
11165            pkg.applicationInfo.privateFlags &=
11166                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
11167        }
11168        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
11169
11170        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
11171            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
11172        }
11173
11174        if (!isSystemApp(pkg)) {
11175            // Only system apps can use these features.
11176            pkg.mOriginalPackages = null;
11177            pkg.mRealPackage = null;
11178            pkg.mAdoptPermissions = null;
11179        }
11180    }
11181
11182    /**
11183     * Asserts the parsed package is valid according to the given policy. If the
11184     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
11185     * <p>
11186     * Implementation detail: This method must NOT have any side effects. It would
11187     * ideally be static, but, it requires locks to read system state.
11188     *
11189     * @throws PackageManagerException If the package fails any of the validation checks
11190     */
11191    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
11192            throws PackageManagerException {
11193        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
11194            assertCodePolicy(pkg);
11195        }
11196
11197        if (pkg.applicationInfo.getCodePath() == null ||
11198                pkg.applicationInfo.getResourcePath() == null) {
11199            // Bail out. The resource and code paths haven't been set.
11200            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
11201                    "Code and resource paths haven't been set correctly");
11202        }
11203
11204        // Make sure we're not adding any bogus keyset info
11205        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11206        ksms.assertScannedPackageValid(pkg);
11207
11208        synchronized (mPackages) {
11209            // The special "android" package can only be defined once
11210            if (pkg.packageName.equals("android")) {
11211                if (mAndroidApplication != null) {
11212                    Slog.w(TAG, "*************************************************");
11213                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
11214                    Slog.w(TAG, " codePath=" + pkg.codePath);
11215                    Slog.w(TAG, "*************************************************");
11216                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11217                            "Core android package being redefined.  Skipping.");
11218                }
11219            }
11220
11221            // A package name must be unique; don't allow duplicates
11222            if (mPackages.containsKey(pkg.packageName)) {
11223                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11224                        "Application package " + pkg.packageName
11225                        + " already installed.  Skipping duplicate.");
11226            }
11227
11228            if (pkg.applicationInfo.isStaticSharedLibrary()) {
11229                // Static libs have a synthetic package name containing the version
11230                // but we still want the base name to be unique.
11231                if (mPackages.containsKey(pkg.manifestPackageName)) {
11232                    throw new PackageManagerException(
11233                            "Duplicate static shared lib provider package");
11234                }
11235
11236                // Static shared libraries should have at least O target SDK
11237                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
11238                    throw new PackageManagerException(
11239                            "Packages declaring static-shared libs must target O SDK or higher");
11240                }
11241
11242                // Package declaring static a shared lib cannot be instant apps
11243                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11244                    throw new PackageManagerException(
11245                            "Packages declaring static-shared libs cannot be instant apps");
11246                }
11247
11248                // Package declaring static a shared lib cannot be renamed since the package
11249                // name is synthetic and apps can't code around package manager internals.
11250                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
11251                    throw new PackageManagerException(
11252                            "Packages declaring static-shared libs cannot be renamed");
11253                }
11254
11255                // Package declaring static a shared lib cannot declare child packages
11256                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
11257                    throw new PackageManagerException(
11258                            "Packages declaring static-shared libs cannot have child packages");
11259                }
11260
11261                // Package declaring static a shared lib cannot declare dynamic libs
11262                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
11263                    throw new PackageManagerException(
11264                            "Packages declaring static-shared libs cannot declare dynamic libs");
11265                }
11266
11267                // Package declaring static a shared lib cannot declare shared users
11268                if (pkg.mSharedUserId != null) {
11269                    throw new PackageManagerException(
11270                            "Packages declaring static-shared libs cannot declare shared users");
11271                }
11272
11273                // Static shared libs cannot declare activities
11274                if (!pkg.activities.isEmpty()) {
11275                    throw new PackageManagerException(
11276                            "Static shared libs cannot declare activities");
11277                }
11278
11279                // Static shared libs cannot declare services
11280                if (!pkg.services.isEmpty()) {
11281                    throw new PackageManagerException(
11282                            "Static shared libs cannot declare services");
11283                }
11284
11285                // Static shared libs cannot declare providers
11286                if (!pkg.providers.isEmpty()) {
11287                    throw new PackageManagerException(
11288                            "Static shared libs cannot declare content providers");
11289                }
11290
11291                // Static shared libs cannot declare receivers
11292                if (!pkg.receivers.isEmpty()) {
11293                    throw new PackageManagerException(
11294                            "Static shared libs cannot declare broadcast receivers");
11295                }
11296
11297                // Static shared libs cannot declare permission groups
11298                if (!pkg.permissionGroups.isEmpty()) {
11299                    throw new PackageManagerException(
11300                            "Static shared libs cannot declare permission groups");
11301                }
11302
11303                // Static shared libs cannot declare permissions
11304                if (!pkg.permissions.isEmpty()) {
11305                    throw new PackageManagerException(
11306                            "Static shared libs cannot declare permissions");
11307                }
11308
11309                // Static shared libs cannot declare protected broadcasts
11310                if (pkg.protectedBroadcasts != null) {
11311                    throw new PackageManagerException(
11312                            "Static shared libs cannot declare protected broadcasts");
11313                }
11314
11315                // Static shared libs cannot be overlay targets
11316                if (pkg.mOverlayTarget != null) {
11317                    throw new PackageManagerException(
11318                            "Static shared libs cannot be overlay targets");
11319                }
11320
11321                // The version codes must be ordered as lib versions
11322                int minVersionCode = Integer.MIN_VALUE;
11323                int maxVersionCode = Integer.MAX_VALUE;
11324
11325                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
11326                        pkg.staticSharedLibName);
11327                if (versionedLib != null) {
11328                    final int versionCount = versionedLib.size();
11329                    for (int i = 0; i < versionCount; i++) {
11330                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
11331                        final int libVersionCode = libInfo.getDeclaringPackage()
11332                                .getVersionCode();
11333                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
11334                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
11335                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
11336                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
11337                        } else {
11338                            minVersionCode = maxVersionCode = libVersionCode;
11339                            break;
11340                        }
11341                    }
11342                }
11343                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
11344                    throw new PackageManagerException("Static shared"
11345                            + " lib version codes must be ordered as lib versions");
11346                }
11347            }
11348
11349            // Only privileged apps and updated privileged apps can add child packages.
11350            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
11351                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
11352                    throw new PackageManagerException("Only privileged apps can add child "
11353                            + "packages. Ignoring package " + pkg.packageName);
11354                }
11355                final int childCount = pkg.childPackages.size();
11356                for (int i = 0; i < childCount; i++) {
11357                    PackageParser.Package childPkg = pkg.childPackages.get(i);
11358                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
11359                            childPkg.packageName)) {
11360                        throw new PackageManagerException("Can't override child of "
11361                                + "another disabled app. Ignoring package " + pkg.packageName);
11362                    }
11363                }
11364            }
11365
11366            // If we're only installing presumed-existing packages, require that the
11367            // scanned APK is both already known and at the path previously established
11368            // for it.  Previously unknown packages we pick up normally, but if we have an
11369            // a priori expectation about this package's install presence, enforce it.
11370            // With a singular exception for new system packages. When an OTA contains
11371            // a new system package, we allow the codepath to change from a system location
11372            // to the user-installed location. If we don't allow this change, any newer,
11373            // user-installed version of the application will be ignored.
11374            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
11375                if (mExpectingBetter.containsKey(pkg.packageName)) {
11376                    logCriticalInfo(Log.WARN,
11377                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
11378                } else {
11379                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
11380                    if (known != null) {
11381                        if (DEBUG_PACKAGE_SCANNING) {
11382                            Log.d(TAG, "Examining " + pkg.codePath
11383                                    + " and requiring known paths " + known.codePathString
11384                                    + " & " + known.resourcePathString);
11385                        }
11386                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
11387                                || !pkg.applicationInfo.getResourcePath().equals(
11388                                        known.resourcePathString)) {
11389                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
11390                                    "Application package " + pkg.packageName
11391                                    + " found at " + pkg.applicationInfo.getCodePath()
11392                                    + " but expected at " + known.codePathString
11393                                    + "; ignoring.");
11394                        }
11395                    } else {
11396                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11397                                "Application package " + pkg.packageName
11398                                + " not found; ignoring.");
11399                    }
11400                }
11401            }
11402
11403            // Verify that this new package doesn't have any content providers
11404            // that conflict with existing packages.  Only do this if the
11405            // package isn't already installed, since we don't want to break
11406            // things that are installed.
11407            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
11408                final int N = pkg.providers.size();
11409                int i;
11410                for (i=0; i<N; i++) {
11411                    PackageParser.Provider p = pkg.providers.get(i);
11412                    if (p.info.authority != null) {
11413                        String names[] = p.info.authority.split(";");
11414                        for (int j = 0; j < names.length; j++) {
11415                            if (mProvidersByAuthority.containsKey(names[j])) {
11416                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11417                                final String otherPackageName =
11418                                        ((other != null && other.getComponentName() != null) ?
11419                                                other.getComponentName().getPackageName() : "?");
11420                                throw new PackageManagerException(
11421                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11422                                        "Can't install because provider name " + names[j]
11423                                                + " (in package " + pkg.applicationInfo.packageName
11424                                                + ") is already used by " + otherPackageName);
11425                            }
11426                        }
11427                    }
11428                }
11429            }
11430        }
11431    }
11432
11433    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
11434            int type, String declaringPackageName, int declaringVersionCode) {
11435        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11436        if (versionedLib == null) {
11437            versionedLib = new SparseArray<>();
11438            mSharedLibraries.put(name, versionedLib);
11439            if (type == SharedLibraryInfo.TYPE_STATIC) {
11440                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11441            }
11442        } else if (versionedLib.indexOfKey(version) >= 0) {
11443            return false;
11444        }
11445        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11446                version, type, declaringPackageName, declaringVersionCode);
11447        versionedLib.put(version, libEntry);
11448        return true;
11449    }
11450
11451    private boolean removeSharedLibraryLPw(String name, int version) {
11452        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11453        if (versionedLib == null) {
11454            return false;
11455        }
11456        final int libIdx = versionedLib.indexOfKey(version);
11457        if (libIdx < 0) {
11458            return false;
11459        }
11460        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11461        versionedLib.remove(version);
11462        if (versionedLib.size() <= 0) {
11463            mSharedLibraries.remove(name);
11464            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11465                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11466                        .getPackageName());
11467            }
11468        }
11469        return true;
11470    }
11471
11472    /**
11473     * Adds a scanned package to the system. When this method is finished, the package will
11474     * be available for query, resolution, etc...
11475     */
11476    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11477            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
11478        final String pkgName = pkg.packageName;
11479        if (mCustomResolverComponentName != null &&
11480                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11481            setUpCustomResolverActivity(pkg);
11482        }
11483
11484        if (pkg.packageName.equals("android")) {
11485            synchronized (mPackages) {
11486                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11487                    // Set up information for our fall-back user intent resolution activity.
11488                    mPlatformPackage = pkg;
11489                    pkg.mVersionCode = mSdkVersion;
11490                    mAndroidApplication = pkg.applicationInfo;
11491                    if (!mResolverReplaced) {
11492                        mResolveActivity.applicationInfo = mAndroidApplication;
11493                        mResolveActivity.name = ResolverActivity.class.getName();
11494                        mResolveActivity.packageName = mAndroidApplication.packageName;
11495                        mResolveActivity.processName = "system:ui";
11496                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11497                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11498                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11499                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11500                        mResolveActivity.exported = true;
11501                        mResolveActivity.enabled = true;
11502                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11503                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11504                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11505                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11506                                | ActivityInfo.CONFIG_ORIENTATION
11507                                | ActivityInfo.CONFIG_KEYBOARD
11508                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11509                        mResolveInfo.activityInfo = mResolveActivity;
11510                        mResolveInfo.priority = 0;
11511                        mResolveInfo.preferredOrder = 0;
11512                        mResolveInfo.match = 0;
11513                        mResolveComponentName = new ComponentName(
11514                                mAndroidApplication.packageName, mResolveActivity.name);
11515                    }
11516                }
11517            }
11518        }
11519
11520        ArrayList<PackageParser.Package> clientLibPkgs = null;
11521        // writer
11522        synchronized (mPackages) {
11523            boolean hasStaticSharedLibs = false;
11524
11525            // Any app can add new static shared libraries
11526            if (pkg.staticSharedLibName != null) {
11527                // Static shared libs don't allow renaming as they have synthetic package
11528                // names to allow install of multiple versions, so use name from manifest.
11529                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11530                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11531                        pkg.manifestPackageName, pkg.mVersionCode)) {
11532                    hasStaticSharedLibs = true;
11533                } else {
11534                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11535                                + pkg.staticSharedLibName + " already exists; skipping");
11536                }
11537                // Static shared libs cannot be updated once installed since they
11538                // use synthetic package name which includes the version code, so
11539                // not need to update other packages's shared lib dependencies.
11540            }
11541
11542            if (!hasStaticSharedLibs
11543                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11544                // Only system apps can add new dynamic shared libraries.
11545                if (pkg.libraryNames != null) {
11546                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11547                        String name = pkg.libraryNames.get(i);
11548                        boolean allowed = false;
11549                        if (pkg.isUpdatedSystemApp()) {
11550                            // New library entries can only be added through the
11551                            // system image.  This is important to get rid of a lot
11552                            // of nasty edge cases: for example if we allowed a non-
11553                            // system update of the app to add a library, then uninstalling
11554                            // the update would make the library go away, and assumptions
11555                            // we made such as through app install filtering would now
11556                            // have allowed apps on the device which aren't compatible
11557                            // with it.  Better to just have the restriction here, be
11558                            // conservative, and create many fewer cases that can negatively
11559                            // impact the user experience.
11560                            final PackageSetting sysPs = mSettings
11561                                    .getDisabledSystemPkgLPr(pkg.packageName);
11562                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11563                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11564                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11565                                        allowed = true;
11566                                        break;
11567                                    }
11568                                }
11569                            }
11570                        } else {
11571                            allowed = true;
11572                        }
11573                        if (allowed) {
11574                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11575                                    SharedLibraryInfo.VERSION_UNDEFINED,
11576                                    SharedLibraryInfo.TYPE_DYNAMIC,
11577                                    pkg.packageName, pkg.mVersionCode)) {
11578                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11579                                        + name + " already exists; skipping");
11580                            }
11581                        } else {
11582                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11583                                    + name + " that is not declared on system image; skipping");
11584                        }
11585                    }
11586
11587                    if ((scanFlags & SCAN_BOOTING) == 0) {
11588                        // If we are not booting, we need to update any applications
11589                        // that are clients of our shared library.  If we are booting,
11590                        // this will all be done once the scan is complete.
11591                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11592                    }
11593                }
11594            }
11595        }
11596
11597        if ((scanFlags & SCAN_BOOTING) != 0) {
11598            // No apps can run during boot scan, so they don't need to be frozen
11599        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11600            // Caller asked to not kill app, so it's probably not frozen
11601        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11602            // Caller asked us to ignore frozen check for some reason; they
11603            // probably didn't know the package name
11604        } else {
11605            // We're doing major surgery on this package, so it better be frozen
11606            // right now to keep it from launching
11607            checkPackageFrozen(pkgName);
11608        }
11609
11610        // Also need to kill any apps that are dependent on the library.
11611        if (clientLibPkgs != null) {
11612            for (int i=0; i<clientLibPkgs.size(); i++) {
11613                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11614                killApplication(clientPkg.applicationInfo.packageName,
11615                        clientPkg.applicationInfo.uid, "update lib");
11616            }
11617        }
11618
11619        // writer
11620        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11621
11622        synchronized (mPackages) {
11623            // We don't expect installation to fail beyond this point
11624
11625            // Add the new setting to mSettings
11626            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11627            // Add the new setting to mPackages
11628            mPackages.put(pkg.applicationInfo.packageName, pkg);
11629            // Make sure we don't accidentally delete its data.
11630            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11631            while (iter.hasNext()) {
11632                PackageCleanItem item = iter.next();
11633                if (pkgName.equals(item.packageName)) {
11634                    iter.remove();
11635                }
11636            }
11637
11638            // Add the package's KeySets to the global KeySetManagerService
11639            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11640            ksms.addScannedPackageLPw(pkg);
11641
11642            int N = pkg.providers.size();
11643            StringBuilder r = null;
11644            int i;
11645            for (i=0; i<N; i++) {
11646                PackageParser.Provider p = pkg.providers.get(i);
11647                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11648                        p.info.processName);
11649                mProviders.addProvider(p);
11650                p.syncable = p.info.isSyncable;
11651                if (p.info.authority != null) {
11652                    String names[] = p.info.authority.split(";");
11653                    p.info.authority = null;
11654                    for (int j = 0; j < names.length; j++) {
11655                        if (j == 1 && p.syncable) {
11656                            // We only want the first authority for a provider to possibly be
11657                            // syncable, so if we already added this provider using a different
11658                            // authority clear the syncable flag. We copy the provider before
11659                            // changing it because the mProviders object contains a reference
11660                            // to a provider that we don't want to change.
11661                            // Only do this for the second authority since the resulting provider
11662                            // object can be the same for all future authorities for this provider.
11663                            p = new PackageParser.Provider(p);
11664                            p.syncable = false;
11665                        }
11666                        if (!mProvidersByAuthority.containsKey(names[j])) {
11667                            mProvidersByAuthority.put(names[j], p);
11668                            if (p.info.authority == null) {
11669                                p.info.authority = names[j];
11670                            } else {
11671                                p.info.authority = p.info.authority + ";" + names[j];
11672                            }
11673                            if (DEBUG_PACKAGE_SCANNING) {
11674                                if (chatty)
11675                                    Log.d(TAG, "Registered content provider: " + names[j]
11676                                            + ", className = " + p.info.name + ", isSyncable = "
11677                                            + p.info.isSyncable);
11678                            }
11679                        } else {
11680                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11681                            Slog.w(TAG, "Skipping provider name " + names[j] +
11682                                    " (in package " + pkg.applicationInfo.packageName +
11683                                    "): name already used by "
11684                                    + ((other != null && other.getComponentName() != null)
11685                                            ? other.getComponentName().getPackageName() : "?"));
11686                        }
11687                    }
11688                }
11689                if (chatty) {
11690                    if (r == null) {
11691                        r = new StringBuilder(256);
11692                    } else {
11693                        r.append(' ');
11694                    }
11695                    r.append(p.info.name);
11696                }
11697            }
11698            if (r != null) {
11699                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11700            }
11701
11702            N = pkg.services.size();
11703            r = null;
11704            for (i=0; i<N; i++) {
11705                PackageParser.Service s = pkg.services.get(i);
11706                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11707                        s.info.processName);
11708                mServices.addService(s);
11709                if (chatty) {
11710                    if (r == null) {
11711                        r = new StringBuilder(256);
11712                    } else {
11713                        r.append(' ');
11714                    }
11715                    r.append(s.info.name);
11716                }
11717            }
11718            if (r != null) {
11719                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11720            }
11721
11722            N = pkg.receivers.size();
11723            r = null;
11724            for (i=0; i<N; i++) {
11725                PackageParser.Activity a = pkg.receivers.get(i);
11726                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11727                        a.info.processName);
11728                mReceivers.addActivity(a, "receiver");
11729                if (chatty) {
11730                    if (r == null) {
11731                        r = new StringBuilder(256);
11732                    } else {
11733                        r.append(' ');
11734                    }
11735                    r.append(a.info.name);
11736                }
11737            }
11738            if (r != null) {
11739                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11740            }
11741
11742            N = pkg.activities.size();
11743            r = null;
11744            for (i=0; i<N; i++) {
11745                PackageParser.Activity a = pkg.activities.get(i);
11746                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11747                        a.info.processName);
11748                mActivities.addActivity(a, "activity");
11749                if (chatty) {
11750                    if (r == null) {
11751                        r = new StringBuilder(256);
11752                    } else {
11753                        r.append(' ');
11754                    }
11755                    r.append(a.info.name);
11756                }
11757            }
11758            if (r != null) {
11759                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11760            }
11761
11762            N = pkg.permissionGroups.size();
11763            r = null;
11764            for (i=0; i<N; i++) {
11765                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11766                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11767                final String curPackageName = cur == null ? null : cur.info.packageName;
11768                // Dont allow ephemeral apps to define new permission groups.
11769                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11770                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11771                            + pg.info.packageName
11772                            + " ignored: instant apps cannot define new permission groups.");
11773                    continue;
11774                }
11775                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11776                if (cur == null || isPackageUpdate) {
11777                    mPermissionGroups.put(pg.info.name, pg);
11778                    if (chatty) {
11779                        if (r == null) {
11780                            r = new StringBuilder(256);
11781                        } else {
11782                            r.append(' ');
11783                        }
11784                        if (isPackageUpdate) {
11785                            r.append("UPD:");
11786                        }
11787                        r.append(pg.info.name);
11788                    }
11789                } else {
11790                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11791                            + pg.info.packageName + " ignored: original from "
11792                            + cur.info.packageName);
11793                    if (chatty) {
11794                        if (r == null) {
11795                            r = new StringBuilder(256);
11796                        } else {
11797                            r.append(' ');
11798                        }
11799                        r.append("DUP:");
11800                        r.append(pg.info.name);
11801                    }
11802                }
11803            }
11804            if (r != null) {
11805                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11806            }
11807
11808            N = pkg.permissions.size();
11809            r = null;
11810            for (i=0; i<N; i++) {
11811                PackageParser.Permission p = pkg.permissions.get(i);
11812
11813                // Dont allow ephemeral apps to define new permissions.
11814                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11815                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11816                            + p.info.packageName
11817                            + " ignored: instant apps cannot define new permissions.");
11818                    continue;
11819                }
11820
11821                // Assume by default that we did not install this permission into the system.
11822                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11823
11824                // Now that permission groups have a special meaning, we ignore permission
11825                // groups for legacy apps to prevent unexpected behavior. In particular,
11826                // permissions for one app being granted to someone just because they happen
11827                // to be in a group defined by another app (before this had no implications).
11828                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11829                    p.group = mPermissionGroups.get(p.info.group);
11830                    // Warn for a permission in an unknown group.
11831                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11832                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11833                                + p.info.packageName + " in an unknown group " + p.info.group);
11834                    }
11835                }
11836
11837                ArrayMap<String, BasePermission> permissionMap =
11838                        p.tree ? mSettings.mPermissionTrees
11839                                : mSettings.mPermissions;
11840                BasePermission bp = permissionMap.get(p.info.name);
11841
11842                // Allow system apps to redefine non-system permissions
11843                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11844                    final boolean currentOwnerIsSystem = (bp.perm != null
11845                            && isSystemApp(bp.perm.owner));
11846                    if (isSystemApp(p.owner)) {
11847                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11848                            // It's a built-in permission and no owner, take ownership now
11849                            bp.packageSetting = pkgSetting;
11850                            bp.perm = p;
11851                            bp.uid = pkg.applicationInfo.uid;
11852                            bp.sourcePackage = p.info.packageName;
11853                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11854                        } else if (!currentOwnerIsSystem) {
11855                            String msg = "New decl " + p.owner + " of permission  "
11856                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
11857                            reportSettingsProblem(Log.WARN, msg);
11858                            bp = null;
11859                        }
11860                    }
11861                }
11862
11863                if (bp == null) {
11864                    bp = new BasePermission(p.info.name, p.info.packageName,
11865                            BasePermission.TYPE_NORMAL);
11866                    permissionMap.put(p.info.name, bp);
11867                }
11868
11869                if (bp.perm == null) {
11870                    if (bp.sourcePackage == null
11871                            || bp.sourcePackage.equals(p.info.packageName)) {
11872                        BasePermission tree = findPermissionTreeLP(p.info.name);
11873                        if (tree == null
11874                                || tree.sourcePackage.equals(p.info.packageName)) {
11875                            bp.packageSetting = pkgSetting;
11876                            bp.perm = p;
11877                            bp.uid = pkg.applicationInfo.uid;
11878                            bp.sourcePackage = p.info.packageName;
11879                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11880                            if (chatty) {
11881                                if (r == null) {
11882                                    r = new StringBuilder(256);
11883                                } else {
11884                                    r.append(' ');
11885                                }
11886                                r.append(p.info.name);
11887                            }
11888                        } else {
11889                            Slog.w(TAG, "Permission " + p.info.name + " from package "
11890                                    + p.info.packageName + " ignored: base tree "
11891                                    + tree.name + " is from package "
11892                                    + tree.sourcePackage);
11893                        }
11894                    } else {
11895                        Slog.w(TAG, "Permission " + p.info.name + " from package "
11896                                + p.info.packageName + " ignored: original from "
11897                                + bp.sourcePackage);
11898                    }
11899                } else if (chatty) {
11900                    if (r == null) {
11901                        r = new StringBuilder(256);
11902                    } else {
11903                        r.append(' ');
11904                    }
11905                    r.append("DUP:");
11906                    r.append(p.info.name);
11907                }
11908                if (bp.perm == p) {
11909                    bp.protectionLevel = p.info.protectionLevel;
11910                }
11911            }
11912
11913            if (r != null) {
11914                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
11915            }
11916
11917            N = pkg.instrumentation.size();
11918            r = null;
11919            for (i=0; i<N; i++) {
11920                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11921                a.info.packageName = pkg.applicationInfo.packageName;
11922                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11923                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11924                a.info.splitNames = pkg.splitNames;
11925                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11926                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11927                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11928                a.info.dataDir = pkg.applicationInfo.dataDir;
11929                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11930                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11931                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11932                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11933                mInstrumentation.put(a.getComponentName(), a);
11934                if (chatty) {
11935                    if (r == null) {
11936                        r = new StringBuilder(256);
11937                    } else {
11938                        r.append(' ');
11939                    }
11940                    r.append(a.info.name);
11941                }
11942            }
11943            if (r != null) {
11944                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11945            }
11946
11947            if (pkg.protectedBroadcasts != null) {
11948                N = pkg.protectedBroadcasts.size();
11949                synchronized (mProtectedBroadcasts) {
11950                    for (i = 0; i < N; i++) {
11951                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11952                    }
11953                }
11954            }
11955        }
11956
11957        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11958    }
11959
11960    /**
11961     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11962     * is derived purely on the basis of the contents of {@code scanFile} and
11963     * {@code cpuAbiOverride}.
11964     *
11965     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11966     */
11967    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11968                                 String cpuAbiOverride, boolean extractLibs,
11969                                 File appLib32InstallDir)
11970            throws PackageManagerException {
11971        // Give ourselves some initial paths; we'll come back for another
11972        // pass once we've determined ABI below.
11973        setNativeLibraryPaths(pkg, appLib32InstallDir);
11974
11975        // We would never need to extract libs for forward-locked and external packages,
11976        // since the container service will do it for us. We shouldn't attempt to
11977        // extract libs from system app when it was not updated.
11978        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11979                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11980            extractLibs = false;
11981        }
11982
11983        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11984        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11985
11986        NativeLibraryHelper.Handle handle = null;
11987        try {
11988            handle = NativeLibraryHelper.Handle.create(pkg);
11989            // TODO(multiArch): This can be null for apps that didn't go through the
11990            // usual installation process. We can calculate it again, like we
11991            // do during install time.
11992            //
11993            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11994            // unnecessary.
11995            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11996
11997            // Null out the abis so that they can be recalculated.
11998            pkg.applicationInfo.primaryCpuAbi = null;
11999            pkg.applicationInfo.secondaryCpuAbi = null;
12000            if (isMultiArch(pkg.applicationInfo)) {
12001                // Warn if we've set an abiOverride for multi-lib packages..
12002                // By definition, we need to copy both 32 and 64 bit libraries for
12003                // such packages.
12004                if (pkg.cpuAbiOverride != null
12005                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
12006                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
12007                }
12008
12009                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
12010                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
12011                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
12012                    if (extractLibs) {
12013                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
12014                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
12015                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
12016                                useIsaSpecificSubdirs);
12017                    } else {
12018                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
12019                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
12020                    }
12021                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12022                }
12023
12024                // Shared library native code should be in the APK zip aligned
12025                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
12026                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12027                            "Shared library native lib extraction not supported");
12028                }
12029
12030                maybeThrowExceptionForMultiArchCopy(
12031                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
12032
12033                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
12034                    if (extractLibs) {
12035                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
12036                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
12037                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
12038                                useIsaSpecificSubdirs);
12039                    } else {
12040                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
12041                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
12042                    }
12043                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12044                }
12045
12046                maybeThrowExceptionForMultiArchCopy(
12047                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
12048
12049                if (abi64 >= 0) {
12050                    // Shared library native libs should be in the APK zip aligned
12051                    if (extractLibs && pkg.isLibrary()) {
12052                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12053                                "Shared library native lib extraction not supported");
12054                    }
12055                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
12056                }
12057
12058                if (abi32 >= 0) {
12059                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
12060                    if (abi64 >= 0) {
12061                        if (pkg.use32bitAbi) {
12062                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
12063                            pkg.applicationInfo.primaryCpuAbi = abi;
12064                        } else {
12065                            pkg.applicationInfo.secondaryCpuAbi = abi;
12066                        }
12067                    } else {
12068                        pkg.applicationInfo.primaryCpuAbi = abi;
12069                    }
12070                }
12071            } else {
12072                String[] abiList = (cpuAbiOverride != null) ?
12073                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
12074
12075                // Enable gross and lame hacks for apps that are built with old
12076                // SDK tools. We must scan their APKs for renderscript bitcode and
12077                // not launch them if it's present. Don't bother checking on devices
12078                // that don't have 64 bit support.
12079                boolean needsRenderScriptOverride = false;
12080                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
12081                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
12082                    abiList = Build.SUPPORTED_32_BIT_ABIS;
12083                    needsRenderScriptOverride = true;
12084                }
12085
12086                final int copyRet;
12087                if (extractLibs) {
12088                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
12089                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
12090                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
12091                } else {
12092                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
12093                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
12094                }
12095                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12096
12097                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
12098                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12099                            "Error unpackaging native libs for app, errorCode=" + copyRet);
12100                }
12101
12102                if (copyRet >= 0) {
12103                    // Shared libraries that have native libs must be multi-architecture
12104                    if (pkg.isLibrary()) {
12105                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12106                                "Shared library with native libs must be multiarch");
12107                    }
12108                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
12109                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
12110                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
12111                } else if (needsRenderScriptOverride) {
12112                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
12113                }
12114            }
12115        } catch (IOException ioe) {
12116            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
12117        } finally {
12118            IoUtils.closeQuietly(handle);
12119        }
12120
12121        // Now that we've calculated the ABIs and determined if it's an internal app,
12122        // we will go ahead and populate the nativeLibraryPath.
12123        setNativeLibraryPaths(pkg, appLib32InstallDir);
12124    }
12125
12126    /**
12127     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
12128     * i.e, so that all packages can be run inside a single process if required.
12129     *
12130     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
12131     * this function will either try and make the ABI for all packages in {@code packagesForUser}
12132     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
12133     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
12134     * updating a package that belongs to a shared user.
12135     *
12136     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
12137     * adds unnecessary complexity.
12138     */
12139    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
12140            PackageParser.Package scannedPackage) {
12141        String requiredInstructionSet = null;
12142        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
12143            requiredInstructionSet = VMRuntime.getInstructionSet(
12144                     scannedPackage.applicationInfo.primaryCpuAbi);
12145        }
12146
12147        PackageSetting requirer = null;
12148        for (PackageSetting ps : packagesForUser) {
12149            // If packagesForUser contains scannedPackage, we skip it. This will happen
12150            // when scannedPackage is an update of an existing package. Without this check,
12151            // we will never be able to change the ABI of any package belonging to a shared
12152            // user, even if it's compatible with other packages.
12153            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
12154                if (ps.primaryCpuAbiString == null) {
12155                    continue;
12156                }
12157
12158                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
12159                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
12160                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
12161                    // this but there's not much we can do.
12162                    String errorMessage = "Instruction set mismatch, "
12163                            + ((requirer == null) ? "[caller]" : requirer)
12164                            + " requires " + requiredInstructionSet + " whereas " + ps
12165                            + " requires " + instructionSet;
12166                    Slog.w(TAG, errorMessage);
12167                }
12168
12169                if (requiredInstructionSet == null) {
12170                    requiredInstructionSet = instructionSet;
12171                    requirer = ps;
12172                }
12173            }
12174        }
12175
12176        if (requiredInstructionSet != null) {
12177            String adjustedAbi;
12178            if (requirer != null) {
12179                // requirer != null implies that either scannedPackage was null or that scannedPackage
12180                // did not require an ABI, in which case we have to adjust scannedPackage to match
12181                // the ABI of the set (which is the same as requirer's ABI)
12182                adjustedAbi = requirer.primaryCpuAbiString;
12183                if (scannedPackage != null) {
12184                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
12185                }
12186            } else {
12187                // requirer == null implies that we're updating all ABIs in the set to
12188                // match scannedPackage.
12189                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
12190            }
12191
12192            for (PackageSetting ps : packagesForUser) {
12193                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
12194                    if (ps.primaryCpuAbiString != null) {
12195                        continue;
12196                    }
12197
12198                    ps.primaryCpuAbiString = adjustedAbi;
12199                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
12200                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
12201                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
12202                        if (DEBUG_ABI_SELECTION) {
12203                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
12204                                    + " (requirer="
12205                                    + (requirer != null ? requirer.pkg : "null")
12206                                    + ", scannedPackage="
12207                                    + (scannedPackage != null ? scannedPackage : "null")
12208                                    + ")");
12209                        }
12210                        try {
12211                            mInstaller.rmdex(ps.codePathString,
12212                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
12213                        } catch (InstallerException ignored) {
12214                        }
12215                    }
12216                }
12217            }
12218        }
12219    }
12220
12221    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
12222        synchronized (mPackages) {
12223            mResolverReplaced = true;
12224            // Set up information for custom user intent resolution activity.
12225            mResolveActivity.applicationInfo = pkg.applicationInfo;
12226            mResolveActivity.name = mCustomResolverComponentName.getClassName();
12227            mResolveActivity.packageName = pkg.applicationInfo.packageName;
12228            mResolveActivity.processName = pkg.applicationInfo.packageName;
12229            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
12230            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
12231                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12232            mResolveActivity.theme = 0;
12233            mResolveActivity.exported = true;
12234            mResolveActivity.enabled = true;
12235            mResolveInfo.activityInfo = mResolveActivity;
12236            mResolveInfo.priority = 0;
12237            mResolveInfo.preferredOrder = 0;
12238            mResolveInfo.match = 0;
12239            mResolveComponentName = mCustomResolverComponentName;
12240            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
12241                    mResolveComponentName);
12242        }
12243    }
12244
12245    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
12246        if (installerActivity == null) {
12247            if (DEBUG_EPHEMERAL) {
12248                Slog.d(TAG, "Clear ephemeral installer activity");
12249            }
12250            mInstantAppInstallerActivity = null;
12251            return;
12252        }
12253
12254        if (DEBUG_EPHEMERAL) {
12255            Slog.d(TAG, "Set ephemeral installer activity: "
12256                    + installerActivity.getComponentName());
12257        }
12258        // Set up information for ephemeral installer activity
12259        mInstantAppInstallerActivity = installerActivity;
12260        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
12261                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12262        mInstantAppInstallerActivity.exported = true;
12263        mInstantAppInstallerActivity.enabled = true;
12264        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
12265        mInstantAppInstallerInfo.priority = 0;
12266        mInstantAppInstallerInfo.preferredOrder = 1;
12267        mInstantAppInstallerInfo.isDefault = true;
12268        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
12269                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
12270    }
12271
12272    private static String calculateBundledApkRoot(final String codePathString) {
12273        final File codePath = new File(codePathString);
12274        final File codeRoot;
12275        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
12276            codeRoot = Environment.getRootDirectory();
12277        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
12278            codeRoot = Environment.getOemDirectory();
12279        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
12280            codeRoot = Environment.getVendorDirectory();
12281        } else {
12282            // Unrecognized code path; take its top real segment as the apk root:
12283            // e.g. /something/app/blah.apk => /something
12284            try {
12285                File f = codePath.getCanonicalFile();
12286                File parent = f.getParentFile();    // non-null because codePath is a file
12287                File tmp;
12288                while ((tmp = parent.getParentFile()) != null) {
12289                    f = parent;
12290                    parent = tmp;
12291                }
12292                codeRoot = f;
12293                Slog.w(TAG, "Unrecognized code path "
12294                        + codePath + " - using " + codeRoot);
12295            } catch (IOException e) {
12296                // Can't canonicalize the code path -- shenanigans?
12297                Slog.w(TAG, "Can't canonicalize code path " + codePath);
12298                return Environment.getRootDirectory().getPath();
12299            }
12300        }
12301        return codeRoot.getPath();
12302    }
12303
12304    /**
12305     * Derive and set the location of native libraries for the given package,
12306     * which varies depending on where and how the package was installed.
12307     */
12308    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
12309        final ApplicationInfo info = pkg.applicationInfo;
12310        final String codePath = pkg.codePath;
12311        final File codeFile = new File(codePath);
12312        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
12313        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
12314
12315        info.nativeLibraryRootDir = null;
12316        info.nativeLibraryRootRequiresIsa = false;
12317        info.nativeLibraryDir = null;
12318        info.secondaryNativeLibraryDir = null;
12319
12320        if (isApkFile(codeFile)) {
12321            // Monolithic install
12322            if (bundledApp) {
12323                // If "/system/lib64/apkname" exists, assume that is the per-package
12324                // native library directory to use; otherwise use "/system/lib/apkname".
12325                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
12326                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
12327                        getPrimaryInstructionSet(info));
12328
12329                // This is a bundled system app so choose the path based on the ABI.
12330                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
12331                // is just the default path.
12332                final String apkName = deriveCodePathName(codePath);
12333                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
12334                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
12335                        apkName).getAbsolutePath();
12336
12337                if (info.secondaryCpuAbi != null) {
12338                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
12339                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
12340                            secondaryLibDir, apkName).getAbsolutePath();
12341                }
12342            } else if (asecApp) {
12343                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
12344                        .getAbsolutePath();
12345            } else {
12346                final String apkName = deriveCodePathName(codePath);
12347                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
12348                        .getAbsolutePath();
12349            }
12350
12351            info.nativeLibraryRootRequiresIsa = false;
12352            info.nativeLibraryDir = info.nativeLibraryRootDir;
12353        } else {
12354            // Cluster install
12355            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
12356            info.nativeLibraryRootRequiresIsa = true;
12357
12358            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
12359                    getPrimaryInstructionSet(info)).getAbsolutePath();
12360
12361            if (info.secondaryCpuAbi != null) {
12362                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
12363                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
12364            }
12365        }
12366    }
12367
12368    /**
12369     * Calculate the abis and roots for a bundled app. These can uniquely
12370     * be determined from the contents of the system partition, i.e whether
12371     * it contains 64 or 32 bit shared libraries etc. We do not validate any
12372     * of this information, and instead assume that the system was built
12373     * sensibly.
12374     */
12375    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
12376                                           PackageSetting pkgSetting) {
12377        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
12378
12379        // If "/system/lib64/apkname" exists, assume that is the per-package
12380        // native library directory to use; otherwise use "/system/lib/apkname".
12381        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
12382        setBundledAppAbi(pkg, apkRoot, apkName);
12383        // pkgSetting might be null during rescan following uninstall of updates
12384        // to a bundled app, so accommodate that possibility.  The settings in
12385        // that case will be established later from the parsed package.
12386        //
12387        // If the settings aren't null, sync them up with what we've just derived.
12388        // note that apkRoot isn't stored in the package settings.
12389        if (pkgSetting != null) {
12390            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
12391            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
12392        }
12393    }
12394
12395    /**
12396     * Deduces the ABI of a bundled app and sets the relevant fields on the
12397     * parsed pkg object.
12398     *
12399     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
12400     *        under which system libraries are installed.
12401     * @param apkName the name of the installed package.
12402     */
12403    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
12404        final File codeFile = new File(pkg.codePath);
12405
12406        final boolean has64BitLibs;
12407        final boolean has32BitLibs;
12408        if (isApkFile(codeFile)) {
12409            // Monolithic install
12410            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
12411            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
12412        } else {
12413            // Cluster install
12414            final File rootDir = new File(codeFile, LIB_DIR_NAME);
12415            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
12416                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
12417                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
12418                has64BitLibs = (new File(rootDir, isa)).exists();
12419            } else {
12420                has64BitLibs = false;
12421            }
12422            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
12423                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
12424                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
12425                has32BitLibs = (new File(rootDir, isa)).exists();
12426            } else {
12427                has32BitLibs = false;
12428            }
12429        }
12430
12431        if (has64BitLibs && !has32BitLibs) {
12432            // The package has 64 bit libs, but not 32 bit libs. Its primary
12433            // ABI should be 64 bit. We can safely assume here that the bundled
12434            // native libraries correspond to the most preferred ABI in the list.
12435
12436            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12437            pkg.applicationInfo.secondaryCpuAbi = null;
12438        } else if (has32BitLibs && !has64BitLibs) {
12439            // The package has 32 bit libs but not 64 bit libs. Its primary
12440            // ABI should be 32 bit.
12441
12442            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12443            pkg.applicationInfo.secondaryCpuAbi = null;
12444        } else if (has32BitLibs && has64BitLibs) {
12445            // The application has both 64 and 32 bit bundled libraries. We check
12446            // here that the app declares multiArch support, and warn if it doesn't.
12447            //
12448            // We will be lenient here and record both ABIs. The primary will be the
12449            // ABI that's higher on the list, i.e, a device that's configured to prefer
12450            // 64 bit apps will see a 64 bit primary ABI,
12451
12452            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
12453                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12454            }
12455
12456            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12457                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12458                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12459            } else {
12460                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12461                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12462            }
12463        } else {
12464            pkg.applicationInfo.primaryCpuAbi = null;
12465            pkg.applicationInfo.secondaryCpuAbi = null;
12466        }
12467    }
12468
12469    private void killApplication(String pkgName, int appId, String reason) {
12470        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12471    }
12472
12473    private void killApplication(String pkgName, int appId, int userId, String reason) {
12474        // Request the ActivityManager to kill the process(only for existing packages)
12475        // so that we do not end up in a confused state while the user is still using the older
12476        // version of the application while the new one gets installed.
12477        final long token = Binder.clearCallingIdentity();
12478        try {
12479            IActivityManager am = ActivityManager.getService();
12480            if (am != null) {
12481                try {
12482                    am.killApplication(pkgName, appId, userId, reason);
12483                } catch (RemoteException e) {
12484                }
12485            }
12486        } finally {
12487            Binder.restoreCallingIdentity(token);
12488        }
12489    }
12490
12491    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12492        // Remove the parent package setting
12493        PackageSetting ps = (PackageSetting) pkg.mExtras;
12494        if (ps != null) {
12495            removePackageLI(ps, chatty);
12496        }
12497        // Remove the child package setting
12498        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12499        for (int i = 0; i < childCount; i++) {
12500            PackageParser.Package childPkg = pkg.childPackages.get(i);
12501            ps = (PackageSetting) childPkg.mExtras;
12502            if (ps != null) {
12503                removePackageLI(ps, chatty);
12504            }
12505        }
12506    }
12507
12508    void removePackageLI(PackageSetting ps, boolean chatty) {
12509        if (DEBUG_INSTALL) {
12510            if (chatty)
12511                Log.d(TAG, "Removing package " + ps.name);
12512        }
12513
12514        // writer
12515        synchronized (mPackages) {
12516            mPackages.remove(ps.name);
12517            final PackageParser.Package pkg = ps.pkg;
12518            if (pkg != null) {
12519                cleanPackageDataStructuresLILPw(pkg, chatty);
12520            }
12521        }
12522    }
12523
12524    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12525        if (DEBUG_INSTALL) {
12526            if (chatty)
12527                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12528        }
12529
12530        // writer
12531        synchronized (mPackages) {
12532            // Remove the parent package
12533            mPackages.remove(pkg.applicationInfo.packageName);
12534            cleanPackageDataStructuresLILPw(pkg, chatty);
12535
12536            // Remove the child packages
12537            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12538            for (int i = 0; i < childCount; i++) {
12539                PackageParser.Package childPkg = pkg.childPackages.get(i);
12540                mPackages.remove(childPkg.applicationInfo.packageName);
12541                cleanPackageDataStructuresLILPw(childPkg, chatty);
12542            }
12543        }
12544    }
12545
12546    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12547        int N = pkg.providers.size();
12548        StringBuilder r = null;
12549        int i;
12550        for (i=0; i<N; i++) {
12551            PackageParser.Provider p = pkg.providers.get(i);
12552            mProviders.removeProvider(p);
12553            if (p.info.authority == null) {
12554
12555                /* There was another ContentProvider with this authority when
12556                 * this app was installed so this authority is null,
12557                 * Ignore it as we don't have to unregister the provider.
12558                 */
12559                continue;
12560            }
12561            String names[] = p.info.authority.split(";");
12562            for (int j = 0; j < names.length; j++) {
12563                if (mProvidersByAuthority.get(names[j]) == p) {
12564                    mProvidersByAuthority.remove(names[j]);
12565                    if (DEBUG_REMOVE) {
12566                        if (chatty)
12567                            Log.d(TAG, "Unregistered content provider: " + names[j]
12568                                    + ", className = " + p.info.name + ", isSyncable = "
12569                                    + p.info.isSyncable);
12570                    }
12571                }
12572            }
12573            if (DEBUG_REMOVE && chatty) {
12574                if (r == null) {
12575                    r = new StringBuilder(256);
12576                } else {
12577                    r.append(' ');
12578                }
12579                r.append(p.info.name);
12580            }
12581        }
12582        if (r != null) {
12583            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12584        }
12585
12586        N = pkg.services.size();
12587        r = null;
12588        for (i=0; i<N; i++) {
12589            PackageParser.Service s = pkg.services.get(i);
12590            mServices.removeService(s);
12591            if (chatty) {
12592                if (r == null) {
12593                    r = new StringBuilder(256);
12594                } else {
12595                    r.append(' ');
12596                }
12597                r.append(s.info.name);
12598            }
12599        }
12600        if (r != null) {
12601            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12602        }
12603
12604        N = pkg.receivers.size();
12605        r = null;
12606        for (i=0; i<N; i++) {
12607            PackageParser.Activity a = pkg.receivers.get(i);
12608            mReceivers.removeActivity(a, "receiver");
12609            if (DEBUG_REMOVE && chatty) {
12610                if (r == null) {
12611                    r = new StringBuilder(256);
12612                } else {
12613                    r.append(' ');
12614                }
12615                r.append(a.info.name);
12616            }
12617        }
12618        if (r != null) {
12619            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12620        }
12621
12622        N = pkg.activities.size();
12623        r = null;
12624        for (i=0; i<N; i++) {
12625            PackageParser.Activity a = pkg.activities.get(i);
12626            mActivities.removeActivity(a, "activity");
12627            if (DEBUG_REMOVE && chatty) {
12628                if (r == null) {
12629                    r = new StringBuilder(256);
12630                } else {
12631                    r.append(' ');
12632                }
12633                r.append(a.info.name);
12634            }
12635        }
12636        if (r != null) {
12637            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12638        }
12639
12640        N = pkg.permissions.size();
12641        r = null;
12642        for (i=0; i<N; i++) {
12643            PackageParser.Permission p = pkg.permissions.get(i);
12644            BasePermission bp = mSettings.mPermissions.get(p.info.name);
12645            if (bp == null) {
12646                bp = mSettings.mPermissionTrees.get(p.info.name);
12647            }
12648            if (bp != null && bp.perm == p) {
12649                bp.perm = null;
12650                if (DEBUG_REMOVE && chatty) {
12651                    if (r == null) {
12652                        r = new StringBuilder(256);
12653                    } else {
12654                        r.append(' ');
12655                    }
12656                    r.append(p.info.name);
12657                }
12658            }
12659            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12660                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12661                if (appOpPkgs != null) {
12662                    appOpPkgs.remove(pkg.packageName);
12663                }
12664            }
12665        }
12666        if (r != null) {
12667            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12668        }
12669
12670        N = pkg.requestedPermissions.size();
12671        r = null;
12672        for (i=0; i<N; i++) {
12673            String perm = pkg.requestedPermissions.get(i);
12674            BasePermission bp = mSettings.mPermissions.get(perm);
12675            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12676                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12677                if (appOpPkgs != null) {
12678                    appOpPkgs.remove(pkg.packageName);
12679                    if (appOpPkgs.isEmpty()) {
12680                        mAppOpPermissionPackages.remove(perm);
12681                    }
12682                }
12683            }
12684        }
12685        if (r != null) {
12686            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12687        }
12688
12689        N = pkg.instrumentation.size();
12690        r = null;
12691        for (i=0; i<N; i++) {
12692            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12693            mInstrumentation.remove(a.getComponentName());
12694            if (DEBUG_REMOVE && chatty) {
12695                if (r == null) {
12696                    r = new StringBuilder(256);
12697                } else {
12698                    r.append(' ');
12699                }
12700                r.append(a.info.name);
12701            }
12702        }
12703        if (r != null) {
12704            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12705        }
12706
12707        r = null;
12708        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12709            // Only system apps can hold shared libraries.
12710            if (pkg.libraryNames != null) {
12711                for (i = 0; i < pkg.libraryNames.size(); i++) {
12712                    String name = pkg.libraryNames.get(i);
12713                    if (removeSharedLibraryLPw(name, 0)) {
12714                        if (DEBUG_REMOVE && chatty) {
12715                            if (r == null) {
12716                                r = new StringBuilder(256);
12717                            } else {
12718                                r.append(' ');
12719                            }
12720                            r.append(name);
12721                        }
12722                    }
12723                }
12724            }
12725        }
12726
12727        r = null;
12728
12729        // Any package can hold static shared libraries.
12730        if (pkg.staticSharedLibName != null) {
12731            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12732                if (DEBUG_REMOVE && chatty) {
12733                    if (r == null) {
12734                        r = new StringBuilder(256);
12735                    } else {
12736                        r.append(' ');
12737                    }
12738                    r.append(pkg.staticSharedLibName);
12739                }
12740            }
12741        }
12742
12743        if (r != null) {
12744            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12745        }
12746    }
12747
12748    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12749        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12750            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12751                return true;
12752            }
12753        }
12754        return false;
12755    }
12756
12757    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12758    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12759    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12760
12761    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12762        // Update the parent permissions
12763        updatePermissionsLPw(pkg.packageName, pkg, flags);
12764        // Update the child permissions
12765        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12766        for (int i = 0; i < childCount; i++) {
12767            PackageParser.Package childPkg = pkg.childPackages.get(i);
12768            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12769        }
12770    }
12771
12772    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12773            int flags) {
12774        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12775        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12776    }
12777
12778    private void updatePermissionsLPw(String changingPkg,
12779            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12780        // Make sure there are no dangling permission trees.
12781        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12782        while (it.hasNext()) {
12783            final BasePermission bp = it.next();
12784            if (bp.packageSetting == null) {
12785                // We may not yet have parsed the package, so just see if
12786                // we still know about its settings.
12787                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12788            }
12789            if (bp.packageSetting == null) {
12790                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12791                        + " from package " + bp.sourcePackage);
12792                it.remove();
12793            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12794                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12795                    Slog.i(TAG, "Removing old permission tree: " + bp.name
12796                            + " from package " + bp.sourcePackage);
12797                    flags |= UPDATE_PERMISSIONS_ALL;
12798                    it.remove();
12799                }
12800            }
12801        }
12802
12803        // Make sure all dynamic permissions have been assigned to a package,
12804        // and make sure there are no dangling permissions.
12805        it = mSettings.mPermissions.values().iterator();
12806        while (it.hasNext()) {
12807            final BasePermission bp = it.next();
12808            if (bp.type == BasePermission.TYPE_DYNAMIC) {
12809                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12810                        + bp.name + " pkg=" + bp.sourcePackage
12811                        + " info=" + bp.pendingInfo);
12812                if (bp.packageSetting == null && bp.pendingInfo != null) {
12813                    final BasePermission tree = findPermissionTreeLP(bp.name);
12814                    if (tree != null && tree.perm != null) {
12815                        bp.packageSetting = tree.packageSetting;
12816                        bp.perm = new PackageParser.Permission(tree.perm.owner,
12817                                new PermissionInfo(bp.pendingInfo));
12818                        bp.perm.info.packageName = tree.perm.info.packageName;
12819                        bp.perm.info.name = bp.name;
12820                        bp.uid = tree.uid;
12821                    }
12822                }
12823            }
12824            if (bp.packageSetting == null) {
12825                // We may not yet have parsed the package, so just see if
12826                // we still know about its settings.
12827                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12828            }
12829            if (bp.packageSetting == null) {
12830                Slog.w(TAG, "Removing dangling permission: " + bp.name
12831                        + " from package " + bp.sourcePackage);
12832                it.remove();
12833            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12834                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12835                    Slog.i(TAG, "Removing old permission: " + bp.name
12836                            + " from package " + bp.sourcePackage);
12837                    flags |= UPDATE_PERMISSIONS_ALL;
12838                    it.remove();
12839                }
12840            }
12841        }
12842
12843        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12844        // Now update the permissions for all packages, in particular
12845        // replace the granted permissions of the system packages.
12846        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12847            for (PackageParser.Package pkg : mPackages.values()) {
12848                if (pkg != pkgInfo) {
12849                    // Only replace for packages on requested volume
12850                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12851                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12852                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12853                    grantPermissionsLPw(pkg, replace, changingPkg);
12854                }
12855            }
12856        }
12857
12858        if (pkgInfo != null) {
12859            // Only replace for packages on requested volume
12860            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12861            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12862                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12863            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12864        }
12865        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12866    }
12867
12868    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12869            String packageOfInterest) {
12870        // IMPORTANT: There are two types of permissions: install and runtime.
12871        // Install time permissions are granted when the app is installed to
12872        // all device users and users added in the future. Runtime permissions
12873        // are granted at runtime explicitly to specific users. Normal and signature
12874        // protected permissions are install time permissions. Dangerous permissions
12875        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12876        // otherwise they are runtime permissions. This function does not manage
12877        // runtime permissions except for the case an app targeting Lollipop MR1
12878        // being upgraded to target a newer SDK, in which case dangerous permissions
12879        // are transformed from install time to runtime ones.
12880
12881        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12882        if (ps == null) {
12883            return;
12884        }
12885
12886        PermissionsState permissionsState = ps.getPermissionsState();
12887        PermissionsState origPermissions = permissionsState;
12888
12889        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12890
12891        boolean runtimePermissionsRevoked = false;
12892        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12893
12894        boolean changedInstallPermission = false;
12895
12896        if (replace) {
12897            ps.installPermissionsFixed = false;
12898            if (!ps.isSharedUser()) {
12899                origPermissions = new PermissionsState(permissionsState);
12900                permissionsState.reset();
12901            } else {
12902                // We need to know only about runtime permission changes since the
12903                // calling code always writes the install permissions state but
12904                // the runtime ones are written only if changed. The only cases of
12905                // changed runtime permissions here are promotion of an install to
12906                // runtime and revocation of a runtime from a shared user.
12907                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12908                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
12909                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12910                    runtimePermissionsRevoked = true;
12911                }
12912            }
12913        }
12914
12915        permissionsState.setGlobalGids(mGlobalGids);
12916
12917        final int N = pkg.requestedPermissions.size();
12918        for (int i=0; i<N; i++) {
12919            final String name = pkg.requestedPermissions.get(i);
12920            final BasePermission bp = mSettings.mPermissions.get(name);
12921            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12922                    >= Build.VERSION_CODES.M;
12923
12924            if (DEBUG_INSTALL) {
12925                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12926            }
12927
12928            if (bp == null || bp.packageSetting == null) {
12929                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12930                    if (DEBUG_PERMISSIONS) {
12931                        Slog.i(TAG, "Unknown permission " + name
12932                                + " in package " + pkg.packageName);
12933                    }
12934                }
12935                continue;
12936            }
12937
12938
12939            // Limit ephemeral apps to ephemeral allowed permissions.
12940            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12941                if (DEBUG_PERMISSIONS) {
12942                    Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
12943                            + pkg.packageName);
12944                }
12945                continue;
12946            }
12947
12948            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12949                if (DEBUG_PERMISSIONS) {
12950                    Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
12951                            + pkg.packageName);
12952                }
12953                continue;
12954            }
12955
12956            final String perm = bp.name;
12957            boolean allowedSig = false;
12958            int grant = GRANT_DENIED;
12959
12960            // Keep track of app op permissions.
12961            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12962                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
12963                if (pkgs == null) {
12964                    pkgs = new ArraySet<>();
12965                    mAppOpPermissionPackages.put(bp.name, pkgs);
12966                }
12967                pkgs.add(pkg.packageName);
12968            }
12969
12970            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
12971            switch (level) {
12972                case PermissionInfo.PROTECTION_NORMAL: {
12973                    // For all apps normal permissions are install time ones.
12974                    grant = GRANT_INSTALL;
12975                } break;
12976
12977                case PermissionInfo.PROTECTION_DANGEROUS: {
12978                    // If a permission review is required for legacy apps we represent
12979                    // their permissions as always granted runtime ones since we need
12980                    // to keep the review required permission flag per user while an
12981                    // install permission's state is shared across all users.
12982                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12983                        // For legacy apps dangerous permissions are install time ones.
12984                        grant = GRANT_INSTALL;
12985                    } else if (origPermissions.hasInstallPermission(bp.name)) {
12986                        // For legacy apps that became modern, install becomes runtime.
12987                        grant = GRANT_UPGRADE;
12988                    } else if (mPromoteSystemApps
12989                            && isSystemApp(ps)
12990                            && mExistingSystemPackages.contains(ps.name)) {
12991                        // For legacy system apps, install becomes runtime.
12992                        // We cannot check hasInstallPermission() for system apps since those
12993                        // permissions were granted implicitly and not persisted pre-M.
12994                        grant = GRANT_UPGRADE;
12995                    } else {
12996                        // For modern apps keep runtime permissions unchanged.
12997                        grant = GRANT_RUNTIME;
12998                    }
12999                } break;
13000
13001                case PermissionInfo.PROTECTION_SIGNATURE: {
13002                    // For all apps signature permissions are install time ones.
13003                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
13004                    if (allowedSig) {
13005                        grant = GRANT_INSTALL;
13006                    }
13007                } break;
13008            }
13009
13010            if (DEBUG_PERMISSIONS) {
13011                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
13012            }
13013
13014            if (grant != GRANT_DENIED) {
13015                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
13016                    // If this is an existing, non-system package, then
13017                    // we can't add any new permissions to it.
13018                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
13019                        // Except...  if this is a permission that was added
13020                        // to the platform (note: need to only do this when
13021                        // updating the platform).
13022                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
13023                            grant = GRANT_DENIED;
13024                        }
13025                    }
13026                }
13027
13028                switch (grant) {
13029                    case GRANT_INSTALL: {
13030                        // Revoke this as runtime permission to handle the case of
13031                        // a runtime permission being downgraded to an install one.
13032                        // Also in permission review mode we keep dangerous permissions
13033                        // for legacy apps
13034                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13035                            if (origPermissions.getRuntimePermissionState(
13036                                    bp.name, userId) != null) {
13037                                // Revoke the runtime permission and clear the flags.
13038                                origPermissions.revokeRuntimePermission(bp, userId);
13039                                origPermissions.updatePermissionFlags(bp, userId,
13040                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
13041                                // If we revoked a permission permission, we have to write.
13042                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13043                                        changedRuntimePermissionUserIds, userId);
13044                            }
13045                        }
13046                        // Grant an install permission.
13047                        if (permissionsState.grantInstallPermission(bp) !=
13048                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
13049                            changedInstallPermission = true;
13050                        }
13051                    } break;
13052
13053                    case GRANT_RUNTIME: {
13054                        // Grant previously granted runtime permissions.
13055                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13056                            PermissionState permissionState = origPermissions
13057                                    .getRuntimePermissionState(bp.name, userId);
13058                            int flags = permissionState != null
13059                                    ? permissionState.getFlags() : 0;
13060                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
13061                                // Don't propagate the permission in a permission review mode if
13062                                // the former was revoked, i.e. marked to not propagate on upgrade.
13063                                // Note that in a permission review mode install permissions are
13064                                // represented as constantly granted runtime ones since we need to
13065                                // keep a per user state associated with the permission. Also the
13066                                // revoke on upgrade flag is no longer applicable and is reset.
13067                                final boolean revokeOnUpgrade = (flags & PackageManager
13068                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
13069                                if (revokeOnUpgrade) {
13070                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13071                                    // Since we changed the flags, we have to write.
13072                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13073                                            changedRuntimePermissionUserIds, userId);
13074                                }
13075                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
13076                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
13077                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
13078                                        // If we cannot put the permission as it was,
13079                                        // we have to write.
13080                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13081                                                changedRuntimePermissionUserIds, userId);
13082                                    }
13083                                }
13084
13085                                // If the app supports runtime permissions no need for a review.
13086                                if (mPermissionReviewRequired
13087                                        && appSupportsRuntimePermissions
13088                                        && (flags & PackageManager
13089                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
13090                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
13091                                    // Since we changed the flags, we have to write.
13092                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13093                                            changedRuntimePermissionUserIds, userId);
13094                                }
13095                            } else if (mPermissionReviewRequired
13096                                    && !appSupportsRuntimePermissions) {
13097                                // For legacy apps that need a permission review, every new
13098                                // runtime permission is granted but it is pending a review.
13099                                // We also need to review only platform defined runtime
13100                                // permissions as these are the only ones the platform knows
13101                                // how to disable the API to simulate revocation as legacy
13102                                // apps don't expect to run with revoked permissions.
13103                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
13104                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
13105                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
13106                                        // We changed the flags, hence have to write.
13107                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13108                                                changedRuntimePermissionUserIds, userId);
13109                                    }
13110                                }
13111                                if (permissionsState.grantRuntimePermission(bp, userId)
13112                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
13113                                    // We changed the permission, hence have to write.
13114                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13115                                            changedRuntimePermissionUserIds, userId);
13116                                }
13117                            }
13118                            // Propagate the permission flags.
13119                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
13120                        }
13121                    } break;
13122
13123                    case GRANT_UPGRADE: {
13124                        // Grant runtime permissions for a previously held install permission.
13125                        PermissionState permissionState = origPermissions
13126                                .getInstallPermissionState(bp.name);
13127                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
13128
13129                        if (origPermissions.revokeInstallPermission(bp)
13130                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
13131                            // We will be transferring the permission flags, so clear them.
13132                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
13133                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
13134                            changedInstallPermission = true;
13135                        }
13136
13137                        // If the permission is not to be promoted to runtime we ignore it and
13138                        // also its other flags as they are not applicable to install permissions.
13139                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
13140                            for (int userId : currentUserIds) {
13141                                if (permissionsState.grantRuntimePermission(bp, userId) !=
13142                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
13143                                    // Transfer the permission flags.
13144                                    permissionsState.updatePermissionFlags(bp, userId,
13145                                            flags, flags);
13146                                    // If we granted the permission, we have to write.
13147                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13148                                            changedRuntimePermissionUserIds, userId);
13149                                }
13150                            }
13151                        }
13152                    } break;
13153
13154                    default: {
13155                        if (packageOfInterest == null
13156                                || packageOfInterest.equals(pkg.packageName)) {
13157                            if (DEBUG_PERMISSIONS) {
13158                                Slog.i(TAG, "Not granting permission " + perm
13159                                        + " to package " + pkg.packageName
13160                                        + " because it was previously installed without");
13161                            }
13162                        }
13163                    } break;
13164                }
13165            } else {
13166                if (permissionsState.revokeInstallPermission(bp) !=
13167                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
13168                    // Also drop the permission flags.
13169                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
13170                            PackageManager.MASK_PERMISSION_FLAGS, 0);
13171                    changedInstallPermission = true;
13172                    Slog.i(TAG, "Un-granting permission " + perm
13173                            + " from package " + pkg.packageName
13174                            + " (protectionLevel=" + bp.protectionLevel
13175                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
13176                            + ")");
13177                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
13178                    // Don't print warning for app op permissions, since it is fine for them
13179                    // not to be granted, there is a UI for the user to decide.
13180                    if (DEBUG_PERMISSIONS
13181                            && (packageOfInterest == null
13182                                    || packageOfInterest.equals(pkg.packageName))) {
13183                        Slog.i(TAG, "Not granting permission " + perm
13184                                + " to package " + pkg.packageName
13185                                + " (protectionLevel=" + bp.protectionLevel
13186                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
13187                                + ")");
13188                    }
13189                }
13190            }
13191        }
13192
13193        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
13194                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
13195            // This is the first that we have heard about this package, so the
13196            // permissions we have now selected are fixed until explicitly
13197            // changed.
13198            ps.installPermissionsFixed = true;
13199        }
13200
13201        // Persist the runtime permissions state for users with changes. If permissions
13202        // were revoked because no app in the shared user declares them we have to
13203        // write synchronously to avoid losing runtime permissions state.
13204        for (int userId : changedRuntimePermissionUserIds) {
13205            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
13206        }
13207    }
13208
13209    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
13210        boolean allowed = false;
13211        final int NP = PackageParser.NEW_PERMISSIONS.length;
13212        for (int ip=0; ip<NP; ip++) {
13213            final PackageParser.NewPermissionInfo npi
13214                    = PackageParser.NEW_PERMISSIONS[ip];
13215            if (npi.name.equals(perm)
13216                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
13217                allowed = true;
13218                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
13219                        + pkg.packageName);
13220                break;
13221            }
13222        }
13223        return allowed;
13224    }
13225
13226    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
13227            BasePermission bp, PermissionsState origPermissions) {
13228        boolean privilegedPermission = (bp.protectionLevel
13229                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
13230        boolean privappPermissionsDisable =
13231                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
13232        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
13233        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
13234        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
13235                && !platformPackage && platformPermission) {
13236            final ArraySet<String> allowedPermissions = SystemConfig.getInstance()
13237                    .getPrivAppPermissions(pkg.packageName);
13238            final boolean whitelisted =
13239                    allowedPermissions != null && allowedPermissions.contains(perm);
13240            if (!whitelisted) {
13241                Slog.w(TAG, "Privileged permission " + perm + " for package "
13242                        + pkg.packageName + " - not in privapp-permissions whitelist");
13243                // Only report violations for apps on system image
13244                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
13245                    // it's only a reportable violation if the permission isn't explicitly denied
13246                    final ArraySet<String> deniedPermissions = SystemConfig.getInstance()
13247                            .getPrivAppDenyPermissions(pkg.packageName);
13248                    final boolean permissionViolation =
13249                            deniedPermissions == null || !deniedPermissions.contains(perm);
13250                    if (permissionViolation) {
13251                        if (mPrivappPermissionsViolations == null) {
13252                            mPrivappPermissionsViolations = new ArraySet<>();
13253                        }
13254                        mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
13255                    } else {
13256                        return false;
13257                    }
13258                }
13259                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
13260                    return false;
13261                }
13262            }
13263        }
13264        boolean allowed = (compareSignatures(
13265                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
13266                        == PackageManager.SIGNATURE_MATCH)
13267                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
13268                        == PackageManager.SIGNATURE_MATCH);
13269        if (!allowed && privilegedPermission) {
13270            if (isSystemApp(pkg)) {
13271                // For updated system applications, a system permission
13272                // is granted only if it had been defined by the original application.
13273                if (pkg.isUpdatedSystemApp()) {
13274                    final PackageSetting sysPs = mSettings
13275                            .getDisabledSystemPkgLPr(pkg.packageName);
13276                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
13277                        // If the original was granted this permission, we take
13278                        // that grant decision as read and propagate it to the
13279                        // update.
13280                        if (sysPs.isPrivileged()) {
13281                            allowed = true;
13282                        }
13283                    } else {
13284                        // The system apk may have been updated with an older
13285                        // version of the one on the data partition, but which
13286                        // granted a new system permission that it didn't have
13287                        // before.  In this case we do want to allow the app to
13288                        // now get the new permission if the ancestral apk is
13289                        // privileged to get it.
13290                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
13291                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
13292                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
13293                                    allowed = true;
13294                                    break;
13295                                }
13296                            }
13297                        }
13298                        // Also if a privileged parent package on the system image or any of
13299                        // its children requested a privileged permission, the updated child
13300                        // packages can also get the permission.
13301                        if (pkg.parentPackage != null) {
13302                            final PackageSetting disabledSysParentPs = mSettings
13303                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
13304                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
13305                                    && disabledSysParentPs.isPrivileged()) {
13306                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
13307                                    allowed = true;
13308                                } else if (disabledSysParentPs.pkg.childPackages != null) {
13309                                    final int count = disabledSysParentPs.pkg.childPackages.size();
13310                                    for (int i = 0; i < count; i++) {
13311                                        PackageParser.Package disabledSysChildPkg =
13312                                                disabledSysParentPs.pkg.childPackages.get(i);
13313                                        if (isPackageRequestingPermission(disabledSysChildPkg,
13314                                                perm)) {
13315                                            allowed = true;
13316                                            break;
13317                                        }
13318                                    }
13319                                }
13320                            }
13321                        }
13322                    }
13323                } else {
13324                    allowed = isPrivilegedApp(pkg);
13325                }
13326            }
13327        }
13328        if (!allowed) {
13329            if (!allowed && (bp.protectionLevel
13330                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
13331                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
13332                // If this was a previously normal/dangerous permission that got moved
13333                // to a system permission as part of the runtime permission redesign, then
13334                // we still want to blindly grant it to old apps.
13335                allowed = true;
13336            }
13337            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
13338                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
13339                // If this permission is to be granted to the system installer and
13340                // this app is an installer, then it gets the permission.
13341                allowed = true;
13342            }
13343            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
13344                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
13345                // If this permission is to be granted to the system verifier and
13346                // this app is a verifier, then it gets the permission.
13347                allowed = true;
13348            }
13349            if (!allowed && (bp.protectionLevel
13350                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
13351                    && isSystemApp(pkg)) {
13352                // Any pre-installed system app is allowed to get this permission.
13353                allowed = true;
13354            }
13355            if (!allowed && (bp.protectionLevel
13356                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
13357                // For development permissions, a development permission
13358                // is granted only if it was already granted.
13359                allowed = origPermissions.hasInstallPermission(perm);
13360            }
13361            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
13362                    && pkg.packageName.equals(mSetupWizardPackage)) {
13363                // If this permission is to be granted to the system setup wizard and
13364                // this app is a setup wizard, then it gets the permission.
13365                allowed = true;
13366            }
13367        }
13368        return allowed;
13369    }
13370
13371    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
13372        final int permCount = pkg.requestedPermissions.size();
13373        for (int j = 0; j < permCount; j++) {
13374            String requestedPermission = pkg.requestedPermissions.get(j);
13375            if (permission.equals(requestedPermission)) {
13376                return true;
13377            }
13378        }
13379        return false;
13380    }
13381
13382    final class ActivityIntentResolver
13383            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
13384        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13385                boolean defaultOnly, int userId) {
13386            if (!sUserManager.exists(userId)) return null;
13387            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
13388            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13389        }
13390
13391        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13392                int userId) {
13393            if (!sUserManager.exists(userId)) return null;
13394            mFlags = flags;
13395            return super.queryIntent(intent, resolvedType,
13396                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13397                    userId);
13398        }
13399
13400        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13401                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
13402            if (!sUserManager.exists(userId)) return null;
13403            if (packageActivities == null) {
13404                return null;
13405            }
13406            mFlags = flags;
13407            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13408            final int N = packageActivities.size();
13409            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
13410                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
13411
13412            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
13413            for (int i = 0; i < N; ++i) {
13414                intentFilters = packageActivities.get(i).intents;
13415                if (intentFilters != null && intentFilters.size() > 0) {
13416                    PackageParser.ActivityIntentInfo[] array =
13417                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
13418                    intentFilters.toArray(array);
13419                    listCut.add(array);
13420                }
13421            }
13422            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13423        }
13424
13425        /**
13426         * Finds a privileged activity that matches the specified activity names.
13427         */
13428        private PackageParser.Activity findMatchingActivity(
13429                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
13430            for (PackageParser.Activity sysActivity : activityList) {
13431                if (sysActivity.info.name.equals(activityInfo.name)) {
13432                    return sysActivity;
13433                }
13434                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
13435                    return sysActivity;
13436                }
13437                if (sysActivity.info.targetActivity != null) {
13438                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
13439                        return sysActivity;
13440                    }
13441                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
13442                        return sysActivity;
13443                    }
13444                }
13445            }
13446            return null;
13447        }
13448
13449        public class IterGenerator<E> {
13450            public Iterator<E> generate(ActivityIntentInfo info) {
13451                return null;
13452            }
13453        }
13454
13455        public class ActionIterGenerator extends IterGenerator<String> {
13456            @Override
13457            public Iterator<String> generate(ActivityIntentInfo info) {
13458                return info.actionsIterator();
13459            }
13460        }
13461
13462        public class CategoriesIterGenerator extends IterGenerator<String> {
13463            @Override
13464            public Iterator<String> generate(ActivityIntentInfo info) {
13465                return info.categoriesIterator();
13466            }
13467        }
13468
13469        public class SchemesIterGenerator extends IterGenerator<String> {
13470            @Override
13471            public Iterator<String> generate(ActivityIntentInfo info) {
13472                return info.schemesIterator();
13473            }
13474        }
13475
13476        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
13477            @Override
13478            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
13479                return info.authoritiesIterator();
13480            }
13481        }
13482
13483        /**
13484         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
13485         * MODIFIED. Do not pass in a list that should not be changed.
13486         */
13487        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
13488                IterGenerator<T> generator, Iterator<T> searchIterator) {
13489            // loop through the set of actions; every one must be found in the intent filter
13490            while (searchIterator.hasNext()) {
13491                // we must have at least one filter in the list to consider a match
13492                if (intentList.size() == 0) {
13493                    break;
13494                }
13495
13496                final T searchAction = searchIterator.next();
13497
13498                // loop through the set of intent filters
13499                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
13500                while (intentIter.hasNext()) {
13501                    final ActivityIntentInfo intentInfo = intentIter.next();
13502                    boolean selectionFound = false;
13503
13504                    // loop through the intent filter's selection criteria; at least one
13505                    // of them must match the searched criteria
13506                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
13507                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
13508                        final T intentSelection = intentSelectionIter.next();
13509                        if (intentSelection != null && intentSelection.equals(searchAction)) {
13510                            selectionFound = true;
13511                            break;
13512                        }
13513                    }
13514
13515                    // the selection criteria wasn't found in this filter's set; this filter
13516                    // is not a potential match
13517                    if (!selectionFound) {
13518                        intentIter.remove();
13519                    }
13520                }
13521            }
13522        }
13523
13524        private boolean isProtectedAction(ActivityIntentInfo filter) {
13525            final Iterator<String> actionsIter = filter.actionsIterator();
13526            while (actionsIter != null && actionsIter.hasNext()) {
13527                final String filterAction = actionsIter.next();
13528                if (PROTECTED_ACTIONS.contains(filterAction)) {
13529                    return true;
13530                }
13531            }
13532            return false;
13533        }
13534
13535        /**
13536         * Adjusts the priority of the given intent filter according to policy.
13537         * <p>
13538         * <ul>
13539         * <li>The priority for non privileged applications is capped to '0'</li>
13540         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
13541         * <li>The priority for unbundled updates to privileged applications is capped to the
13542         *      priority defined on the system partition</li>
13543         * </ul>
13544         * <p>
13545         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
13546         * allowed to obtain any priority on any action.
13547         */
13548        private void adjustPriority(
13549                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
13550            // nothing to do; priority is fine as-is
13551            if (intent.getPriority() <= 0) {
13552                return;
13553            }
13554
13555            final ActivityInfo activityInfo = intent.activity.info;
13556            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
13557
13558            final boolean privilegedApp =
13559                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
13560            if (!privilegedApp) {
13561                // non-privileged applications can never define a priority >0
13562                if (DEBUG_FILTERS) {
13563                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
13564                            + " package: " + applicationInfo.packageName
13565                            + " activity: " + intent.activity.className
13566                            + " origPrio: " + intent.getPriority());
13567                }
13568                intent.setPriority(0);
13569                return;
13570            }
13571
13572            if (systemActivities == null) {
13573                // the system package is not disabled; we're parsing the system partition
13574                if (isProtectedAction(intent)) {
13575                    if (mDeferProtectedFilters) {
13576                        // We can't deal with these just yet. No component should ever obtain a
13577                        // >0 priority for a protected actions, with ONE exception -- the setup
13578                        // wizard. The setup wizard, however, cannot be known until we're able to
13579                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
13580                        // until all intent filters have been processed. Chicken, meet egg.
13581                        // Let the filter temporarily have a high priority and rectify the
13582                        // priorities after all system packages have been scanned.
13583                        mProtectedFilters.add(intent);
13584                        if (DEBUG_FILTERS) {
13585                            Slog.i(TAG, "Protected action; save for later;"
13586                                    + " package: " + applicationInfo.packageName
13587                                    + " activity: " + intent.activity.className
13588                                    + " origPrio: " + intent.getPriority());
13589                        }
13590                        return;
13591                    } else {
13592                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13593                            Slog.i(TAG, "No setup wizard;"
13594                                + " All protected intents capped to priority 0");
13595                        }
13596                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13597                            if (DEBUG_FILTERS) {
13598                                Slog.i(TAG, "Found setup wizard;"
13599                                    + " allow priority " + intent.getPriority() + ";"
13600                                    + " package: " + intent.activity.info.packageName
13601                                    + " activity: " + intent.activity.className
13602                                    + " priority: " + intent.getPriority());
13603                            }
13604                            // setup wizard gets whatever it wants
13605                            return;
13606                        }
13607                        if (DEBUG_FILTERS) {
13608                            Slog.i(TAG, "Protected action; cap priority to 0;"
13609                                    + " package: " + intent.activity.info.packageName
13610                                    + " activity: " + intent.activity.className
13611                                    + " origPrio: " + intent.getPriority());
13612                        }
13613                        intent.setPriority(0);
13614                        return;
13615                    }
13616                }
13617                // privileged apps on the system image get whatever priority they request
13618                return;
13619            }
13620
13621            // privileged app unbundled update ... try to find the same activity
13622            final PackageParser.Activity foundActivity =
13623                    findMatchingActivity(systemActivities, activityInfo);
13624            if (foundActivity == null) {
13625                // this is a new activity; it cannot obtain >0 priority
13626                if (DEBUG_FILTERS) {
13627                    Slog.i(TAG, "New activity; cap priority to 0;"
13628                            + " package: " + applicationInfo.packageName
13629                            + " activity: " + intent.activity.className
13630                            + " origPrio: " + intent.getPriority());
13631                }
13632                intent.setPriority(0);
13633                return;
13634            }
13635
13636            // found activity, now check for filter equivalence
13637
13638            // a shallow copy is enough; we modify the list, not its contents
13639            final List<ActivityIntentInfo> intentListCopy =
13640                    new ArrayList<>(foundActivity.intents);
13641            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13642
13643            // find matching action subsets
13644            final Iterator<String> actionsIterator = intent.actionsIterator();
13645            if (actionsIterator != null) {
13646                getIntentListSubset(
13647                        intentListCopy, new ActionIterGenerator(), actionsIterator);
13648                if (intentListCopy.size() == 0) {
13649                    // no more intents to match; we're not equivalent
13650                    if (DEBUG_FILTERS) {
13651                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
13652                                + " package: " + applicationInfo.packageName
13653                                + " activity: " + intent.activity.className
13654                                + " origPrio: " + intent.getPriority());
13655                    }
13656                    intent.setPriority(0);
13657                    return;
13658                }
13659            }
13660
13661            // find matching category subsets
13662            final Iterator<String> categoriesIterator = intent.categoriesIterator();
13663            if (categoriesIterator != null) {
13664                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13665                        categoriesIterator);
13666                if (intentListCopy.size() == 0) {
13667                    // no more intents to match; we're not equivalent
13668                    if (DEBUG_FILTERS) {
13669                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
13670                                + " package: " + applicationInfo.packageName
13671                                + " activity: " + intent.activity.className
13672                                + " origPrio: " + intent.getPriority());
13673                    }
13674                    intent.setPriority(0);
13675                    return;
13676                }
13677            }
13678
13679            // find matching schemes subsets
13680            final Iterator<String> schemesIterator = intent.schemesIterator();
13681            if (schemesIterator != null) {
13682                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13683                        schemesIterator);
13684                if (intentListCopy.size() == 0) {
13685                    // no more intents to match; we're not equivalent
13686                    if (DEBUG_FILTERS) {
13687                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
13688                                + " package: " + applicationInfo.packageName
13689                                + " activity: " + intent.activity.className
13690                                + " origPrio: " + intent.getPriority());
13691                    }
13692                    intent.setPriority(0);
13693                    return;
13694                }
13695            }
13696
13697            // find matching authorities subsets
13698            final Iterator<IntentFilter.AuthorityEntry>
13699                    authoritiesIterator = intent.authoritiesIterator();
13700            if (authoritiesIterator != null) {
13701                getIntentListSubset(intentListCopy,
13702                        new AuthoritiesIterGenerator(),
13703                        authoritiesIterator);
13704                if (intentListCopy.size() == 0) {
13705                    // no more intents to match; we're not equivalent
13706                    if (DEBUG_FILTERS) {
13707                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13708                                + " package: " + applicationInfo.packageName
13709                                + " activity: " + intent.activity.className
13710                                + " origPrio: " + intent.getPriority());
13711                    }
13712                    intent.setPriority(0);
13713                    return;
13714                }
13715            }
13716
13717            // we found matching filter(s); app gets the max priority of all intents
13718            int cappedPriority = 0;
13719            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13720                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13721            }
13722            if (intent.getPriority() > cappedPriority) {
13723                if (DEBUG_FILTERS) {
13724                    Slog.i(TAG, "Found matching filter(s);"
13725                            + " cap priority to " + cappedPriority + ";"
13726                            + " package: " + applicationInfo.packageName
13727                            + " activity: " + intent.activity.className
13728                            + " origPrio: " + intent.getPriority());
13729                }
13730                intent.setPriority(cappedPriority);
13731                return;
13732            }
13733            // all this for nothing; the requested priority was <= what was on the system
13734        }
13735
13736        public final void addActivity(PackageParser.Activity a, String type) {
13737            mActivities.put(a.getComponentName(), a);
13738            if (DEBUG_SHOW_INFO)
13739                Log.v(
13740                TAG, "  " + type + " " +
13741                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13742            if (DEBUG_SHOW_INFO)
13743                Log.v(TAG, "    Class=" + a.info.name);
13744            final int NI = a.intents.size();
13745            for (int j=0; j<NI; j++) {
13746                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13747                if ("activity".equals(type)) {
13748                    final PackageSetting ps =
13749                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13750                    final List<PackageParser.Activity> systemActivities =
13751                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
13752                    adjustPriority(systemActivities, intent);
13753                }
13754                if (DEBUG_SHOW_INFO) {
13755                    Log.v(TAG, "    IntentFilter:");
13756                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13757                }
13758                if (!intent.debugCheck()) {
13759                    Log.w(TAG, "==> For Activity " + a.info.name);
13760                }
13761                addFilter(intent);
13762            }
13763        }
13764
13765        public final void removeActivity(PackageParser.Activity a, String type) {
13766            mActivities.remove(a.getComponentName());
13767            if (DEBUG_SHOW_INFO) {
13768                Log.v(TAG, "  " + type + " "
13769                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13770                                : a.info.name) + ":");
13771                Log.v(TAG, "    Class=" + a.info.name);
13772            }
13773            final int NI = a.intents.size();
13774            for (int j=0; j<NI; j++) {
13775                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13776                if (DEBUG_SHOW_INFO) {
13777                    Log.v(TAG, "    IntentFilter:");
13778                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13779                }
13780                removeFilter(intent);
13781            }
13782        }
13783
13784        @Override
13785        protected boolean allowFilterResult(
13786                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13787            ActivityInfo filterAi = filter.activity.info;
13788            for (int i=dest.size()-1; i>=0; i--) {
13789                ActivityInfo destAi = dest.get(i).activityInfo;
13790                if (destAi.name == filterAi.name
13791                        && destAi.packageName == filterAi.packageName) {
13792                    return false;
13793                }
13794            }
13795            return true;
13796        }
13797
13798        @Override
13799        protected ActivityIntentInfo[] newArray(int size) {
13800            return new ActivityIntentInfo[size];
13801        }
13802
13803        @Override
13804        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13805            if (!sUserManager.exists(userId)) return true;
13806            PackageParser.Package p = filter.activity.owner;
13807            if (p != null) {
13808                PackageSetting ps = (PackageSetting)p.mExtras;
13809                if (ps != null) {
13810                    // System apps are never considered stopped for purposes of
13811                    // filtering, because there may be no way for the user to
13812                    // actually re-launch them.
13813                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13814                            && ps.getStopped(userId);
13815                }
13816            }
13817            return false;
13818        }
13819
13820        @Override
13821        protected boolean isPackageForFilter(String packageName,
13822                PackageParser.ActivityIntentInfo info) {
13823            return packageName.equals(info.activity.owner.packageName);
13824        }
13825
13826        @Override
13827        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13828                int match, int userId) {
13829            if (!sUserManager.exists(userId)) return null;
13830            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13831                return null;
13832            }
13833            final PackageParser.Activity activity = info.activity;
13834            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13835            if (ps == null) {
13836                return null;
13837            }
13838            final PackageUserState userState = ps.readUserState(userId);
13839            ActivityInfo ai =
13840                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13841            if (ai == null) {
13842                return null;
13843            }
13844            final boolean matchExplicitlyVisibleOnly =
13845                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13846            final boolean matchVisibleToInstantApp =
13847                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13848            final boolean componentVisible =
13849                    matchVisibleToInstantApp
13850                    && info.isVisibleToInstantApp()
13851                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13852            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13853            // throw out filters that aren't visible to ephemeral apps
13854            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13855                return null;
13856            }
13857            // throw out instant app filters if we're not explicitly requesting them
13858            if (!matchInstantApp && userState.instantApp) {
13859                return null;
13860            }
13861            // throw out instant app filters if updates are available; will trigger
13862            // instant app resolution
13863            if (userState.instantApp && ps.isUpdateAvailable()) {
13864                return null;
13865            }
13866            final ResolveInfo res = new ResolveInfo();
13867            res.activityInfo = ai;
13868            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13869                res.filter = info;
13870            }
13871            if (info != null) {
13872                res.handleAllWebDataURI = info.handleAllWebDataURI();
13873            }
13874            res.priority = info.getPriority();
13875            res.preferredOrder = activity.owner.mPreferredOrder;
13876            //System.out.println("Result: " + res.activityInfo.className +
13877            //                   " = " + res.priority);
13878            res.match = match;
13879            res.isDefault = info.hasDefault;
13880            res.labelRes = info.labelRes;
13881            res.nonLocalizedLabel = info.nonLocalizedLabel;
13882            if (userNeedsBadging(userId)) {
13883                res.noResourceId = true;
13884            } else {
13885                res.icon = info.icon;
13886            }
13887            res.iconResourceId = info.icon;
13888            res.system = res.activityInfo.applicationInfo.isSystemApp();
13889            res.isInstantAppAvailable = userState.instantApp;
13890            return res;
13891        }
13892
13893        @Override
13894        protected void sortResults(List<ResolveInfo> results) {
13895            Collections.sort(results, mResolvePrioritySorter);
13896        }
13897
13898        @Override
13899        protected void dumpFilter(PrintWriter out, String prefix,
13900                PackageParser.ActivityIntentInfo filter) {
13901            out.print(prefix); out.print(
13902                    Integer.toHexString(System.identityHashCode(filter.activity)));
13903                    out.print(' ');
13904                    filter.activity.printComponentShortName(out);
13905                    out.print(" filter ");
13906                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13907        }
13908
13909        @Override
13910        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13911            return filter.activity;
13912        }
13913
13914        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13915            PackageParser.Activity activity = (PackageParser.Activity)label;
13916            out.print(prefix); out.print(
13917                    Integer.toHexString(System.identityHashCode(activity)));
13918                    out.print(' ');
13919                    activity.printComponentShortName(out);
13920            if (count > 1) {
13921                out.print(" ("); out.print(count); out.print(" filters)");
13922            }
13923            out.println();
13924        }
13925
13926        // Keys are String (activity class name), values are Activity.
13927        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13928                = new ArrayMap<ComponentName, PackageParser.Activity>();
13929        private int mFlags;
13930    }
13931
13932    private final class ServiceIntentResolver
13933            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13934        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13935                boolean defaultOnly, int userId) {
13936            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13937            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13938        }
13939
13940        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13941                int userId) {
13942            if (!sUserManager.exists(userId)) return null;
13943            mFlags = flags;
13944            return super.queryIntent(intent, resolvedType,
13945                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13946                    userId);
13947        }
13948
13949        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13950                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13951            if (!sUserManager.exists(userId)) return null;
13952            if (packageServices == null) {
13953                return null;
13954            }
13955            mFlags = flags;
13956            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13957            final int N = packageServices.size();
13958            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13959                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13960
13961            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13962            for (int i = 0; i < N; ++i) {
13963                intentFilters = packageServices.get(i).intents;
13964                if (intentFilters != null && intentFilters.size() > 0) {
13965                    PackageParser.ServiceIntentInfo[] array =
13966                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
13967                    intentFilters.toArray(array);
13968                    listCut.add(array);
13969                }
13970            }
13971            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13972        }
13973
13974        public final void addService(PackageParser.Service s) {
13975            mServices.put(s.getComponentName(), s);
13976            if (DEBUG_SHOW_INFO) {
13977                Log.v(TAG, "  "
13978                        + (s.info.nonLocalizedLabel != null
13979                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13980                Log.v(TAG, "    Class=" + s.info.name);
13981            }
13982            final int NI = s.intents.size();
13983            int j;
13984            for (j=0; j<NI; j++) {
13985                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13986                if (DEBUG_SHOW_INFO) {
13987                    Log.v(TAG, "    IntentFilter:");
13988                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13989                }
13990                if (!intent.debugCheck()) {
13991                    Log.w(TAG, "==> For Service " + s.info.name);
13992                }
13993                addFilter(intent);
13994            }
13995        }
13996
13997        public final void removeService(PackageParser.Service s) {
13998            mServices.remove(s.getComponentName());
13999            if (DEBUG_SHOW_INFO) {
14000                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
14001                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
14002                Log.v(TAG, "    Class=" + s.info.name);
14003            }
14004            final int NI = s.intents.size();
14005            int j;
14006            for (j=0; j<NI; j++) {
14007                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
14008                if (DEBUG_SHOW_INFO) {
14009                    Log.v(TAG, "    IntentFilter:");
14010                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14011                }
14012                removeFilter(intent);
14013            }
14014        }
14015
14016        @Override
14017        protected boolean allowFilterResult(
14018                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
14019            ServiceInfo filterSi = filter.service.info;
14020            for (int i=dest.size()-1; i>=0; i--) {
14021                ServiceInfo destAi = dest.get(i).serviceInfo;
14022                if (destAi.name == filterSi.name
14023                        && destAi.packageName == filterSi.packageName) {
14024                    return false;
14025                }
14026            }
14027            return true;
14028        }
14029
14030        @Override
14031        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
14032            return new PackageParser.ServiceIntentInfo[size];
14033        }
14034
14035        @Override
14036        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
14037            if (!sUserManager.exists(userId)) return true;
14038            PackageParser.Package p = filter.service.owner;
14039            if (p != null) {
14040                PackageSetting ps = (PackageSetting)p.mExtras;
14041                if (ps != null) {
14042                    // System apps are never considered stopped for purposes of
14043                    // filtering, because there may be no way for the user to
14044                    // actually re-launch them.
14045                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
14046                            && ps.getStopped(userId);
14047                }
14048            }
14049            return false;
14050        }
14051
14052        @Override
14053        protected boolean isPackageForFilter(String packageName,
14054                PackageParser.ServiceIntentInfo info) {
14055            return packageName.equals(info.service.owner.packageName);
14056        }
14057
14058        @Override
14059        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
14060                int match, int userId) {
14061            if (!sUserManager.exists(userId)) return null;
14062            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
14063            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
14064                return null;
14065            }
14066            final PackageParser.Service service = info.service;
14067            PackageSetting ps = (PackageSetting) service.owner.mExtras;
14068            if (ps == null) {
14069                return null;
14070            }
14071            final PackageUserState userState = ps.readUserState(userId);
14072            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
14073                    userState, userId);
14074            if (si == null) {
14075                return null;
14076            }
14077            final boolean matchVisibleToInstantApp =
14078                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
14079            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
14080            // throw out filters that aren't visible to ephemeral apps
14081            if (matchVisibleToInstantApp
14082                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
14083                return null;
14084            }
14085            // throw out ephemeral filters if we're not explicitly requesting them
14086            if (!isInstantApp && userState.instantApp) {
14087                return null;
14088            }
14089            // throw out instant app filters if updates are available; will trigger
14090            // instant app resolution
14091            if (userState.instantApp && ps.isUpdateAvailable()) {
14092                return null;
14093            }
14094            final ResolveInfo res = new ResolveInfo();
14095            res.serviceInfo = si;
14096            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
14097                res.filter = filter;
14098            }
14099            res.priority = info.getPriority();
14100            res.preferredOrder = service.owner.mPreferredOrder;
14101            res.match = match;
14102            res.isDefault = info.hasDefault;
14103            res.labelRes = info.labelRes;
14104            res.nonLocalizedLabel = info.nonLocalizedLabel;
14105            res.icon = info.icon;
14106            res.system = res.serviceInfo.applicationInfo.isSystemApp();
14107            return res;
14108        }
14109
14110        @Override
14111        protected void sortResults(List<ResolveInfo> results) {
14112            Collections.sort(results, mResolvePrioritySorter);
14113        }
14114
14115        @Override
14116        protected void dumpFilter(PrintWriter out, String prefix,
14117                PackageParser.ServiceIntentInfo filter) {
14118            out.print(prefix); out.print(
14119                    Integer.toHexString(System.identityHashCode(filter.service)));
14120                    out.print(' ');
14121                    filter.service.printComponentShortName(out);
14122                    out.print(" filter ");
14123                    out.println(Integer.toHexString(System.identityHashCode(filter)));
14124        }
14125
14126        @Override
14127        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
14128            return filter.service;
14129        }
14130
14131        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
14132            PackageParser.Service service = (PackageParser.Service)label;
14133            out.print(prefix); out.print(
14134                    Integer.toHexString(System.identityHashCode(service)));
14135                    out.print(' ');
14136                    service.printComponentShortName(out);
14137            if (count > 1) {
14138                out.print(" ("); out.print(count); out.print(" filters)");
14139            }
14140            out.println();
14141        }
14142
14143//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
14144//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
14145//            final List<ResolveInfo> retList = Lists.newArrayList();
14146//            while (i.hasNext()) {
14147//                final ResolveInfo resolveInfo = (ResolveInfo) i;
14148//                if (isEnabledLP(resolveInfo.serviceInfo)) {
14149//                    retList.add(resolveInfo);
14150//                }
14151//            }
14152//            return retList;
14153//        }
14154
14155        // Keys are String (activity class name), values are Activity.
14156        private final ArrayMap<ComponentName, PackageParser.Service> mServices
14157                = new ArrayMap<ComponentName, PackageParser.Service>();
14158        private int mFlags;
14159    }
14160
14161    private final class ProviderIntentResolver
14162            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
14163        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
14164                boolean defaultOnly, int userId) {
14165            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
14166            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
14167        }
14168
14169        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
14170                int userId) {
14171            if (!sUserManager.exists(userId))
14172                return null;
14173            mFlags = flags;
14174            return super.queryIntent(intent, resolvedType,
14175                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
14176                    userId);
14177        }
14178
14179        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
14180                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
14181            if (!sUserManager.exists(userId))
14182                return null;
14183            if (packageProviders == null) {
14184                return null;
14185            }
14186            mFlags = flags;
14187            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
14188            final int N = packageProviders.size();
14189            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
14190                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
14191
14192            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
14193            for (int i = 0; i < N; ++i) {
14194                intentFilters = packageProviders.get(i).intents;
14195                if (intentFilters != null && intentFilters.size() > 0) {
14196                    PackageParser.ProviderIntentInfo[] array =
14197                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
14198                    intentFilters.toArray(array);
14199                    listCut.add(array);
14200                }
14201            }
14202            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
14203        }
14204
14205        public final void addProvider(PackageParser.Provider p) {
14206            if (mProviders.containsKey(p.getComponentName())) {
14207                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
14208                return;
14209            }
14210
14211            mProviders.put(p.getComponentName(), p);
14212            if (DEBUG_SHOW_INFO) {
14213                Log.v(TAG, "  "
14214                        + (p.info.nonLocalizedLabel != null
14215                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
14216                Log.v(TAG, "    Class=" + p.info.name);
14217            }
14218            final int NI = p.intents.size();
14219            int j;
14220            for (j = 0; j < NI; j++) {
14221                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
14222                if (DEBUG_SHOW_INFO) {
14223                    Log.v(TAG, "    IntentFilter:");
14224                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14225                }
14226                if (!intent.debugCheck()) {
14227                    Log.w(TAG, "==> For Provider " + p.info.name);
14228                }
14229                addFilter(intent);
14230            }
14231        }
14232
14233        public final void removeProvider(PackageParser.Provider p) {
14234            mProviders.remove(p.getComponentName());
14235            if (DEBUG_SHOW_INFO) {
14236                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
14237                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
14238                Log.v(TAG, "    Class=" + p.info.name);
14239            }
14240            final int NI = p.intents.size();
14241            int j;
14242            for (j = 0; j < NI; j++) {
14243                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
14244                if (DEBUG_SHOW_INFO) {
14245                    Log.v(TAG, "    IntentFilter:");
14246                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14247                }
14248                removeFilter(intent);
14249            }
14250        }
14251
14252        @Override
14253        protected boolean allowFilterResult(
14254                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
14255            ProviderInfo filterPi = filter.provider.info;
14256            for (int i = dest.size() - 1; i >= 0; i--) {
14257                ProviderInfo destPi = dest.get(i).providerInfo;
14258                if (destPi.name == filterPi.name
14259                        && destPi.packageName == filterPi.packageName) {
14260                    return false;
14261                }
14262            }
14263            return true;
14264        }
14265
14266        @Override
14267        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
14268            return new PackageParser.ProviderIntentInfo[size];
14269        }
14270
14271        @Override
14272        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
14273            if (!sUserManager.exists(userId))
14274                return true;
14275            PackageParser.Package p = filter.provider.owner;
14276            if (p != null) {
14277                PackageSetting ps = (PackageSetting) p.mExtras;
14278                if (ps != null) {
14279                    // System apps are never considered stopped for purposes of
14280                    // filtering, because there may be no way for the user to
14281                    // actually re-launch them.
14282                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
14283                            && ps.getStopped(userId);
14284                }
14285            }
14286            return false;
14287        }
14288
14289        @Override
14290        protected boolean isPackageForFilter(String packageName,
14291                PackageParser.ProviderIntentInfo info) {
14292            return packageName.equals(info.provider.owner.packageName);
14293        }
14294
14295        @Override
14296        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
14297                int match, int userId) {
14298            if (!sUserManager.exists(userId))
14299                return null;
14300            final PackageParser.ProviderIntentInfo info = filter;
14301            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
14302                return null;
14303            }
14304            final PackageParser.Provider provider = info.provider;
14305            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
14306            if (ps == null) {
14307                return null;
14308            }
14309            final PackageUserState userState = ps.readUserState(userId);
14310            final boolean matchVisibleToInstantApp =
14311                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
14312            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
14313            // throw out filters that aren't visible to instant applications
14314            if (matchVisibleToInstantApp
14315                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
14316                return null;
14317            }
14318            // throw out instant application filters if we're not explicitly requesting them
14319            if (!isInstantApp && userState.instantApp) {
14320                return null;
14321            }
14322            // throw out instant application filters if updates are available; will trigger
14323            // instant application resolution
14324            if (userState.instantApp && ps.isUpdateAvailable()) {
14325                return null;
14326            }
14327            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
14328                    userState, userId);
14329            if (pi == null) {
14330                return null;
14331            }
14332            final ResolveInfo res = new ResolveInfo();
14333            res.providerInfo = pi;
14334            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
14335                res.filter = filter;
14336            }
14337            res.priority = info.getPriority();
14338            res.preferredOrder = provider.owner.mPreferredOrder;
14339            res.match = match;
14340            res.isDefault = info.hasDefault;
14341            res.labelRes = info.labelRes;
14342            res.nonLocalizedLabel = info.nonLocalizedLabel;
14343            res.icon = info.icon;
14344            res.system = res.providerInfo.applicationInfo.isSystemApp();
14345            return res;
14346        }
14347
14348        @Override
14349        protected void sortResults(List<ResolveInfo> results) {
14350            Collections.sort(results, mResolvePrioritySorter);
14351        }
14352
14353        @Override
14354        protected void dumpFilter(PrintWriter out, String prefix,
14355                PackageParser.ProviderIntentInfo filter) {
14356            out.print(prefix);
14357            out.print(
14358                    Integer.toHexString(System.identityHashCode(filter.provider)));
14359            out.print(' ');
14360            filter.provider.printComponentShortName(out);
14361            out.print(" filter ");
14362            out.println(Integer.toHexString(System.identityHashCode(filter)));
14363        }
14364
14365        @Override
14366        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
14367            return filter.provider;
14368        }
14369
14370        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
14371            PackageParser.Provider provider = (PackageParser.Provider)label;
14372            out.print(prefix); out.print(
14373                    Integer.toHexString(System.identityHashCode(provider)));
14374                    out.print(' ');
14375                    provider.printComponentShortName(out);
14376            if (count > 1) {
14377                out.print(" ("); out.print(count); out.print(" filters)");
14378            }
14379            out.println();
14380        }
14381
14382        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
14383                = new ArrayMap<ComponentName, PackageParser.Provider>();
14384        private int mFlags;
14385    }
14386
14387    static final class EphemeralIntentResolver
14388            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
14389        /**
14390         * The result that has the highest defined order. Ordering applies on a
14391         * per-package basis. Mapping is from package name to Pair of order and
14392         * EphemeralResolveInfo.
14393         * <p>
14394         * NOTE: This is implemented as a field variable for convenience and efficiency.
14395         * By having a field variable, we're able to track filter ordering as soon as
14396         * a non-zero order is defined. Otherwise, multiple loops across the result set
14397         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
14398         * this needs to be contained entirely within {@link #filterResults}.
14399         */
14400        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
14401
14402        @Override
14403        protected AuxiliaryResolveInfo[] newArray(int size) {
14404            return new AuxiliaryResolveInfo[size];
14405        }
14406
14407        @Override
14408        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
14409            return true;
14410        }
14411
14412        @Override
14413        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
14414                int userId) {
14415            if (!sUserManager.exists(userId)) {
14416                return null;
14417            }
14418            final String packageName = responseObj.resolveInfo.getPackageName();
14419            final Integer order = responseObj.getOrder();
14420            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
14421                    mOrderResult.get(packageName);
14422            // ordering is enabled and this item's order isn't high enough
14423            if (lastOrderResult != null && lastOrderResult.first >= order) {
14424                return null;
14425            }
14426            final InstantAppResolveInfo res = responseObj.resolveInfo;
14427            if (order > 0) {
14428                // non-zero order, enable ordering
14429                mOrderResult.put(packageName, new Pair<>(order, res));
14430            }
14431            return responseObj;
14432        }
14433
14434        @Override
14435        protected void filterResults(List<AuxiliaryResolveInfo> results) {
14436            // only do work if ordering is enabled [most of the time it won't be]
14437            if (mOrderResult.size() == 0) {
14438                return;
14439            }
14440            int resultSize = results.size();
14441            for (int i = 0; i < resultSize; i++) {
14442                final InstantAppResolveInfo info = results.get(i).resolveInfo;
14443                final String packageName = info.getPackageName();
14444                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
14445                if (savedInfo == null) {
14446                    // package doesn't having ordering
14447                    continue;
14448                }
14449                if (savedInfo.second == info) {
14450                    // circled back to the highest ordered item; remove from order list
14451                    mOrderResult.remove(packageName);
14452                    if (mOrderResult.size() == 0) {
14453                        // no more ordered items
14454                        break;
14455                    }
14456                    continue;
14457                }
14458                // item has a worse order, remove it from the result list
14459                results.remove(i);
14460                resultSize--;
14461                i--;
14462            }
14463        }
14464    }
14465
14466    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
14467            new Comparator<ResolveInfo>() {
14468        public int compare(ResolveInfo r1, ResolveInfo r2) {
14469            int v1 = r1.priority;
14470            int v2 = r2.priority;
14471            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
14472            if (v1 != v2) {
14473                return (v1 > v2) ? -1 : 1;
14474            }
14475            v1 = r1.preferredOrder;
14476            v2 = r2.preferredOrder;
14477            if (v1 != v2) {
14478                return (v1 > v2) ? -1 : 1;
14479            }
14480            if (r1.isDefault != r2.isDefault) {
14481                return r1.isDefault ? -1 : 1;
14482            }
14483            v1 = r1.match;
14484            v2 = r2.match;
14485            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
14486            if (v1 != v2) {
14487                return (v1 > v2) ? -1 : 1;
14488            }
14489            if (r1.system != r2.system) {
14490                return r1.system ? -1 : 1;
14491            }
14492            if (r1.activityInfo != null) {
14493                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
14494            }
14495            if (r1.serviceInfo != null) {
14496                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
14497            }
14498            if (r1.providerInfo != null) {
14499                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
14500            }
14501            return 0;
14502        }
14503    };
14504
14505    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
14506            new Comparator<ProviderInfo>() {
14507        public int compare(ProviderInfo p1, ProviderInfo p2) {
14508            final int v1 = p1.initOrder;
14509            final int v2 = p2.initOrder;
14510            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
14511        }
14512    };
14513
14514    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
14515            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
14516            final int[] userIds) {
14517        mHandler.post(new Runnable() {
14518            @Override
14519            public void run() {
14520                try {
14521                    final IActivityManager am = ActivityManager.getService();
14522                    if (am == null) return;
14523                    final int[] resolvedUserIds;
14524                    if (userIds == null) {
14525                        resolvedUserIds = am.getRunningUserIds();
14526                    } else {
14527                        resolvedUserIds = userIds;
14528                    }
14529                    for (int id : resolvedUserIds) {
14530                        final Intent intent = new Intent(action,
14531                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
14532                        if (extras != null) {
14533                            intent.putExtras(extras);
14534                        }
14535                        if (targetPkg != null) {
14536                            intent.setPackage(targetPkg);
14537                        }
14538                        // Modify the UID when posting to other users
14539                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
14540                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
14541                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
14542                            intent.putExtra(Intent.EXTRA_UID, uid);
14543                        }
14544                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
14545                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
14546                        if (DEBUG_BROADCASTS) {
14547                            RuntimeException here = new RuntimeException("here");
14548                            here.fillInStackTrace();
14549                            Slog.d(TAG, "Sending to user " + id + ": "
14550                                    + intent.toShortString(false, true, false, false)
14551                                    + " " + intent.getExtras(), here);
14552                        }
14553                        am.broadcastIntent(null, intent, null, finishedReceiver,
14554                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
14555                                null, finishedReceiver != null, false, id);
14556                    }
14557                } catch (RemoteException ex) {
14558                }
14559            }
14560        });
14561    }
14562
14563    /**
14564     * Check if the external storage media is available. This is true if there
14565     * is a mounted external storage medium or if the external storage is
14566     * emulated.
14567     */
14568    private boolean isExternalMediaAvailable() {
14569        return mMediaMounted || Environment.isExternalStorageEmulated();
14570    }
14571
14572    @Override
14573    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
14574        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14575            return null;
14576        }
14577        // writer
14578        synchronized (mPackages) {
14579            if (!isExternalMediaAvailable()) {
14580                // If the external storage is no longer mounted at this point,
14581                // the caller may not have been able to delete all of this
14582                // packages files and can not delete any more.  Bail.
14583                return null;
14584            }
14585            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14586            if (lastPackage != null) {
14587                pkgs.remove(lastPackage);
14588            }
14589            if (pkgs.size() > 0) {
14590                return pkgs.get(0);
14591            }
14592        }
14593        return null;
14594    }
14595
14596    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14597        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14598                userId, andCode ? 1 : 0, packageName);
14599        if (mSystemReady) {
14600            msg.sendToTarget();
14601        } else {
14602            if (mPostSystemReadyMessages == null) {
14603                mPostSystemReadyMessages = new ArrayList<>();
14604            }
14605            mPostSystemReadyMessages.add(msg);
14606        }
14607    }
14608
14609    void startCleaningPackages() {
14610        // reader
14611        if (!isExternalMediaAvailable()) {
14612            return;
14613        }
14614        synchronized (mPackages) {
14615            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14616                return;
14617            }
14618        }
14619        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14620        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14621        IActivityManager am = ActivityManager.getService();
14622        if (am != null) {
14623            int dcsUid = -1;
14624            synchronized (mPackages) {
14625                if (!mDefaultContainerWhitelisted) {
14626                    mDefaultContainerWhitelisted = true;
14627                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14628                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14629                }
14630            }
14631            try {
14632                if (dcsUid > 0) {
14633                    am.backgroundWhitelistUid(dcsUid);
14634                }
14635                am.startService(null, intent, null, false, mContext.getOpPackageName(),
14636                        UserHandle.USER_SYSTEM);
14637            } catch (RemoteException e) {
14638            }
14639        }
14640    }
14641
14642    @Override
14643    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14644            int installFlags, String installerPackageName, int userId) {
14645        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14646
14647        final int callingUid = Binder.getCallingUid();
14648        enforceCrossUserPermission(callingUid, userId,
14649                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14650
14651        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14652            try {
14653                if (observer != null) {
14654                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14655                }
14656            } catch (RemoteException re) {
14657            }
14658            return;
14659        }
14660
14661        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14662            installFlags |= PackageManager.INSTALL_FROM_ADB;
14663
14664        } else {
14665            // Caller holds INSTALL_PACKAGES permission, so we're less strict
14666            // about installerPackageName.
14667
14668            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14669            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14670        }
14671
14672        UserHandle user;
14673        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14674            user = UserHandle.ALL;
14675        } else {
14676            user = new UserHandle(userId);
14677        }
14678
14679        // Only system components can circumvent runtime permissions when installing.
14680        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14681                && mContext.checkCallingOrSelfPermission(Manifest.permission
14682                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14683            throw new SecurityException("You need the "
14684                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14685                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14686        }
14687
14688        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14689                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14690            throw new IllegalArgumentException(
14691                    "New installs into ASEC containers no longer supported");
14692        }
14693
14694        final File originFile = new File(originPath);
14695        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14696
14697        final Message msg = mHandler.obtainMessage(INIT_COPY);
14698        final VerificationInfo verificationInfo = new VerificationInfo(
14699                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14700        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14701                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14702                null /*packageAbiOverride*/, null /*grantedPermissions*/,
14703                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14704        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14705        msg.obj = params;
14706
14707        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14708                System.identityHashCode(msg.obj));
14709        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14710                System.identityHashCode(msg.obj));
14711
14712        mHandler.sendMessage(msg);
14713    }
14714
14715
14716    /**
14717     * Ensure that the install reason matches what we know about the package installer (e.g. whether
14718     * it is acting on behalf on an enterprise or the user).
14719     *
14720     * Note that the ordering of the conditionals in this method is important. The checks we perform
14721     * are as follows, in this order:
14722     *
14723     * 1) If the install is being performed by a system app, we can trust the app to have set the
14724     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14725     *    what it is.
14726     * 2) If the install is being performed by a device or profile owner app, the install reason
14727     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14728     *    set the install reason correctly. If the app targets an older SDK version where install
14729     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14730     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14731     * 3) In all other cases, the install is being performed by a regular app that is neither part
14732     *    of the system nor a device or profile owner. We have no reason to believe that this app is
14733     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14734     *    set to enterprise policy and if so, change it to unknown instead.
14735     */
14736    private int fixUpInstallReason(String installerPackageName, int installerUid,
14737            int installReason) {
14738        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14739                == PERMISSION_GRANTED) {
14740            // If the install is being performed by a system app, we trust that app to have set the
14741            // install reason correctly.
14742            return installReason;
14743        }
14744
14745        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14746            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14747        if (dpm != null) {
14748            ComponentName owner = null;
14749            try {
14750                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14751                if (owner == null) {
14752                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14753                }
14754            } catch (RemoteException e) {
14755            }
14756            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14757                // If the install is being performed by a device or profile owner, the install
14758                // reason should be enterprise policy.
14759                return PackageManager.INSTALL_REASON_POLICY;
14760            }
14761        }
14762
14763        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14764            // If the install is being performed by a regular app (i.e. neither system app nor
14765            // device or profile owner), we have no reason to believe that the app is acting on
14766            // behalf of an enterprise. If the app set the install reason to enterprise policy,
14767            // change it to unknown instead.
14768            return PackageManager.INSTALL_REASON_UNKNOWN;
14769        }
14770
14771        // If the install is being performed by a regular app and the install reason was set to any
14772        // value but enterprise policy, leave the install reason unchanged.
14773        return installReason;
14774    }
14775
14776    void installStage(String packageName, File stagedDir, String stagedCid,
14777            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14778            String installerPackageName, int installerUid, UserHandle user,
14779            Certificate[][] certificates) {
14780        if (DEBUG_EPHEMERAL) {
14781            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14782                Slog.d(TAG, "Ephemeral install of " + packageName);
14783            }
14784        }
14785        final VerificationInfo verificationInfo = new VerificationInfo(
14786                sessionParams.originatingUri, sessionParams.referrerUri,
14787                sessionParams.originatingUid, installerUid);
14788
14789        final OriginInfo origin;
14790        if (stagedDir != null) {
14791            origin = OriginInfo.fromStagedFile(stagedDir);
14792        } else {
14793            origin = OriginInfo.fromStagedContainer(stagedCid);
14794        }
14795
14796        final Message msg = mHandler.obtainMessage(INIT_COPY);
14797        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14798                sessionParams.installReason);
14799        final InstallParams params = new InstallParams(origin, null, observer,
14800                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14801                verificationInfo, user, sessionParams.abiOverride,
14802                sessionParams.grantedRuntimePermissions, certificates, installReason);
14803        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14804        msg.obj = params;
14805
14806        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14807                System.identityHashCode(msg.obj));
14808        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14809                System.identityHashCode(msg.obj));
14810
14811        mHandler.sendMessage(msg);
14812    }
14813
14814    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14815            int userId) {
14816        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14817        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
14818                false /*startReceiver*/, pkgSetting.appId, userId);
14819
14820        // Send a session commit broadcast
14821        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14822        info.installReason = pkgSetting.getInstallReason(userId);
14823        info.appPackageName = packageName;
14824        sendSessionCommitBroadcast(info, userId);
14825    }
14826
14827    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
14828            boolean includeStopped, int appId, int... userIds) {
14829        if (ArrayUtils.isEmpty(userIds)) {
14830            return;
14831        }
14832        Bundle extras = new Bundle(1);
14833        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14834        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14835
14836        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14837                packageName, extras, 0, null, null, userIds);
14838        if (sendBootCompleted) {
14839            mHandler.post(() -> {
14840                        for (int userId : userIds) {
14841                            sendBootCompletedBroadcastToSystemApp(
14842                                    packageName, includeStopped, userId);
14843                        }
14844                    }
14845            );
14846        }
14847    }
14848
14849    /**
14850     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14851     * automatically without needing an explicit launch.
14852     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14853     */
14854    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
14855            int userId) {
14856        // If user is not running, the app didn't miss any broadcast
14857        if (!mUserManagerInternal.isUserRunning(userId)) {
14858            return;
14859        }
14860        final IActivityManager am = ActivityManager.getService();
14861        try {
14862            // Deliver LOCKED_BOOT_COMPLETED first
14863            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14864                    .setPackage(packageName);
14865            if (includeStopped) {
14866                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14867            }
14868            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14869            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14870                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14871
14872            // Deliver BOOT_COMPLETED only if user is unlocked
14873            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14874                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14875                if (includeStopped) {
14876                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14877                }
14878                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14879                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14880            }
14881        } catch (RemoteException e) {
14882            throw e.rethrowFromSystemServer();
14883        }
14884    }
14885
14886    @Override
14887    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14888            int userId) {
14889        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14890        PackageSetting pkgSetting;
14891        final int callingUid = Binder.getCallingUid();
14892        enforceCrossUserPermission(callingUid, userId,
14893                true /* requireFullPermission */, true /* checkShell */,
14894                "setApplicationHiddenSetting for user " + userId);
14895
14896        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14897            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14898            return false;
14899        }
14900
14901        long callingId = Binder.clearCallingIdentity();
14902        try {
14903            boolean sendAdded = false;
14904            boolean sendRemoved = false;
14905            // writer
14906            synchronized (mPackages) {
14907                pkgSetting = mSettings.mPackages.get(packageName);
14908                if (pkgSetting == null) {
14909                    return false;
14910                }
14911                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14912                    return false;
14913                }
14914                // Do not allow "android" is being disabled
14915                if ("android".equals(packageName)) {
14916                    Slog.w(TAG, "Cannot hide package: android");
14917                    return false;
14918                }
14919                // Cannot hide static shared libs as they are considered
14920                // a part of the using app (emulating static linking). Also
14921                // static libs are installed always on internal storage.
14922                PackageParser.Package pkg = mPackages.get(packageName);
14923                if (pkg != null && pkg.staticSharedLibName != null) {
14924                    Slog.w(TAG, "Cannot hide package: " + packageName
14925                            + " providing static shared library: "
14926                            + pkg.staticSharedLibName);
14927                    return false;
14928                }
14929                // Only allow protected packages to hide themselves.
14930                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14931                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14932                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14933                    return false;
14934                }
14935
14936                if (pkgSetting.getHidden(userId) != hidden) {
14937                    pkgSetting.setHidden(hidden, userId);
14938                    mSettings.writePackageRestrictionsLPr(userId);
14939                    if (hidden) {
14940                        sendRemoved = true;
14941                    } else {
14942                        sendAdded = true;
14943                    }
14944                }
14945            }
14946            if (sendAdded) {
14947                sendPackageAddedForUser(packageName, pkgSetting, userId);
14948                return true;
14949            }
14950            if (sendRemoved) {
14951                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14952                        "hiding pkg");
14953                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14954                return true;
14955            }
14956        } finally {
14957            Binder.restoreCallingIdentity(callingId);
14958        }
14959        return false;
14960    }
14961
14962    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14963            int userId) {
14964        final PackageRemovedInfo info = new PackageRemovedInfo(this);
14965        info.removedPackage = packageName;
14966        info.installerPackageName = pkgSetting.installerPackageName;
14967        info.removedUsers = new int[] {userId};
14968        info.broadcastUsers = new int[] {userId};
14969        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14970        info.sendPackageRemovedBroadcasts(true /*killApp*/);
14971    }
14972
14973    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14974        if (pkgList.length > 0) {
14975            Bundle extras = new Bundle(1);
14976            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14977
14978            sendPackageBroadcast(
14979                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14980                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
14981                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14982                    new int[] {userId});
14983        }
14984    }
14985
14986    /**
14987     * Returns true if application is not found or there was an error. Otherwise it returns
14988     * the hidden state of the package for the given user.
14989     */
14990    @Override
14991    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14992        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14993        final int callingUid = Binder.getCallingUid();
14994        enforceCrossUserPermission(callingUid, userId,
14995                true /* requireFullPermission */, false /* checkShell */,
14996                "getApplicationHidden for user " + userId);
14997        PackageSetting ps;
14998        long callingId = Binder.clearCallingIdentity();
14999        try {
15000            // writer
15001            synchronized (mPackages) {
15002                ps = mSettings.mPackages.get(packageName);
15003                if (ps == null) {
15004                    return true;
15005                }
15006                if (filterAppAccessLPr(ps, callingUid, userId)) {
15007                    return true;
15008                }
15009                return ps.getHidden(userId);
15010            }
15011        } finally {
15012            Binder.restoreCallingIdentity(callingId);
15013        }
15014    }
15015
15016    /**
15017     * @hide
15018     */
15019    @Override
15020    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
15021            int installReason) {
15022        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
15023                null);
15024        PackageSetting pkgSetting;
15025        final int callingUid = Binder.getCallingUid();
15026        enforceCrossUserPermission(callingUid, userId,
15027                true /* requireFullPermission */, true /* checkShell */,
15028                "installExistingPackage for user " + userId);
15029        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
15030            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
15031        }
15032
15033        long callingId = Binder.clearCallingIdentity();
15034        try {
15035            boolean installed = false;
15036            final boolean instantApp =
15037                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15038            final boolean fullApp =
15039                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
15040
15041            // writer
15042            synchronized (mPackages) {
15043                pkgSetting = mSettings.mPackages.get(packageName);
15044                if (pkgSetting == null) {
15045                    return PackageManager.INSTALL_FAILED_INVALID_URI;
15046                }
15047                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
15048                    // only allow the existing package to be used if it's installed as a full
15049                    // application for at least one user
15050                    boolean installAllowed = false;
15051                    for (int checkUserId : sUserManager.getUserIds()) {
15052                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
15053                        if (installAllowed) {
15054                            break;
15055                        }
15056                    }
15057                    if (!installAllowed) {
15058                        return PackageManager.INSTALL_FAILED_INVALID_URI;
15059                    }
15060                }
15061                if (!pkgSetting.getInstalled(userId)) {
15062                    pkgSetting.setInstalled(true, userId);
15063                    pkgSetting.setHidden(false, userId);
15064                    pkgSetting.setInstallReason(installReason, userId);
15065                    mSettings.writePackageRestrictionsLPr(userId);
15066                    mSettings.writeKernelMappingLPr(pkgSetting);
15067                    installed = true;
15068                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
15069                    // upgrade app from instant to full; we don't allow app downgrade
15070                    installed = true;
15071                }
15072                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
15073            }
15074
15075            if (installed) {
15076                if (pkgSetting.pkg != null) {
15077                    synchronized (mInstallLock) {
15078                        // We don't need to freeze for a brand new install
15079                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
15080                    }
15081                }
15082                sendPackageAddedForUser(packageName, pkgSetting, userId);
15083                synchronized (mPackages) {
15084                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
15085                }
15086            }
15087        } finally {
15088            Binder.restoreCallingIdentity(callingId);
15089        }
15090
15091        return PackageManager.INSTALL_SUCCEEDED;
15092    }
15093
15094    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
15095            boolean instantApp, boolean fullApp) {
15096        // no state specified; do nothing
15097        if (!instantApp && !fullApp) {
15098            return;
15099        }
15100        if (userId != UserHandle.USER_ALL) {
15101            if (instantApp && !pkgSetting.getInstantApp(userId)) {
15102                pkgSetting.setInstantApp(true /*instantApp*/, userId);
15103            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
15104                pkgSetting.setInstantApp(false /*instantApp*/, userId);
15105            }
15106        } else {
15107            for (int currentUserId : sUserManager.getUserIds()) {
15108                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
15109                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
15110                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
15111                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
15112                }
15113            }
15114        }
15115    }
15116
15117    boolean isUserRestricted(int userId, String restrictionKey) {
15118        Bundle restrictions = sUserManager.getUserRestrictions(userId);
15119        if (restrictions.getBoolean(restrictionKey, false)) {
15120            Log.w(TAG, "User is restricted: " + restrictionKey);
15121            return true;
15122        }
15123        return false;
15124    }
15125
15126    @Override
15127    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
15128            int userId) {
15129        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
15130        final int callingUid = Binder.getCallingUid();
15131        enforceCrossUserPermission(callingUid, userId,
15132                true /* requireFullPermission */, true /* checkShell */,
15133                "setPackagesSuspended for user " + userId);
15134
15135        if (ArrayUtils.isEmpty(packageNames)) {
15136            return packageNames;
15137        }
15138
15139        // List of package names for whom the suspended state has changed.
15140        List<String> changedPackages = new ArrayList<>(packageNames.length);
15141        // List of package names for whom the suspended state is not set as requested in this
15142        // method.
15143        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
15144        long callingId = Binder.clearCallingIdentity();
15145        try {
15146            for (int i = 0; i < packageNames.length; i++) {
15147                String packageName = packageNames[i];
15148                boolean changed = false;
15149                final int appId;
15150                synchronized (mPackages) {
15151                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
15152                    if (pkgSetting == null
15153                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
15154                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
15155                                + "\". Skipping suspending/un-suspending.");
15156                        unactionedPackages.add(packageName);
15157                        continue;
15158                    }
15159                    appId = pkgSetting.appId;
15160                    if (pkgSetting.getSuspended(userId) != suspended) {
15161                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
15162                            unactionedPackages.add(packageName);
15163                            continue;
15164                        }
15165                        pkgSetting.setSuspended(suspended, userId);
15166                        mSettings.writePackageRestrictionsLPr(userId);
15167                        changed = true;
15168                        changedPackages.add(packageName);
15169                    }
15170                }
15171
15172                if (changed && suspended) {
15173                    killApplication(packageName, UserHandle.getUid(userId, appId),
15174                            "suspending package");
15175                }
15176            }
15177        } finally {
15178            Binder.restoreCallingIdentity(callingId);
15179        }
15180
15181        if (!changedPackages.isEmpty()) {
15182            sendPackagesSuspendedForUser(changedPackages.toArray(
15183                    new String[changedPackages.size()]), userId, suspended);
15184        }
15185
15186        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
15187    }
15188
15189    @Override
15190    public boolean isPackageSuspendedForUser(String packageName, int userId) {
15191        final int callingUid = Binder.getCallingUid();
15192        enforceCrossUserPermission(callingUid, userId,
15193                true /* requireFullPermission */, false /* checkShell */,
15194                "isPackageSuspendedForUser for user " + userId);
15195        synchronized (mPackages) {
15196            final PackageSetting ps = mSettings.mPackages.get(packageName);
15197            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
15198                throw new IllegalArgumentException("Unknown target package: " + packageName);
15199            }
15200            return ps.getSuspended(userId);
15201        }
15202    }
15203
15204    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
15205        if (isPackageDeviceAdmin(packageName, userId)) {
15206            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15207                    + "\": has an active device admin");
15208            return false;
15209        }
15210
15211        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
15212        if (packageName.equals(activeLauncherPackageName)) {
15213            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15214                    + "\": contains the active launcher");
15215            return false;
15216        }
15217
15218        if (packageName.equals(mRequiredInstallerPackage)) {
15219            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15220                    + "\": required for package installation");
15221            return false;
15222        }
15223
15224        if (packageName.equals(mRequiredUninstallerPackage)) {
15225            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15226                    + "\": required for package uninstallation");
15227            return false;
15228        }
15229
15230        if (packageName.equals(mRequiredVerifierPackage)) {
15231            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15232                    + "\": required for package verification");
15233            return false;
15234        }
15235
15236        if (packageName.equals(getDefaultDialerPackageName(userId))) {
15237            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15238                    + "\": is the default dialer");
15239            return false;
15240        }
15241
15242        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
15243            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15244                    + "\": protected package");
15245            return false;
15246        }
15247
15248        // Cannot suspend static shared libs as they are considered
15249        // a part of the using app (emulating static linking). Also
15250        // static libs are installed always on internal storage.
15251        PackageParser.Package pkg = mPackages.get(packageName);
15252        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
15253            Slog.w(TAG, "Cannot suspend package: " + packageName
15254                    + " providing static shared library: "
15255                    + pkg.staticSharedLibName);
15256            return false;
15257        }
15258
15259        return true;
15260    }
15261
15262    private String getActiveLauncherPackageName(int userId) {
15263        Intent intent = new Intent(Intent.ACTION_MAIN);
15264        intent.addCategory(Intent.CATEGORY_HOME);
15265        ResolveInfo resolveInfo = resolveIntent(
15266                intent,
15267                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
15268                PackageManager.MATCH_DEFAULT_ONLY,
15269                userId);
15270
15271        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
15272    }
15273
15274    private String getDefaultDialerPackageName(int userId) {
15275        synchronized (mPackages) {
15276            return mSettings.getDefaultDialerPackageNameLPw(userId);
15277        }
15278    }
15279
15280    @Override
15281    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
15282        mContext.enforceCallingOrSelfPermission(
15283                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15284                "Only package verification agents can verify applications");
15285
15286        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
15287        final PackageVerificationResponse response = new PackageVerificationResponse(
15288                verificationCode, Binder.getCallingUid());
15289        msg.arg1 = id;
15290        msg.obj = response;
15291        mHandler.sendMessage(msg);
15292    }
15293
15294    @Override
15295    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
15296            long millisecondsToDelay) {
15297        mContext.enforceCallingOrSelfPermission(
15298                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15299                "Only package verification agents can extend verification timeouts");
15300
15301        final PackageVerificationState state = mPendingVerification.get(id);
15302        final PackageVerificationResponse response = new PackageVerificationResponse(
15303                verificationCodeAtTimeout, Binder.getCallingUid());
15304
15305        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
15306            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
15307        }
15308        if (millisecondsToDelay < 0) {
15309            millisecondsToDelay = 0;
15310        }
15311        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
15312                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
15313            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
15314        }
15315
15316        if ((state != null) && !state.timeoutExtended()) {
15317            state.extendTimeout();
15318
15319            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
15320            msg.arg1 = id;
15321            msg.obj = response;
15322            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
15323        }
15324    }
15325
15326    private void broadcastPackageVerified(int verificationId, Uri packageUri,
15327            int verificationCode, UserHandle user) {
15328        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
15329        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
15330        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15331        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15332        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
15333
15334        mContext.sendBroadcastAsUser(intent, user,
15335                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
15336    }
15337
15338    private ComponentName matchComponentForVerifier(String packageName,
15339            List<ResolveInfo> receivers) {
15340        ActivityInfo targetReceiver = null;
15341
15342        final int NR = receivers.size();
15343        for (int i = 0; i < NR; i++) {
15344            final ResolveInfo info = receivers.get(i);
15345            if (info.activityInfo == null) {
15346                continue;
15347            }
15348
15349            if (packageName.equals(info.activityInfo.packageName)) {
15350                targetReceiver = info.activityInfo;
15351                break;
15352            }
15353        }
15354
15355        if (targetReceiver == null) {
15356            return null;
15357        }
15358
15359        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
15360    }
15361
15362    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
15363            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
15364        if (pkgInfo.verifiers.length == 0) {
15365            return null;
15366        }
15367
15368        final int N = pkgInfo.verifiers.length;
15369        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
15370        for (int i = 0; i < N; i++) {
15371            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
15372
15373            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
15374                    receivers);
15375            if (comp == null) {
15376                continue;
15377            }
15378
15379            final int verifierUid = getUidForVerifier(verifierInfo);
15380            if (verifierUid == -1) {
15381                continue;
15382            }
15383
15384            if (DEBUG_VERIFY) {
15385                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
15386                        + " with the correct signature");
15387            }
15388            sufficientVerifiers.add(comp);
15389            verificationState.addSufficientVerifier(verifierUid);
15390        }
15391
15392        return sufficientVerifiers;
15393    }
15394
15395    private int getUidForVerifier(VerifierInfo verifierInfo) {
15396        synchronized (mPackages) {
15397            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
15398            if (pkg == null) {
15399                return -1;
15400            } else if (pkg.mSignatures.length != 1) {
15401                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15402                        + " has more than one signature; ignoring");
15403                return -1;
15404            }
15405
15406            /*
15407             * If the public key of the package's signature does not match
15408             * our expected public key, then this is a different package and
15409             * we should skip.
15410             */
15411
15412            final byte[] expectedPublicKey;
15413            try {
15414                final Signature verifierSig = pkg.mSignatures[0];
15415                final PublicKey publicKey = verifierSig.getPublicKey();
15416                expectedPublicKey = publicKey.getEncoded();
15417            } catch (CertificateException e) {
15418                return -1;
15419            }
15420
15421            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
15422
15423            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
15424                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15425                        + " does not have the expected public key; ignoring");
15426                return -1;
15427            }
15428
15429            return pkg.applicationInfo.uid;
15430        }
15431    }
15432
15433    @Override
15434    public void finishPackageInstall(int token, boolean didLaunch) {
15435        enforceSystemOrRoot("Only the system is allowed to finish installs");
15436
15437        if (DEBUG_INSTALL) {
15438            Slog.v(TAG, "BM finishing package install for " + token);
15439        }
15440        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15441
15442        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
15443        mHandler.sendMessage(msg);
15444    }
15445
15446    /**
15447     * Get the verification agent timeout.  Used for both the APK verifier and the
15448     * intent filter verifier.
15449     *
15450     * @return verification timeout in milliseconds
15451     */
15452    private long getVerificationTimeout() {
15453        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
15454                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
15455                DEFAULT_VERIFICATION_TIMEOUT);
15456    }
15457
15458    /**
15459     * Get the default verification agent response code.
15460     *
15461     * @return default verification response code
15462     */
15463    private int getDefaultVerificationResponse(UserHandle user) {
15464        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
15465            return PackageManager.VERIFICATION_REJECT;
15466        }
15467        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15468                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
15469                DEFAULT_VERIFICATION_RESPONSE);
15470    }
15471
15472    /**
15473     * Check whether or not package verification has been enabled.
15474     *
15475     * @return true if verification should be performed
15476     */
15477    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
15478        if (!DEFAULT_VERIFY_ENABLE) {
15479            return false;
15480        }
15481
15482        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
15483
15484        // Check if installing from ADB
15485        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
15486            // Do not run verification in a test harness environment
15487            if (ActivityManager.isRunningInTestHarness()) {
15488                return false;
15489            }
15490            if (ensureVerifyAppsEnabled) {
15491                return true;
15492            }
15493            // Check if the developer does not want package verification for ADB installs
15494            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15495                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
15496                return false;
15497            }
15498        } else {
15499            // only when not installed from ADB, skip verification for instant apps when
15500            // the installer and verifier are the same.
15501            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
15502                if (mInstantAppInstallerActivity != null
15503                        && mInstantAppInstallerActivity.packageName.equals(
15504                                mRequiredVerifierPackage)) {
15505                    try {
15506                        mContext.getSystemService(AppOpsManager.class)
15507                                .checkPackage(installerUid, mRequiredVerifierPackage);
15508                        if (DEBUG_VERIFY) {
15509                            Slog.i(TAG, "disable verification for instant app");
15510                        }
15511                        return false;
15512                    } catch (SecurityException ignore) { }
15513                }
15514            }
15515        }
15516
15517        if (ensureVerifyAppsEnabled) {
15518            return true;
15519        }
15520
15521        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15522                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
15523    }
15524
15525    @Override
15526    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
15527            throws RemoteException {
15528        mContext.enforceCallingOrSelfPermission(
15529                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
15530                "Only intentfilter verification agents can verify applications");
15531
15532        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
15533        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
15534                Binder.getCallingUid(), verificationCode, failedDomains);
15535        msg.arg1 = id;
15536        msg.obj = response;
15537        mHandler.sendMessage(msg);
15538    }
15539
15540    @Override
15541    public int getIntentVerificationStatus(String packageName, int userId) {
15542        final int callingUid = Binder.getCallingUid();
15543        if (UserHandle.getUserId(callingUid) != userId) {
15544            mContext.enforceCallingOrSelfPermission(
15545                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15546                    "getIntentVerificationStatus" + userId);
15547        }
15548        if (getInstantAppPackageName(callingUid) != null) {
15549            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15550        }
15551        synchronized (mPackages) {
15552            final PackageSetting ps = mSettings.mPackages.get(packageName);
15553            if (ps == null
15554                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15555                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15556            }
15557            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
15558        }
15559    }
15560
15561    @Override
15562    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
15563        mContext.enforceCallingOrSelfPermission(
15564                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15565
15566        boolean result = false;
15567        synchronized (mPackages) {
15568            final PackageSetting ps = mSettings.mPackages.get(packageName);
15569            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15570                return false;
15571            }
15572            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
15573        }
15574        if (result) {
15575            scheduleWritePackageRestrictionsLocked(userId);
15576        }
15577        return result;
15578    }
15579
15580    @Override
15581    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
15582            String packageName) {
15583        final int callingUid = Binder.getCallingUid();
15584        if (getInstantAppPackageName(callingUid) != null) {
15585            return ParceledListSlice.emptyList();
15586        }
15587        synchronized (mPackages) {
15588            final PackageSetting ps = mSettings.mPackages.get(packageName);
15589            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15590                return ParceledListSlice.emptyList();
15591            }
15592            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
15593        }
15594    }
15595
15596    @Override
15597    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
15598        if (TextUtils.isEmpty(packageName)) {
15599            return ParceledListSlice.emptyList();
15600        }
15601        final int callingUid = Binder.getCallingUid();
15602        final int callingUserId = UserHandle.getUserId(callingUid);
15603        synchronized (mPackages) {
15604            PackageParser.Package pkg = mPackages.get(packageName);
15605            if (pkg == null || pkg.activities == null) {
15606                return ParceledListSlice.emptyList();
15607            }
15608            if (pkg.mExtras == null) {
15609                return ParceledListSlice.emptyList();
15610            }
15611            final PackageSetting ps = (PackageSetting) pkg.mExtras;
15612            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15613                return ParceledListSlice.emptyList();
15614            }
15615            final int count = pkg.activities.size();
15616            ArrayList<IntentFilter> result = new ArrayList<>();
15617            for (int n=0; n<count; n++) {
15618                PackageParser.Activity activity = pkg.activities.get(n);
15619                if (activity.intents != null && activity.intents.size() > 0) {
15620                    result.addAll(activity.intents);
15621                }
15622            }
15623            return new ParceledListSlice<>(result);
15624        }
15625    }
15626
15627    @Override
15628    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15629        mContext.enforceCallingOrSelfPermission(
15630                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15631        if (UserHandle.getCallingUserId() != userId) {
15632            mContext.enforceCallingOrSelfPermission(
15633                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15634        }
15635
15636        synchronized (mPackages) {
15637            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15638            if (packageName != null) {
15639                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
15640                        packageName, userId);
15641            }
15642            return result;
15643        }
15644    }
15645
15646    @Override
15647    public String getDefaultBrowserPackageName(int userId) {
15648        if (UserHandle.getCallingUserId() != userId) {
15649            mContext.enforceCallingOrSelfPermission(
15650                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15651        }
15652        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15653            return null;
15654        }
15655        synchronized (mPackages) {
15656            return mSettings.getDefaultBrowserPackageNameLPw(userId);
15657        }
15658    }
15659
15660    /**
15661     * Get the "allow unknown sources" setting.
15662     *
15663     * @return the current "allow unknown sources" setting
15664     */
15665    private int getUnknownSourcesSettings() {
15666        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15667                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15668                -1);
15669    }
15670
15671    @Override
15672    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15673        final int callingUid = Binder.getCallingUid();
15674        if (getInstantAppPackageName(callingUid) != null) {
15675            return;
15676        }
15677        // writer
15678        synchronized (mPackages) {
15679            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15680            if (targetPackageSetting == null
15681                    || filterAppAccessLPr(
15682                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15683                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15684            }
15685
15686            PackageSetting installerPackageSetting;
15687            if (installerPackageName != null) {
15688                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15689                if (installerPackageSetting == null) {
15690                    throw new IllegalArgumentException("Unknown installer package: "
15691                            + installerPackageName);
15692                }
15693            } else {
15694                installerPackageSetting = null;
15695            }
15696
15697            Signature[] callerSignature;
15698            Object obj = mSettings.getUserIdLPr(callingUid);
15699            if (obj != null) {
15700                if (obj instanceof SharedUserSetting) {
15701                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15702                } else if (obj instanceof PackageSetting) {
15703                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15704                } else {
15705                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15706                }
15707            } else {
15708                throw new SecurityException("Unknown calling UID: " + callingUid);
15709            }
15710
15711            // Verify: can't set installerPackageName to a package that is
15712            // not signed with the same cert as the caller.
15713            if (installerPackageSetting != null) {
15714                if (compareSignatures(callerSignature,
15715                        installerPackageSetting.signatures.mSignatures)
15716                        != PackageManager.SIGNATURE_MATCH) {
15717                    throw new SecurityException(
15718                            "Caller does not have same cert as new installer package "
15719                            + installerPackageName);
15720                }
15721            }
15722
15723            // Verify: if target already has an installer package, it must
15724            // be signed with the same cert as the caller.
15725            if (targetPackageSetting.installerPackageName != null) {
15726                PackageSetting setting = mSettings.mPackages.get(
15727                        targetPackageSetting.installerPackageName);
15728                // If the currently set package isn't valid, then it's always
15729                // okay to change it.
15730                if (setting != null) {
15731                    if (compareSignatures(callerSignature,
15732                            setting.signatures.mSignatures)
15733                            != PackageManager.SIGNATURE_MATCH) {
15734                        throw new SecurityException(
15735                                "Caller does not have same cert as old installer package "
15736                                + targetPackageSetting.installerPackageName);
15737                    }
15738                }
15739            }
15740
15741            // Okay!
15742            targetPackageSetting.installerPackageName = installerPackageName;
15743            if (installerPackageName != null) {
15744                mSettings.mInstallerPackages.add(installerPackageName);
15745            }
15746            scheduleWriteSettingsLocked();
15747        }
15748    }
15749
15750    @Override
15751    public void setApplicationCategoryHint(String packageName, int categoryHint,
15752            String callerPackageName) {
15753        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15754            throw new SecurityException("Instant applications don't have access to this method");
15755        }
15756        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15757                callerPackageName);
15758        synchronized (mPackages) {
15759            PackageSetting ps = mSettings.mPackages.get(packageName);
15760            if (ps == null) {
15761                throw new IllegalArgumentException("Unknown target package " + packageName);
15762            }
15763            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15764                throw new IllegalArgumentException("Unknown target package " + packageName);
15765            }
15766            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15767                throw new IllegalArgumentException("Calling package " + callerPackageName
15768                        + " is not installer for " + packageName);
15769            }
15770
15771            if (ps.categoryHint != categoryHint) {
15772                ps.categoryHint = categoryHint;
15773                scheduleWriteSettingsLocked();
15774            }
15775        }
15776    }
15777
15778    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15779        // Queue up an async operation since the package installation may take a little while.
15780        mHandler.post(new Runnable() {
15781            public void run() {
15782                mHandler.removeCallbacks(this);
15783                 // Result object to be returned
15784                PackageInstalledInfo res = new PackageInstalledInfo();
15785                res.setReturnCode(currentStatus);
15786                res.uid = -1;
15787                res.pkg = null;
15788                res.removedInfo = null;
15789                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15790                    args.doPreInstall(res.returnCode);
15791                    synchronized (mInstallLock) {
15792                        installPackageTracedLI(args, res);
15793                    }
15794                    args.doPostInstall(res.returnCode, res.uid);
15795                }
15796
15797                // A restore should be performed at this point if (a) the install
15798                // succeeded, (b) the operation is not an update, and (c) the new
15799                // package has not opted out of backup participation.
15800                final boolean update = res.removedInfo != null
15801                        && res.removedInfo.removedPackage != null;
15802                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15803                boolean doRestore = !update
15804                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15805
15806                // Set up the post-install work request bookkeeping.  This will be used
15807                // and cleaned up by the post-install event handling regardless of whether
15808                // there's a restore pass performed.  Token values are >= 1.
15809                int token;
15810                if (mNextInstallToken < 0) mNextInstallToken = 1;
15811                token = mNextInstallToken++;
15812
15813                PostInstallData data = new PostInstallData(args, res);
15814                mRunningInstalls.put(token, data);
15815                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15816
15817                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15818                    // Pass responsibility to the Backup Manager.  It will perform a
15819                    // restore if appropriate, then pass responsibility back to the
15820                    // Package Manager to run the post-install observer callbacks
15821                    // and broadcasts.
15822                    IBackupManager bm = IBackupManager.Stub.asInterface(
15823                            ServiceManager.getService(Context.BACKUP_SERVICE));
15824                    if (bm != null) {
15825                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15826                                + " to BM for possible restore");
15827                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15828                        try {
15829                            // TODO: http://b/22388012
15830                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15831                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15832                            } else {
15833                                doRestore = false;
15834                            }
15835                        } catch (RemoteException e) {
15836                            // can't happen; the backup manager is local
15837                        } catch (Exception e) {
15838                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15839                            doRestore = false;
15840                        }
15841                    } else {
15842                        Slog.e(TAG, "Backup Manager not found!");
15843                        doRestore = false;
15844                    }
15845                }
15846
15847                if (!doRestore) {
15848                    // No restore possible, or the Backup Manager was mysteriously not
15849                    // available -- just fire the post-install work request directly.
15850                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15851
15852                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15853
15854                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15855                    mHandler.sendMessage(msg);
15856                }
15857            }
15858        });
15859    }
15860
15861    /**
15862     * Callback from PackageSettings whenever an app is first transitioned out of the
15863     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15864     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15865     * here whether the app is the target of an ongoing install, and only send the
15866     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15867     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15868     * handling.
15869     */
15870    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15871        // Serialize this with the rest of the install-process message chain.  In the
15872        // restore-at-install case, this Runnable will necessarily run before the
15873        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15874        // are coherent.  In the non-restore case, the app has already completed install
15875        // and been launched through some other means, so it is not in a problematic
15876        // state for observers to see the FIRST_LAUNCH signal.
15877        mHandler.post(new Runnable() {
15878            @Override
15879            public void run() {
15880                for (int i = 0; i < mRunningInstalls.size(); i++) {
15881                    final PostInstallData data = mRunningInstalls.valueAt(i);
15882                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15883                        continue;
15884                    }
15885                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15886                        // right package; but is it for the right user?
15887                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15888                            if (userId == data.res.newUsers[uIndex]) {
15889                                if (DEBUG_BACKUP) {
15890                                    Slog.i(TAG, "Package " + pkgName
15891                                            + " being restored so deferring FIRST_LAUNCH");
15892                                }
15893                                return;
15894                            }
15895                        }
15896                    }
15897                }
15898                // didn't find it, so not being restored
15899                if (DEBUG_BACKUP) {
15900                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15901                }
15902                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15903            }
15904        });
15905    }
15906
15907    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15908        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15909                installerPkg, null, userIds);
15910    }
15911
15912    private abstract class HandlerParams {
15913        private static final int MAX_RETRIES = 4;
15914
15915        /**
15916         * Number of times startCopy() has been attempted and had a non-fatal
15917         * error.
15918         */
15919        private int mRetries = 0;
15920
15921        /** User handle for the user requesting the information or installation. */
15922        private final UserHandle mUser;
15923        String traceMethod;
15924        int traceCookie;
15925
15926        HandlerParams(UserHandle user) {
15927            mUser = user;
15928        }
15929
15930        UserHandle getUser() {
15931            return mUser;
15932        }
15933
15934        HandlerParams setTraceMethod(String traceMethod) {
15935            this.traceMethod = traceMethod;
15936            return this;
15937        }
15938
15939        HandlerParams setTraceCookie(int traceCookie) {
15940            this.traceCookie = traceCookie;
15941            return this;
15942        }
15943
15944        final boolean startCopy() {
15945            boolean res;
15946            try {
15947                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15948
15949                if (++mRetries > MAX_RETRIES) {
15950                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15951                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15952                    handleServiceError();
15953                    return false;
15954                } else {
15955                    handleStartCopy();
15956                    res = true;
15957                }
15958            } catch (RemoteException e) {
15959                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15960                mHandler.sendEmptyMessage(MCS_RECONNECT);
15961                res = false;
15962            }
15963            handleReturnCode();
15964            return res;
15965        }
15966
15967        final void serviceError() {
15968            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15969            handleServiceError();
15970            handleReturnCode();
15971        }
15972
15973        abstract void handleStartCopy() throws RemoteException;
15974        abstract void handleServiceError();
15975        abstract void handleReturnCode();
15976    }
15977
15978    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15979        for (File path : paths) {
15980            try {
15981                mcs.clearDirectory(path.getAbsolutePath());
15982            } catch (RemoteException e) {
15983            }
15984        }
15985    }
15986
15987    static class OriginInfo {
15988        /**
15989         * Location where install is coming from, before it has been
15990         * copied/renamed into place. This could be a single monolithic APK
15991         * file, or a cluster directory. This location may be untrusted.
15992         */
15993        final File file;
15994        final String cid;
15995
15996        /**
15997         * Flag indicating that {@link #file} or {@link #cid} has already been
15998         * staged, meaning downstream users don't need to defensively copy the
15999         * contents.
16000         */
16001        final boolean staged;
16002
16003        /**
16004         * Flag indicating that {@link #file} or {@link #cid} is an already
16005         * installed app that is being moved.
16006         */
16007        final boolean existing;
16008
16009        final String resolvedPath;
16010        final File resolvedFile;
16011
16012        static OriginInfo fromNothing() {
16013            return new OriginInfo(null, null, false, false);
16014        }
16015
16016        static OriginInfo fromUntrustedFile(File file) {
16017            return new OriginInfo(file, null, false, false);
16018        }
16019
16020        static OriginInfo fromExistingFile(File file) {
16021            return new OriginInfo(file, null, false, true);
16022        }
16023
16024        static OriginInfo fromStagedFile(File file) {
16025            return new OriginInfo(file, null, true, false);
16026        }
16027
16028        static OriginInfo fromStagedContainer(String cid) {
16029            return new OriginInfo(null, cid, true, false);
16030        }
16031
16032        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
16033            this.file = file;
16034            this.cid = cid;
16035            this.staged = staged;
16036            this.existing = existing;
16037
16038            if (cid != null) {
16039                resolvedPath = PackageHelper.getSdDir(cid);
16040                resolvedFile = new File(resolvedPath);
16041            } else if (file != null) {
16042                resolvedPath = file.getAbsolutePath();
16043                resolvedFile = file;
16044            } else {
16045                resolvedPath = null;
16046                resolvedFile = null;
16047            }
16048        }
16049    }
16050
16051    static class MoveInfo {
16052        final int moveId;
16053        final String fromUuid;
16054        final String toUuid;
16055        final String packageName;
16056        final String dataAppName;
16057        final int appId;
16058        final String seinfo;
16059        final int targetSdkVersion;
16060
16061        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
16062                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
16063            this.moveId = moveId;
16064            this.fromUuid = fromUuid;
16065            this.toUuid = toUuid;
16066            this.packageName = packageName;
16067            this.dataAppName = dataAppName;
16068            this.appId = appId;
16069            this.seinfo = seinfo;
16070            this.targetSdkVersion = targetSdkVersion;
16071        }
16072    }
16073
16074    static class VerificationInfo {
16075        /** A constant used to indicate that a uid value is not present. */
16076        public static final int NO_UID = -1;
16077
16078        /** URI referencing where the package was downloaded from. */
16079        final Uri originatingUri;
16080
16081        /** HTTP referrer URI associated with the originatingURI. */
16082        final Uri referrer;
16083
16084        /** UID of the application that the install request originated from. */
16085        final int originatingUid;
16086
16087        /** UID of application requesting the install */
16088        final int installerUid;
16089
16090        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
16091            this.originatingUri = originatingUri;
16092            this.referrer = referrer;
16093            this.originatingUid = originatingUid;
16094            this.installerUid = installerUid;
16095        }
16096    }
16097
16098    class InstallParams extends HandlerParams {
16099        final OriginInfo origin;
16100        final MoveInfo move;
16101        final IPackageInstallObserver2 observer;
16102        int installFlags;
16103        final String installerPackageName;
16104        final String volumeUuid;
16105        private InstallArgs mArgs;
16106        private int mRet;
16107        final String packageAbiOverride;
16108        final String[] grantedRuntimePermissions;
16109        final VerificationInfo verificationInfo;
16110        final Certificate[][] certificates;
16111        final int installReason;
16112
16113        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16114                int installFlags, String installerPackageName, String volumeUuid,
16115                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
16116                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
16117            super(user);
16118            this.origin = origin;
16119            this.move = move;
16120            this.observer = observer;
16121            this.installFlags = installFlags;
16122            this.installerPackageName = installerPackageName;
16123            this.volumeUuid = volumeUuid;
16124            this.verificationInfo = verificationInfo;
16125            this.packageAbiOverride = packageAbiOverride;
16126            this.grantedRuntimePermissions = grantedPermissions;
16127            this.certificates = certificates;
16128            this.installReason = installReason;
16129        }
16130
16131        @Override
16132        public String toString() {
16133            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
16134                    + " file=" + origin.file + " cid=" + origin.cid + "}";
16135        }
16136
16137        private int installLocationPolicy(PackageInfoLite pkgLite) {
16138            String packageName = pkgLite.packageName;
16139            int installLocation = pkgLite.installLocation;
16140            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16141            // reader
16142            synchronized (mPackages) {
16143                // Currently installed package which the new package is attempting to replace or
16144                // null if no such package is installed.
16145                PackageParser.Package installedPkg = mPackages.get(packageName);
16146                // Package which currently owns the data which the new package will own if installed.
16147                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
16148                // will be null whereas dataOwnerPkg will contain information about the package
16149                // which was uninstalled while keeping its data.
16150                PackageParser.Package dataOwnerPkg = installedPkg;
16151                if (dataOwnerPkg  == null) {
16152                    PackageSetting ps = mSettings.mPackages.get(packageName);
16153                    if (ps != null) {
16154                        dataOwnerPkg = ps.pkg;
16155                    }
16156                }
16157
16158                if (dataOwnerPkg != null) {
16159                    // If installed, the package will get access to data left on the device by its
16160                    // predecessor. As a security measure, this is permited only if this is not a
16161                    // version downgrade or if the predecessor package is marked as debuggable and
16162                    // a downgrade is explicitly requested.
16163                    //
16164                    // On debuggable platform builds, downgrades are permitted even for
16165                    // non-debuggable packages to make testing easier. Debuggable platform builds do
16166                    // not offer security guarantees and thus it's OK to disable some security
16167                    // mechanisms to make debugging/testing easier on those builds. However, even on
16168                    // debuggable builds downgrades of packages are permitted only if requested via
16169                    // installFlags. This is because we aim to keep the behavior of debuggable
16170                    // platform builds as close as possible to the behavior of non-debuggable
16171                    // platform builds.
16172                    final boolean downgradeRequested =
16173                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
16174                    final boolean packageDebuggable =
16175                                (dataOwnerPkg.applicationInfo.flags
16176                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
16177                    final boolean downgradePermitted =
16178                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
16179                    if (!downgradePermitted) {
16180                        try {
16181                            checkDowngrade(dataOwnerPkg, pkgLite);
16182                        } catch (PackageManagerException e) {
16183                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
16184                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
16185                        }
16186                    }
16187                }
16188
16189                if (installedPkg != null) {
16190                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16191                        // Check for updated system application.
16192                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16193                            if (onSd) {
16194                                Slog.w(TAG, "Cannot install update to system app on sdcard");
16195                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
16196                            }
16197                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16198                        } else {
16199                            if (onSd) {
16200                                // Install flag overrides everything.
16201                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16202                            }
16203                            // If current upgrade specifies particular preference
16204                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
16205                                // Application explicitly specified internal.
16206                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16207                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
16208                                // App explictly prefers external. Let policy decide
16209                            } else {
16210                                // Prefer previous location
16211                                if (isExternal(installedPkg)) {
16212                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16213                                }
16214                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16215                            }
16216                        }
16217                    } else {
16218                        // Invalid install. Return error code
16219                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
16220                    }
16221                }
16222            }
16223            // All the special cases have been taken care of.
16224            // Return result based on recommended install location.
16225            if (onSd) {
16226                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16227            }
16228            return pkgLite.recommendedInstallLocation;
16229        }
16230
16231        /*
16232         * Invoke remote method to get package information and install
16233         * location values. Override install location based on default
16234         * policy if needed and then create install arguments based
16235         * on the install location.
16236         */
16237        public void handleStartCopy() throws RemoteException {
16238            int ret = PackageManager.INSTALL_SUCCEEDED;
16239
16240            // If we're already staged, we've firmly committed to an install location
16241            if (origin.staged) {
16242                if (origin.file != null) {
16243                    installFlags |= PackageManager.INSTALL_INTERNAL;
16244                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
16245                } else if (origin.cid != null) {
16246                    installFlags |= PackageManager.INSTALL_EXTERNAL;
16247                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
16248                } else {
16249                    throw new IllegalStateException("Invalid stage location");
16250                }
16251            }
16252
16253            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16254            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
16255            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16256            PackageInfoLite pkgLite = null;
16257
16258            if (onInt && onSd) {
16259                // Check if both bits are set.
16260                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
16261                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16262            } else if (onSd && ephemeral) {
16263                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
16264                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16265            } else {
16266                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
16267                        packageAbiOverride);
16268
16269                if (DEBUG_EPHEMERAL && ephemeral) {
16270                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
16271                }
16272
16273                /*
16274                 * If we have too little free space, try to free cache
16275                 * before giving up.
16276                 */
16277                if (!origin.staged && pkgLite.recommendedInstallLocation
16278                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
16279                    // TODO: focus freeing disk space on the target device
16280                    final StorageManager storage = StorageManager.from(mContext);
16281                    final long lowThreshold = storage.getStorageLowBytes(
16282                            Environment.getDataDirectory());
16283
16284                    final long sizeBytes = mContainerService.calculateInstalledSize(
16285                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
16286
16287                    try {
16288                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
16289                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
16290                                installFlags, packageAbiOverride);
16291                    } catch (InstallerException e) {
16292                        Slog.w(TAG, "Failed to free cache", e);
16293                    }
16294
16295                    /*
16296                     * The cache free must have deleted the file we
16297                     * downloaded to install.
16298                     *
16299                     * TODO: fix the "freeCache" call to not delete
16300                     *       the file we care about.
16301                     */
16302                    if (pkgLite.recommendedInstallLocation
16303                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
16304                        pkgLite.recommendedInstallLocation
16305                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
16306                    }
16307                }
16308            }
16309
16310            if (ret == PackageManager.INSTALL_SUCCEEDED) {
16311                int loc = pkgLite.recommendedInstallLocation;
16312                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
16313                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16314                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
16315                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
16316                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
16317                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16318                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
16319                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
16320                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
16321                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
16322                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
16323                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
16324                } else {
16325                    // Override with defaults if needed.
16326                    loc = installLocationPolicy(pkgLite);
16327                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
16328                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
16329                    } else if (!onSd && !onInt) {
16330                        // Override install location with flags
16331                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
16332                            // Set the flag to install on external media.
16333                            installFlags |= PackageManager.INSTALL_EXTERNAL;
16334                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
16335                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
16336                            if (DEBUG_EPHEMERAL) {
16337                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
16338                            }
16339                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
16340                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
16341                                    |PackageManager.INSTALL_INTERNAL);
16342                        } else {
16343                            // Make sure the flag for installing on external
16344                            // media is unset
16345                            installFlags |= PackageManager.INSTALL_INTERNAL;
16346                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
16347                        }
16348                    }
16349                }
16350            }
16351
16352            final InstallArgs args = createInstallArgs(this);
16353            mArgs = args;
16354
16355            if (ret == PackageManager.INSTALL_SUCCEEDED) {
16356                // TODO: http://b/22976637
16357                // Apps installed for "all" users use the device owner to verify the app
16358                UserHandle verifierUser = getUser();
16359                if (verifierUser == UserHandle.ALL) {
16360                    verifierUser = UserHandle.SYSTEM;
16361                }
16362
16363                /*
16364                 * Determine if we have any installed package verifiers. If we
16365                 * do, then we'll defer to them to verify the packages.
16366                 */
16367                final int requiredUid = mRequiredVerifierPackage == null ? -1
16368                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
16369                                verifierUser.getIdentifier());
16370                final int installerUid =
16371                        verificationInfo == null ? -1 : verificationInfo.installerUid;
16372                if (!origin.existing && requiredUid != -1
16373                        && isVerificationEnabled(
16374                                verifierUser.getIdentifier(), installFlags, installerUid)) {
16375                    final Intent verification = new Intent(
16376                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
16377                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
16378                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
16379                            PACKAGE_MIME_TYPE);
16380                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
16381
16382                    // Query all live verifiers based on current user state
16383                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
16384                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
16385                            false /*allowDynamicSplits*/);
16386
16387                    if (DEBUG_VERIFY) {
16388                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
16389                                + verification.toString() + " with " + pkgLite.verifiers.length
16390                                + " optional verifiers");
16391                    }
16392
16393                    final int verificationId = mPendingVerificationToken++;
16394
16395                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
16396
16397                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
16398                            installerPackageName);
16399
16400                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
16401                            installFlags);
16402
16403                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
16404                            pkgLite.packageName);
16405
16406                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
16407                            pkgLite.versionCode);
16408
16409                    if (verificationInfo != null) {
16410                        if (verificationInfo.originatingUri != null) {
16411                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
16412                                    verificationInfo.originatingUri);
16413                        }
16414                        if (verificationInfo.referrer != null) {
16415                            verification.putExtra(Intent.EXTRA_REFERRER,
16416                                    verificationInfo.referrer);
16417                        }
16418                        if (verificationInfo.originatingUid >= 0) {
16419                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
16420                                    verificationInfo.originatingUid);
16421                        }
16422                        if (verificationInfo.installerUid >= 0) {
16423                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
16424                                    verificationInfo.installerUid);
16425                        }
16426                    }
16427
16428                    final PackageVerificationState verificationState = new PackageVerificationState(
16429                            requiredUid, args);
16430
16431                    mPendingVerification.append(verificationId, verificationState);
16432
16433                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
16434                            receivers, verificationState);
16435
16436                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
16437                    final long idleDuration = getVerificationTimeout();
16438
16439                    /*
16440                     * If any sufficient verifiers were listed in the package
16441                     * manifest, attempt to ask them.
16442                     */
16443                    if (sufficientVerifiers != null) {
16444                        final int N = sufficientVerifiers.size();
16445                        if (N == 0) {
16446                            Slog.i(TAG, "Additional verifiers required, but none installed.");
16447                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
16448                        } else {
16449                            for (int i = 0; i < N; i++) {
16450                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
16451                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16452                                        verifierComponent.getPackageName(), idleDuration,
16453                                        verifierUser.getIdentifier(), false, "package verifier");
16454
16455                                final Intent sufficientIntent = new Intent(verification);
16456                                sufficientIntent.setComponent(verifierComponent);
16457                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
16458                            }
16459                        }
16460                    }
16461
16462                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
16463                            mRequiredVerifierPackage, receivers);
16464                    if (ret == PackageManager.INSTALL_SUCCEEDED
16465                            && mRequiredVerifierPackage != null) {
16466                        Trace.asyncTraceBegin(
16467                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
16468                        /*
16469                         * Send the intent to the required verification agent,
16470                         * but only start the verification timeout after the
16471                         * target BroadcastReceivers have run.
16472                         */
16473                        verification.setComponent(requiredVerifierComponent);
16474                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16475                                mRequiredVerifierPackage, idleDuration,
16476                                verifierUser.getIdentifier(), false, "package verifier");
16477                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
16478                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16479                                new BroadcastReceiver() {
16480                                    @Override
16481                                    public void onReceive(Context context, Intent intent) {
16482                                        final Message msg = mHandler
16483                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
16484                                        msg.arg1 = verificationId;
16485                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
16486                                    }
16487                                }, null, 0, null, null);
16488
16489                        /*
16490                         * We don't want the copy to proceed until verification
16491                         * succeeds, so null out this field.
16492                         */
16493                        mArgs = null;
16494                    }
16495                } else {
16496                    /*
16497                     * No package verification is enabled, so immediately start
16498                     * the remote call to initiate copy using temporary file.
16499                     */
16500                    ret = args.copyApk(mContainerService, true);
16501                }
16502            }
16503
16504            mRet = ret;
16505        }
16506
16507        @Override
16508        void handleReturnCode() {
16509            // If mArgs is null, then MCS couldn't be reached. When it
16510            // reconnects, it will try again to install. At that point, this
16511            // will succeed.
16512            if (mArgs != null) {
16513                processPendingInstall(mArgs, mRet);
16514            }
16515        }
16516
16517        @Override
16518        void handleServiceError() {
16519            mArgs = createInstallArgs(this);
16520            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16521        }
16522
16523        public boolean isForwardLocked() {
16524            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16525        }
16526    }
16527
16528    /**
16529     * Used during creation of InstallArgs
16530     *
16531     * @param installFlags package installation flags
16532     * @return true if should be installed on external storage
16533     */
16534    private static boolean installOnExternalAsec(int installFlags) {
16535        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
16536            return false;
16537        }
16538        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
16539            return true;
16540        }
16541        return false;
16542    }
16543
16544    /**
16545     * Used during creation of InstallArgs
16546     *
16547     * @param installFlags package installation flags
16548     * @return true if should be installed as forward locked
16549     */
16550    private static boolean installForwardLocked(int installFlags) {
16551        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16552    }
16553
16554    private InstallArgs createInstallArgs(InstallParams params) {
16555        if (params.move != null) {
16556            return new MoveInstallArgs(params);
16557        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
16558            return new AsecInstallArgs(params);
16559        } else {
16560            return new FileInstallArgs(params);
16561        }
16562    }
16563
16564    /**
16565     * Create args that describe an existing installed package. Typically used
16566     * when cleaning up old installs, or used as a move source.
16567     */
16568    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
16569            String resourcePath, String[] instructionSets) {
16570        final boolean isInAsec;
16571        if (installOnExternalAsec(installFlags)) {
16572            /* Apps on SD card are always in ASEC containers. */
16573            isInAsec = true;
16574        } else if (installForwardLocked(installFlags)
16575                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
16576            /*
16577             * Forward-locked apps are only in ASEC containers if they're the
16578             * new style
16579             */
16580            isInAsec = true;
16581        } else {
16582            isInAsec = false;
16583        }
16584
16585        if (isInAsec) {
16586            return new AsecInstallArgs(codePath, instructionSets,
16587                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
16588        } else {
16589            return new FileInstallArgs(codePath, resourcePath, instructionSets);
16590        }
16591    }
16592
16593    static abstract class InstallArgs {
16594        /** @see InstallParams#origin */
16595        final OriginInfo origin;
16596        /** @see InstallParams#move */
16597        final MoveInfo move;
16598
16599        final IPackageInstallObserver2 observer;
16600        // Always refers to PackageManager flags only
16601        final int installFlags;
16602        final String installerPackageName;
16603        final String volumeUuid;
16604        final UserHandle user;
16605        final String abiOverride;
16606        final String[] installGrantPermissions;
16607        /** If non-null, drop an async trace when the install completes */
16608        final String traceMethod;
16609        final int traceCookie;
16610        final Certificate[][] certificates;
16611        final int installReason;
16612
16613        // The list of instruction sets supported by this app. This is currently
16614        // only used during the rmdex() phase to clean up resources. We can get rid of this
16615        // if we move dex files under the common app path.
16616        /* nullable */ String[] instructionSets;
16617
16618        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16619                int installFlags, String installerPackageName, String volumeUuid,
16620                UserHandle user, String[] instructionSets,
16621                String abiOverride, String[] installGrantPermissions,
16622                String traceMethod, int traceCookie, Certificate[][] certificates,
16623                int installReason) {
16624            this.origin = origin;
16625            this.move = move;
16626            this.installFlags = installFlags;
16627            this.observer = observer;
16628            this.installerPackageName = installerPackageName;
16629            this.volumeUuid = volumeUuid;
16630            this.user = user;
16631            this.instructionSets = instructionSets;
16632            this.abiOverride = abiOverride;
16633            this.installGrantPermissions = installGrantPermissions;
16634            this.traceMethod = traceMethod;
16635            this.traceCookie = traceCookie;
16636            this.certificates = certificates;
16637            this.installReason = installReason;
16638        }
16639
16640        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16641        abstract int doPreInstall(int status);
16642
16643        /**
16644         * Rename package into final resting place. All paths on the given
16645         * scanned package should be updated to reflect the rename.
16646         */
16647        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16648        abstract int doPostInstall(int status, int uid);
16649
16650        /** @see PackageSettingBase#codePathString */
16651        abstract String getCodePath();
16652        /** @see PackageSettingBase#resourcePathString */
16653        abstract String getResourcePath();
16654
16655        // Need installer lock especially for dex file removal.
16656        abstract void cleanUpResourcesLI();
16657        abstract boolean doPostDeleteLI(boolean delete);
16658
16659        /**
16660         * Called before the source arguments are copied. This is used mostly
16661         * for MoveParams when it needs to read the source file to put it in the
16662         * destination.
16663         */
16664        int doPreCopy() {
16665            return PackageManager.INSTALL_SUCCEEDED;
16666        }
16667
16668        /**
16669         * Called after the source arguments are copied. This is used mostly for
16670         * MoveParams when it needs to read the source file to put it in the
16671         * destination.
16672         */
16673        int doPostCopy(int uid) {
16674            return PackageManager.INSTALL_SUCCEEDED;
16675        }
16676
16677        protected boolean isFwdLocked() {
16678            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16679        }
16680
16681        protected boolean isExternalAsec() {
16682            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16683        }
16684
16685        protected boolean isEphemeral() {
16686            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16687        }
16688
16689        UserHandle getUser() {
16690            return user;
16691        }
16692    }
16693
16694    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16695        if (!allCodePaths.isEmpty()) {
16696            if (instructionSets == null) {
16697                throw new IllegalStateException("instructionSet == null");
16698            }
16699            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16700            for (String codePath : allCodePaths) {
16701                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16702                    try {
16703                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
16704                    } catch (InstallerException ignored) {
16705                    }
16706                }
16707            }
16708        }
16709    }
16710
16711    /**
16712     * Logic to handle installation of non-ASEC applications, including copying
16713     * and renaming logic.
16714     */
16715    class FileInstallArgs extends InstallArgs {
16716        private File codeFile;
16717        private File resourceFile;
16718
16719        // Example topology:
16720        // /data/app/com.example/base.apk
16721        // /data/app/com.example/split_foo.apk
16722        // /data/app/com.example/lib/arm/libfoo.so
16723        // /data/app/com.example/lib/arm64/libfoo.so
16724        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16725
16726        /** New install */
16727        FileInstallArgs(InstallParams params) {
16728            super(params.origin, params.move, params.observer, params.installFlags,
16729                    params.installerPackageName, params.volumeUuid,
16730                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16731                    params.grantedRuntimePermissions,
16732                    params.traceMethod, params.traceCookie, params.certificates,
16733                    params.installReason);
16734            if (isFwdLocked()) {
16735                throw new IllegalArgumentException("Forward locking only supported in ASEC");
16736            }
16737        }
16738
16739        /** Existing install */
16740        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16741            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16742                    null, null, null, 0, null /*certificates*/,
16743                    PackageManager.INSTALL_REASON_UNKNOWN);
16744            this.codeFile = (codePath != null) ? new File(codePath) : null;
16745            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16746        }
16747
16748        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16749            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16750            try {
16751                return doCopyApk(imcs, temp);
16752            } finally {
16753                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16754            }
16755        }
16756
16757        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16758            if (origin.staged) {
16759                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16760                codeFile = origin.file;
16761                resourceFile = origin.file;
16762                return PackageManager.INSTALL_SUCCEEDED;
16763            }
16764
16765            try {
16766                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16767                final File tempDir =
16768                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16769                codeFile = tempDir;
16770                resourceFile = tempDir;
16771            } catch (IOException e) {
16772                Slog.w(TAG, "Failed to create copy file: " + e);
16773                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16774            }
16775
16776            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16777                @Override
16778                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16779                    if (!FileUtils.isValidExtFilename(name)) {
16780                        throw new IllegalArgumentException("Invalid filename: " + name);
16781                    }
16782                    try {
16783                        final File file = new File(codeFile, name);
16784                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16785                                O_RDWR | O_CREAT, 0644);
16786                        Os.chmod(file.getAbsolutePath(), 0644);
16787                        return new ParcelFileDescriptor(fd);
16788                    } catch (ErrnoException e) {
16789                        throw new RemoteException("Failed to open: " + e.getMessage());
16790                    }
16791                }
16792            };
16793
16794            int ret = PackageManager.INSTALL_SUCCEEDED;
16795            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16796            if (ret != PackageManager.INSTALL_SUCCEEDED) {
16797                Slog.e(TAG, "Failed to copy package");
16798                return ret;
16799            }
16800
16801            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16802            NativeLibraryHelper.Handle handle = null;
16803            try {
16804                handle = NativeLibraryHelper.Handle.create(codeFile);
16805                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16806                        abiOverride);
16807            } catch (IOException e) {
16808                Slog.e(TAG, "Copying native libraries failed", e);
16809                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16810            } finally {
16811                IoUtils.closeQuietly(handle);
16812            }
16813
16814            return ret;
16815        }
16816
16817        int doPreInstall(int status) {
16818            if (status != PackageManager.INSTALL_SUCCEEDED) {
16819                cleanUp();
16820            }
16821            return status;
16822        }
16823
16824        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16825            if (status != PackageManager.INSTALL_SUCCEEDED) {
16826                cleanUp();
16827                return false;
16828            }
16829
16830            final File targetDir = codeFile.getParentFile();
16831            final File beforeCodeFile = codeFile;
16832            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16833
16834            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16835            try {
16836                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16837            } catch (ErrnoException e) {
16838                Slog.w(TAG, "Failed to rename", e);
16839                return false;
16840            }
16841
16842            if (!SELinux.restoreconRecursive(afterCodeFile)) {
16843                Slog.w(TAG, "Failed to restorecon");
16844                return false;
16845            }
16846
16847            // Reflect the rename internally
16848            codeFile = afterCodeFile;
16849            resourceFile = afterCodeFile;
16850
16851            // Reflect the rename in scanned details
16852            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16853            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16854                    afterCodeFile, pkg.baseCodePath));
16855            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16856                    afterCodeFile, pkg.splitCodePaths));
16857
16858            // Reflect the rename in app info
16859            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16860            pkg.setApplicationInfoCodePath(pkg.codePath);
16861            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16862            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16863            pkg.setApplicationInfoResourcePath(pkg.codePath);
16864            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16865            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16866
16867            return true;
16868        }
16869
16870        int doPostInstall(int status, int uid) {
16871            if (status != PackageManager.INSTALL_SUCCEEDED) {
16872                cleanUp();
16873            }
16874            return status;
16875        }
16876
16877        @Override
16878        String getCodePath() {
16879            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16880        }
16881
16882        @Override
16883        String getResourcePath() {
16884            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16885        }
16886
16887        private boolean cleanUp() {
16888            if (codeFile == null || !codeFile.exists()) {
16889                return false;
16890            }
16891
16892            removeCodePathLI(codeFile);
16893
16894            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16895                resourceFile.delete();
16896            }
16897
16898            return true;
16899        }
16900
16901        void cleanUpResourcesLI() {
16902            // Try enumerating all code paths before deleting
16903            List<String> allCodePaths = Collections.EMPTY_LIST;
16904            if (codeFile != null && codeFile.exists()) {
16905                try {
16906                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16907                    allCodePaths = pkg.getAllCodePaths();
16908                } catch (PackageParserException e) {
16909                    // Ignored; we tried our best
16910                }
16911            }
16912
16913            cleanUp();
16914            removeDexFiles(allCodePaths, instructionSets);
16915        }
16916
16917        boolean doPostDeleteLI(boolean delete) {
16918            // XXX err, shouldn't we respect the delete flag?
16919            cleanUpResourcesLI();
16920            return true;
16921        }
16922    }
16923
16924    private boolean isAsecExternal(String cid) {
16925        final String asecPath = PackageHelper.getSdFilesystem(cid);
16926        return !asecPath.startsWith(mAsecInternalPath);
16927    }
16928
16929    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16930            PackageManagerException {
16931        if (copyRet < 0) {
16932            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16933                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16934                throw new PackageManagerException(copyRet, message);
16935            }
16936        }
16937    }
16938
16939    /**
16940     * Extract the StorageManagerService "container ID" from the full code path of an
16941     * .apk.
16942     */
16943    static String cidFromCodePath(String fullCodePath) {
16944        int eidx = fullCodePath.lastIndexOf("/");
16945        String subStr1 = fullCodePath.substring(0, eidx);
16946        int sidx = subStr1.lastIndexOf("/");
16947        return subStr1.substring(sidx+1, eidx);
16948    }
16949
16950    /**
16951     * Logic to handle installation of ASEC applications, including copying and
16952     * renaming logic.
16953     */
16954    class AsecInstallArgs extends InstallArgs {
16955        static final String RES_FILE_NAME = "pkg.apk";
16956        static final String PUBLIC_RES_FILE_NAME = "res.zip";
16957
16958        String cid;
16959        String packagePath;
16960        String resourcePath;
16961
16962        /** New install */
16963        AsecInstallArgs(InstallParams params) {
16964            super(params.origin, params.move, params.observer, params.installFlags,
16965                    params.installerPackageName, params.volumeUuid,
16966                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16967                    params.grantedRuntimePermissions,
16968                    params.traceMethod, params.traceCookie, params.certificates,
16969                    params.installReason);
16970        }
16971
16972        /** Existing install */
16973        AsecInstallArgs(String fullCodePath, String[] instructionSets,
16974                        boolean isExternal, boolean isForwardLocked) {
16975            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
16976                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16977                    instructionSets, null, null, null, 0, null /*certificates*/,
16978                    PackageManager.INSTALL_REASON_UNKNOWN);
16979            // Hackily pretend we're still looking at a full code path
16980            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
16981                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
16982            }
16983
16984            // Extract cid from fullCodePath
16985            int eidx = fullCodePath.lastIndexOf("/");
16986            String subStr1 = fullCodePath.substring(0, eidx);
16987            int sidx = subStr1.lastIndexOf("/");
16988            cid = subStr1.substring(sidx+1, eidx);
16989            setMountPath(subStr1);
16990        }
16991
16992        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
16993            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
16994                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16995                    instructionSets, null, null, null, 0, null /*certificates*/,
16996                    PackageManager.INSTALL_REASON_UNKNOWN);
16997            this.cid = cid;
16998            setMountPath(PackageHelper.getSdDir(cid));
16999        }
17000
17001        void createCopyFile() {
17002            cid = mInstallerService.allocateExternalStageCidLegacy();
17003        }
17004
17005        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
17006            if (origin.staged && origin.cid != null) {
17007                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
17008                cid = origin.cid;
17009                setMountPath(PackageHelper.getSdDir(cid));
17010                return PackageManager.INSTALL_SUCCEEDED;
17011            }
17012
17013            if (temp) {
17014                createCopyFile();
17015            } else {
17016                /*
17017                 * Pre-emptively destroy the container since it's destroyed if
17018                 * copying fails due to it existing anyway.
17019                 */
17020                PackageHelper.destroySdDir(cid);
17021            }
17022
17023            final String newMountPath = imcs.copyPackageToContainer(
17024                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
17025                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
17026
17027            if (newMountPath != null) {
17028                setMountPath(newMountPath);
17029                return PackageManager.INSTALL_SUCCEEDED;
17030            } else {
17031                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17032            }
17033        }
17034
17035        @Override
17036        String getCodePath() {
17037            return packagePath;
17038        }
17039
17040        @Override
17041        String getResourcePath() {
17042            return resourcePath;
17043        }
17044
17045        int doPreInstall(int status) {
17046            if (status != PackageManager.INSTALL_SUCCEEDED) {
17047                // Destroy container
17048                PackageHelper.destroySdDir(cid);
17049            } else {
17050                boolean mounted = PackageHelper.isContainerMounted(cid);
17051                if (!mounted) {
17052                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
17053                            Process.SYSTEM_UID);
17054                    if (newMountPath != null) {
17055                        setMountPath(newMountPath);
17056                    } else {
17057                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17058                    }
17059                }
17060            }
17061            return status;
17062        }
17063
17064        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
17065            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
17066            String newMountPath = null;
17067            if (PackageHelper.isContainerMounted(cid)) {
17068                // Unmount the container
17069                if (!PackageHelper.unMountSdDir(cid)) {
17070                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
17071                    return false;
17072                }
17073            }
17074            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
17075                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
17076                        " which might be stale. Will try to clean up.");
17077                // Clean up the stale container and proceed to recreate.
17078                if (!PackageHelper.destroySdDir(newCacheId)) {
17079                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
17080                    return false;
17081                }
17082                // Successfully cleaned up stale container. Try to rename again.
17083                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
17084                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
17085                            + " inspite of cleaning it up.");
17086                    return false;
17087                }
17088            }
17089            if (!PackageHelper.isContainerMounted(newCacheId)) {
17090                Slog.w(TAG, "Mounting container " + newCacheId);
17091                newMountPath = PackageHelper.mountSdDir(newCacheId,
17092                        getEncryptKey(), Process.SYSTEM_UID);
17093            } else {
17094                newMountPath = PackageHelper.getSdDir(newCacheId);
17095            }
17096            if (newMountPath == null) {
17097                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
17098                return false;
17099            }
17100            Log.i(TAG, "Succesfully renamed " + cid +
17101                    " to " + newCacheId +
17102                    " at new path: " + newMountPath);
17103            cid = newCacheId;
17104
17105            final File beforeCodeFile = new File(packagePath);
17106            setMountPath(newMountPath);
17107            final File afterCodeFile = new File(packagePath);
17108
17109            // Reflect the rename in scanned details
17110            pkg.setCodePath(afterCodeFile.getAbsolutePath());
17111            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
17112                    afterCodeFile, pkg.baseCodePath));
17113            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
17114                    afterCodeFile, pkg.splitCodePaths));
17115
17116            // Reflect the rename in app info
17117            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
17118            pkg.setApplicationInfoCodePath(pkg.codePath);
17119            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
17120            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
17121            pkg.setApplicationInfoResourcePath(pkg.codePath);
17122            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
17123            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
17124
17125            return true;
17126        }
17127
17128        private void setMountPath(String mountPath) {
17129            final File mountFile = new File(mountPath);
17130
17131            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
17132            if (monolithicFile.exists()) {
17133                packagePath = monolithicFile.getAbsolutePath();
17134                if (isFwdLocked()) {
17135                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
17136                } else {
17137                    resourcePath = packagePath;
17138                }
17139            } else {
17140                packagePath = mountFile.getAbsolutePath();
17141                resourcePath = packagePath;
17142            }
17143        }
17144
17145        int doPostInstall(int status, int uid) {
17146            if (status != PackageManager.INSTALL_SUCCEEDED) {
17147                cleanUp();
17148            } else {
17149                final int groupOwner;
17150                final String protectedFile;
17151                if (isFwdLocked()) {
17152                    groupOwner = UserHandle.getSharedAppGid(uid);
17153                    protectedFile = RES_FILE_NAME;
17154                } else {
17155                    groupOwner = -1;
17156                    protectedFile = null;
17157                }
17158
17159                if (uid < Process.FIRST_APPLICATION_UID
17160                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
17161                    Slog.e(TAG, "Failed to finalize " + cid);
17162                    PackageHelper.destroySdDir(cid);
17163                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17164                }
17165
17166                boolean mounted = PackageHelper.isContainerMounted(cid);
17167                if (!mounted) {
17168                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
17169                }
17170            }
17171            return status;
17172        }
17173
17174        private void cleanUp() {
17175            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
17176
17177            // Destroy secure container
17178            PackageHelper.destroySdDir(cid);
17179        }
17180
17181        private List<String> getAllCodePaths() {
17182            final File codeFile = new File(getCodePath());
17183            if (codeFile != null && codeFile.exists()) {
17184                try {
17185                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
17186                    return pkg.getAllCodePaths();
17187                } catch (PackageParserException e) {
17188                    // Ignored; we tried our best
17189                }
17190            }
17191            return Collections.EMPTY_LIST;
17192        }
17193
17194        void cleanUpResourcesLI() {
17195            // Enumerate all code paths before deleting
17196            cleanUpResourcesLI(getAllCodePaths());
17197        }
17198
17199        private void cleanUpResourcesLI(List<String> allCodePaths) {
17200            cleanUp();
17201            removeDexFiles(allCodePaths, instructionSets);
17202        }
17203
17204        String getPackageName() {
17205            return getAsecPackageName(cid);
17206        }
17207
17208        boolean doPostDeleteLI(boolean delete) {
17209            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
17210            final List<String> allCodePaths = getAllCodePaths();
17211            boolean mounted = PackageHelper.isContainerMounted(cid);
17212            if (mounted) {
17213                // Unmount first
17214                if (PackageHelper.unMountSdDir(cid)) {
17215                    mounted = false;
17216                }
17217            }
17218            if (!mounted && delete) {
17219                cleanUpResourcesLI(allCodePaths);
17220            }
17221            return !mounted;
17222        }
17223
17224        @Override
17225        int doPreCopy() {
17226            if (isFwdLocked()) {
17227                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
17228                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
17229                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17230                }
17231            }
17232
17233            return PackageManager.INSTALL_SUCCEEDED;
17234        }
17235
17236        @Override
17237        int doPostCopy(int uid) {
17238            if (isFwdLocked()) {
17239                if (uid < Process.FIRST_APPLICATION_UID
17240                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
17241                                RES_FILE_NAME)) {
17242                    Slog.e(TAG, "Failed to finalize " + cid);
17243                    PackageHelper.destroySdDir(cid);
17244                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17245                }
17246            }
17247
17248            return PackageManager.INSTALL_SUCCEEDED;
17249        }
17250    }
17251
17252    /**
17253     * Logic to handle movement of existing installed applications.
17254     */
17255    class MoveInstallArgs extends InstallArgs {
17256        private File codeFile;
17257        private File resourceFile;
17258
17259        /** New install */
17260        MoveInstallArgs(InstallParams params) {
17261            super(params.origin, params.move, params.observer, params.installFlags,
17262                    params.installerPackageName, params.volumeUuid,
17263                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
17264                    params.grantedRuntimePermissions,
17265                    params.traceMethod, params.traceCookie, params.certificates,
17266                    params.installReason);
17267        }
17268
17269        int copyApk(IMediaContainerService imcs, boolean temp) {
17270            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
17271                    + move.fromUuid + " to " + move.toUuid);
17272            synchronized (mInstaller) {
17273                try {
17274                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
17275                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
17276                } catch (InstallerException e) {
17277                    Slog.w(TAG, "Failed to move app", e);
17278                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
17279                }
17280            }
17281
17282            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
17283            resourceFile = codeFile;
17284            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
17285
17286            return PackageManager.INSTALL_SUCCEEDED;
17287        }
17288
17289        int doPreInstall(int status) {
17290            if (status != PackageManager.INSTALL_SUCCEEDED) {
17291                cleanUp(move.toUuid);
17292            }
17293            return status;
17294        }
17295
17296        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
17297            if (status != PackageManager.INSTALL_SUCCEEDED) {
17298                cleanUp(move.toUuid);
17299                return false;
17300            }
17301
17302            // Reflect the move in app info
17303            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
17304            pkg.setApplicationInfoCodePath(pkg.codePath);
17305            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
17306            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
17307            pkg.setApplicationInfoResourcePath(pkg.codePath);
17308            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
17309            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
17310
17311            return true;
17312        }
17313
17314        int doPostInstall(int status, int uid) {
17315            if (status == PackageManager.INSTALL_SUCCEEDED) {
17316                cleanUp(move.fromUuid);
17317            } else {
17318                cleanUp(move.toUuid);
17319            }
17320            return status;
17321        }
17322
17323        @Override
17324        String getCodePath() {
17325            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
17326        }
17327
17328        @Override
17329        String getResourcePath() {
17330            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
17331        }
17332
17333        private boolean cleanUp(String volumeUuid) {
17334            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
17335                    move.dataAppName);
17336            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
17337            final int[] userIds = sUserManager.getUserIds();
17338            synchronized (mInstallLock) {
17339                // Clean up both app data and code
17340                // All package moves are frozen until finished
17341                for (int userId : userIds) {
17342                    try {
17343                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
17344                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
17345                    } catch (InstallerException e) {
17346                        Slog.w(TAG, String.valueOf(e));
17347                    }
17348                }
17349                removeCodePathLI(codeFile);
17350            }
17351            return true;
17352        }
17353
17354        void cleanUpResourcesLI() {
17355            throw new UnsupportedOperationException();
17356        }
17357
17358        boolean doPostDeleteLI(boolean delete) {
17359            throw new UnsupportedOperationException();
17360        }
17361    }
17362
17363    static String getAsecPackageName(String packageCid) {
17364        int idx = packageCid.lastIndexOf("-");
17365        if (idx == -1) {
17366            return packageCid;
17367        }
17368        return packageCid.substring(0, idx);
17369    }
17370
17371    // Utility method used to create code paths based on package name and available index.
17372    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
17373        String idxStr = "";
17374        int idx = 1;
17375        // Fall back to default value of idx=1 if prefix is not
17376        // part of oldCodePath
17377        if (oldCodePath != null) {
17378            String subStr = oldCodePath;
17379            // Drop the suffix right away
17380            if (suffix != null && subStr.endsWith(suffix)) {
17381                subStr = subStr.substring(0, subStr.length() - suffix.length());
17382            }
17383            // If oldCodePath already contains prefix find out the
17384            // ending index to either increment or decrement.
17385            int sidx = subStr.lastIndexOf(prefix);
17386            if (sidx != -1) {
17387                subStr = subStr.substring(sidx + prefix.length());
17388                if (subStr != null) {
17389                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
17390                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
17391                    }
17392                    try {
17393                        idx = Integer.parseInt(subStr);
17394                        if (idx <= 1) {
17395                            idx++;
17396                        } else {
17397                            idx--;
17398                        }
17399                    } catch(NumberFormatException e) {
17400                    }
17401                }
17402            }
17403        }
17404        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
17405        return prefix + idxStr;
17406    }
17407
17408    private File getNextCodePath(File targetDir, String packageName) {
17409        File result;
17410        SecureRandom random = new SecureRandom();
17411        byte[] bytes = new byte[16];
17412        do {
17413            random.nextBytes(bytes);
17414            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
17415            result = new File(targetDir, packageName + "-" + suffix);
17416        } while (result.exists());
17417        return result;
17418    }
17419
17420    // Utility method that returns the relative package path with respect
17421    // to the installation directory. Like say for /data/data/com.test-1.apk
17422    // string com.test-1 is returned.
17423    static String deriveCodePathName(String codePath) {
17424        if (codePath == null) {
17425            return null;
17426        }
17427        final File codeFile = new File(codePath);
17428        final String name = codeFile.getName();
17429        if (codeFile.isDirectory()) {
17430            return name;
17431        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
17432            final int lastDot = name.lastIndexOf('.');
17433            return name.substring(0, lastDot);
17434        } else {
17435            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
17436            return null;
17437        }
17438    }
17439
17440    static class PackageInstalledInfo {
17441        String name;
17442        int uid;
17443        // The set of users that originally had this package installed.
17444        int[] origUsers;
17445        // The set of users that now have this package installed.
17446        int[] newUsers;
17447        PackageParser.Package pkg;
17448        int returnCode;
17449        String returnMsg;
17450        String installerPackageName;
17451        PackageRemovedInfo removedInfo;
17452        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
17453
17454        public void setError(int code, String msg) {
17455            setReturnCode(code);
17456            setReturnMessage(msg);
17457            Slog.w(TAG, msg);
17458        }
17459
17460        public void setError(String msg, PackageParserException e) {
17461            setReturnCode(e.error);
17462            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17463            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17464            for (int i = 0; i < childCount; i++) {
17465                addedChildPackages.valueAt(i).setError(msg, e);
17466            }
17467            Slog.w(TAG, msg, e);
17468        }
17469
17470        public void setError(String msg, PackageManagerException e) {
17471            returnCode = e.error;
17472            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17473            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17474            for (int i = 0; i < childCount; i++) {
17475                addedChildPackages.valueAt(i).setError(msg, e);
17476            }
17477            Slog.w(TAG, msg, e);
17478        }
17479
17480        public void setReturnCode(int returnCode) {
17481            this.returnCode = returnCode;
17482            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17483            for (int i = 0; i < childCount; i++) {
17484                addedChildPackages.valueAt(i).returnCode = returnCode;
17485            }
17486        }
17487
17488        private void setReturnMessage(String returnMsg) {
17489            this.returnMsg = returnMsg;
17490            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17491            for (int i = 0; i < childCount; i++) {
17492                addedChildPackages.valueAt(i).returnMsg = returnMsg;
17493            }
17494        }
17495
17496        // In some error cases we want to convey more info back to the observer
17497        String origPackage;
17498        String origPermission;
17499    }
17500
17501    /*
17502     * Install a non-existing package.
17503     */
17504    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
17505            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
17506            PackageInstalledInfo res, int installReason) {
17507        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
17508
17509        // Remember this for later, in case we need to rollback this install
17510        String pkgName = pkg.packageName;
17511
17512        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
17513
17514        synchronized(mPackages) {
17515            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
17516            if (renamedPackage != null) {
17517                // A package with the same name is already installed, though
17518                // it has been renamed to an older name.  The package we
17519                // are trying to install should be installed as an update to
17520                // the existing one, but that has not been requested, so bail.
17521                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17522                        + " without first uninstalling package running as "
17523                        + renamedPackage);
17524                return;
17525            }
17526            if (mPackages.containsKey(pkgName)) {
17527                // Don't allow installation over an existing package with the same name.
17528                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17529                        + " without first uninstalling.");
17530                return;
17531            }
17532        }
17533
17534        try {
17535            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
17536                    System.currentTimeMillis(), user);
17537
17538            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
17539
17540            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17541                prepareAppDataAfterInstallLIF(newPackage);
17542
17543            } else {
17544                // Remove package from internal structures, but keep around any
17545                // data that might have already existed
17546                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
17547                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
17548            }
17549        } catch (PackageManagerException e) {
17550            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17551        }
17552
17553        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17554    }
17555
17556    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
17557        // Can't rotate keys during boot or if sharedUser.
17558        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
17559                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
17560            return false;
17561        }
17562        // app is using upgradeKeySets; make sure all are valid
17563        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17564        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
17565        for (int i = 0; i < upgradeKeySets.length; i++) {
17566            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
17567                Slog.wtf(TAG, "Package "
17568                         + (oldPs.name != null ? oldPs.name : "<null>")
17569                         + " contains upgrade-key-set reference to unknown key-set: "
17570                         + upgradeKeySets[i]
17571                         + " reverting to signatures check.");
17572                return false;
17573            }
17574        }
17575        return true;
17576    }
17577
17578    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
17579        // Upgrade keysets are being used.  Determine if new package has a superset of the
17580        // required keys.
17581        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
17582        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17583        for (int i = 0; i < upgradeKeySets.length; i++) {
17584            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
17585            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
17586                return true;
17587            }
17588        }
17589        return false;
17590    }
17591
17592    private static void updateDigest(MessageDigest digest, File file) throws IOException {
17593        try (DigestInputStream digestStream =
17594                new DigestInputStream(new FileInputStream(file), digest)) {
17595            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
17596        }
17597    }
17598
17599    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
17600            UserHandle user, String installerPackageName, PackageInstalledInfo res,
17601            int installReason) {
17602        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17603
17604        final PackageParser.Package oldPackage;
17605        final PackageSetting ps;
17606        final String pkgName = pkg.packageName;
17607        final int[] allUsers;
17608        final int[] installedUsers;
17609
17610        synchronized(mPackages) {
17611            oldPackage = mPackages.get(pkgName);
17612            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
17613
17614            // don't allow upgrade to target a release SDK from a pre-release SDK
17615            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
17616                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17617            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
17618                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17619            if (oldTargetsPreRelease
17620                    && !newTargetsPreRelease
17621                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
17622                Slog.w(TAG, "Can't install package targeting released sdk");
17623                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
17624                return;
17625            }
17626
17627            ps = mSettings.mPackages.get(pkgName);
17628
17629            // verify signatures are valid
17630            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17631                if (!checkUpgradeKeySetLP(ps, pkg)) {
17632                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17633                            "New package not signed by keys specified by upgrade-keysets: "
17634                                    + pkgName);
17635                    return;
17636                }
17637            } else {
17638                // default to original signature matching
17639                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17640                        != PackageManager.SIGNATURE_MATCH) {
17641                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17642                            "New package has a different signature: " + pkgName);
17643                    return;
17644                }
17645            }
17646
17647            // don't allow a system upgrade unless the upgrade hash matches
17648            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17649                byte[] digestBytes = null;
17650                try {
17651                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17652                    updateDigest(digest, new File(pkg.baseCodePath));
17653                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17654                        for (String path : pkg.splitCodePaths) {
17655                            updateDigest(digest, new File(path));
17656                        }
17657                    }
17658                    digestBytes = digest.digest();
17659                } catch (NoSuchAlgorithmException | IOException e) {
17660                    res.setError(INSTALL_FAILED_INVALID_APK,
17661                            "Could not compute hash: " + pkgName);
17662                    return;
17663                }
17664                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17665                    res.setError(INSTALL_FAILED_INVALID_APK,
17666                            "New package fails restrict-update check: " + pkgName);
17667                    return;
17668                }
17669                // retain upgrade restriction
17670                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17671            }
17672
17673            // Check for shared user id changes
17674            String invalidPackageName =
17675                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17676            if (invalidPackageName != null) {
17677                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17678                        "Package " + invalidPackageName + " tried to change user "
17679                                + oldPackage.mSharedUserId);
17680                return;
17681            }
17682
17683            // In case of rollback, remember per-user/profile install state
17684            allUsers = sUserManager.getUserIds();
17685            installedUsers = ps.queryInstalledUsers(allUsers, true);
17686
17687            // don't allow an upgrade from full to ephemeral
17688            if (isInstantApp) {
17689                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17690                    for (int currentUser : allUsers) {
17691                        if (!ps.getInstantApp(currentUser)) {
17692                            // can't downgrade from full to instant
17693                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17694                                    + " for user: " + currentUser);
17695                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17696                            return;
17697                        }
17698                    }
17699                } else if (!ps.getInstantApp(user.getIdentifier())) {
17700                    // can't downgrade from full to instant
17701                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17702                            + " for user: " + user.getIdentifier());
17703                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17704                    return;
17705                }
17706            }
17707        }
17708
17709        // Update what is removed
17710        res.removedInfo = new PackageRemovedInfo(this);
17711        res.removedInfo.uid = oldPackage.applicationInfo.uid;
17712        res.removedInfo.removedPackage = oldPackage.packageName;
17713        res.removedInfo.installerPackageName = ps.installerPackageName;
17714        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17715        res.removedInfo.isUpdate = true;
17716        res.removedInfo.origUsers = installedUsers;
17717        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17718        for (int i = 0; i < installedUsers.length; i++) {
17719            final int userId = installedUsers[i];
17720            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17721        }
17722
17723        final int childCount = (oldPackage.childPackages != null)
17724                ? oldPackage.childPackages.size() : 0;
17725        for (int i = 0; i < childCount; i++) {
17726            boolean childPackageUpdated = false;
17727            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17728            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17729            if (res.addedChildPackages != null) {
17730                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17731                if (childRes != null) {
17732                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17733                    childRes.removedInfo.removedPackage = childPkg.packageName;
17734                    if (childPs != null) {
17735                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17736                    }
17737                    childRes.removedInfo.isUpdate = true;
17738                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17739                    childPackageUpdated = true;
17740                }
17741            }
17742            if (!childPackageUpdated) {
17743                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17744                childRemovedRes.removedPackage = childPkg.packageName;
17745                if (childPs != null) {
17746                    childRemovedRes.installerPackageName = childPs.installerPackageName;
17747                }
17748                childRemovedRes.isUpdate = false;
17749                childRemovedRes.dataRemoved = true;
17750                synchronized (mPackages) {
17751                    if (childPs != null) {
17752                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17753                    }
17754                }
17755                if (res.removedInfo.removedChildPackages == null) {
17756                    res.removedInfo.removedChildPackages = new ArrayMap<>();
17757                }
17758                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17759            }
17760        }
17761
17762        boolean sysPkg = (isSystemApp(oldPackage));
17763        if (sysPkg) {
17764            // Set the system/privileged flags as needed
17765            final boolean privileged =
17766                    (oldPackage.applicationInfo.privateFlags
17767                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17768            final int systemPolicyFlags = policyFlags
17769                    | PackageParser.PARSE_IS_SYSTEM
17770                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
17771
17772            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17773                    user, allUsers, installerPackageName, res, installReason);
17774        } else {
17775            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17776                    user, allUsers, installerPackageName, res, installReason);
17777        }
17778    }
17779
17780    @Override
17781    public List<String> getPreviousCodePaths(String packageName) {
17782        final int callingUid = Binder.getCallingUid();
17783        final List<String> result = new ArrayList<>();
17784        if (getInstantAppPackageName(callingUid) != null) {
17785            return result;
17786        }
17787        final PackageSetting ps = mSettings.mPackages.get(packageName);
17788        if (ps != null
17789                && ps.oldCodePaths != null
17790                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17791            result.addAll(ps.oldCodePaths);
17792        }
17793        return result;
17794    }
17795
17796    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17797            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17798            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17799            int installReason) {
17800        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17801                + deletedPackage);
17802
17803        String pkgName = deletedPackage.packageName;
17804        boolean deletedPkg = true;
17805        boolean addedPkg = false;
17806        boolean updatedSettings = false;
17807        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17808        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17809                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17810
17811        final long origUpdateTime = (pkg.mExtras != null)
17812                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17813
17814        // First delete the existing package while retaining the data directory
17815        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17816                res.removedInfo, true, pkg)) {
17817            // If the existing package wasn't successfully deleted
17818            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17819            deletedPkg = false;
17820        } else {
17821            // Successfully deleted the old package; proceed with replace.
17822
17823            // If deleted package lived in a container, give users a chance to
17824            // relinquish resources before killing.
17825            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17826                if (DEBUG_INSTALL) {
17827                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17828                }
17829                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17830                final ArrayList<String> pkgList = new ArrayList<String>(1);
17831                pkgList.add(deletedPackage.applicationInfo.packageName);
17832                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17833            }
17834
17835            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17836                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17837            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17838
17839            try {
17840                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17841                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17842                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17843                        installReason);
17844
17845                // Update the in-memory copy of the previous code paths.
17846                PackageSetting ps = mSettings.mPackages.get(pkgName);
17847                if (!killApp) {
17848                    if (ps.oldCodePaths == null) {
17849                        ps.oldCodePaths = new ArraySet<>();
17850                    }
17851                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17852                    if (deletedPackage.splitCodePaths != null) {
17853                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17854                    }
17855                } else {
17856                    ps.oldCodePaths = null;
17857                }
17858                if (ps.childPackageNames != null) {
17859                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17860                        final String childPkgName = ps.childPackageNames.get(i);
17861                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17862                        childPs.oldCodePaths = ps.oldCodePaths;
17863                    }
17864                }
17865                // set instant app status, but, only if it's explicitly specified
17866                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17867                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17868                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17869                prepareAppDataAfterInstallLIF(newPackage);
17870                addedPkg = true;
17871                mDexManager.notifyPackageUpdated(newPackage.packageName,
17872                        newPackage.baseCodePath, newPackage.splitCodePaths);
17873            } catch (PackageManagerException e) {
17874                res.setError("Package couldn't be installed in " + pkg.codePath, e);
17875            }
17876        }
17877
17878        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17879            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17880
17881            // Revert all internal state mutations and added folders for the failed install
17882            if (addedPkg) {
17883                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17884                        res.removedInfo, true, null);
17885            }
17886
17887            // Restore the old package
17888            if (deletedPkg) {
17889                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17890                File restoreFile = new File(deletedPackage.codePath);
17891                // Parse old package
17892                boolean oldExternal = isExternal(deletedPackage);
17893                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
17894                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17895                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17896                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17897                try {
17898                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17899                            null);
17900                } catch (PackageManagerException e) {
17901                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17902                            + e.getMessage());
17903                    return;
17904                }
17905
17906                synchronized (mPackages) {
17907                    // Ensure the installer package name up to date
17908                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17909
17910                    // Update permissions for restored package
17911                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17912
17913                    mSettings.writeLPr();
17914                }
17915
17916                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17917            }
17918        } else {
17919            synchronized (mPackages) {
17920                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17921                if (ps != null) {
17922                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17923                    if (res.removedInfo.removedChildPackages != null) {
17924                        final int childCount = res.removedInfo.removedChildPackages.size();
17925                        // Iterate in reverse as we may modify the collection
17926                        for (int i = childCount - 1; i >= 0; i--) {
17927                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17928                            if (res.addedChildPackages.containsKey(childPackageName)) {
17929                                res.removedInfo.removedChildPackages.removeAt(i);
17930                            } else {
17931                                PackageRemovedInfo childInfo = res.removedInfo
17932                                        .removedChildPackages.valueAt(i);
17933                                childInfo.removedForAllUsers = mPackages.get(
17934                                        childInfo.removedPackage) == null;
17935                            }
17936                        }
17937                    }
17938                }
17939            }
17940        }
17941    }
17942
17943    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
17944            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17945            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17946            int installReason) {
17947        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
17948                + ", old=" + deletedPackage);
17949
17950        final boolean disabledSystem;
17951
17952        // Remove existing system package
17953        removePackageLI(deletedPackage, true);
17954
17955        synchronized (mPackages) {
17956            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
17957        }
17958        if (!disabledSystem) {
17959            // We didn't need to disable the .apk as a current system package,
17960            // which means we are replacing another update that is already
17961            // installed.  We need to make sure to delete the older one's .apk.
17962            res.removedInfo.args = createInstallArgsForExisting(0,
17963                    deletedPackage.applicationInfo.getCodePath(),
17964                    deletedPackage.applicationInfo.getResourcePath(),
17965                    getAppDexInstructionSets(deletedPackage.applicationInfo));
17966        } else {
17967            res.removedInfo.args = null;
17968        }
17969
17970        // Successfully disabled the old package. Now proceed with re-installation
17971        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17972                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17973        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17974
17975        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17976        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
17977                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
17978
17979        PackageParser.Package newPackage = null;
17980        try {
17981            // Add the package to the internal data structures
17982            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
17983
17984            // Set the update and install times
17985            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
17986            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
17987                    System.currentTimeMillis());
17988
17989            // Update the package dynamic state if succeeded
17990            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17991                // Now that the install succeeded make sure we remove data
17992                // directories for any child package the update removed.
17993                final int deletedChildCount = (deletedPackage.childPackages != null)
17994                        ? deletedPackage.childPackages.size() : 0;
17995                final int newChildCount = (newPackage.childPackages != null)
17996                        ? newPackage.childPackages.size() : 0;
17997                for (int i = 0; i < deletedChildCount; i++) {
17998                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
17999                    boolean childPackageDeleted = true;
18000                    for (int j = 0; j < newChildCount; j++) {
18001                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
18002                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
18003                            childPackageDeleted = false;
18004                            break;
18005                        }
18006                    }
18007                    if (childPackageDeleted) {
18008                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
18009                                deletedChildPkg.packageName);
18010                        if (ps != null && res.removedInfo.removedChildPackages != null) {
18011                            PackageRemovedInfo removedChildRes = res.removedInfo
18012                                    .removedChildPackages.get(deletedChildPkg.packageName);
18013                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
18014                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
18015                        }
18016                    }
18017                }
18018
18019                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
18020                        installReason);
18021                prepareAppDataAfterInstallLIF(newPackage);
18022
18023                mDexManager.notifyPackageUpdated(newPackage.packageName,
18024                            newPackage.baseCodePath, newPackage.splitCodePaths);
18025            }
18026        } catch (PackageManagerException e) {
18027            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
18028            res.setError("Package couldn't be installed in " + pkg.codePath, e);
18029        }
18030
18031        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
18032            // Re installation failed. Restore old information
18033            // Remove new pkg information
18034            if (newPackage != null) {
18035                removeInstalledPackageLI(newPackage, true);
18036            }
18037            // Add back the old system package
18038            try {
18039                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
18040            } catch (PackageManagerException e) {
18041                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
18042            }
18043
18044            synchronized (mPackages) {
18045                if (disabledSystem) {
18046                    enableSystemPackageLPw(deletedPackage);
18047                }
18048
18049                // Ensure the installer package name up to date
18050                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
18051
18052                // Update permissions for restored package
18053                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
18054
18055                mSettings.writeLPr();
18056            }
18057
18058            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
18059                    + " after failed upgrade");
18060        }
18061    }
18062
18063    /**
18064     * Checks whether the parent or any of the child packages have a change shared
18065     * user. For a package to be a valid update the shred users of the parent and
18066     * the children should match. We may later support changing child shared users.
18067     * @param oldPkg The updated package.
18068     * @param newPkg The update package.
18069     * @return The shared user that change between the versions.
18070     */
18071    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
18072            PackageParser.Package newPkg) {
18073        // Check parent shared user
18074        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
18075            return newPkg.packageName;
18076        }
18077        // Check child shared users
18078        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
18079        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
18080        for (int i = 0; i < newChildCount; i++) {
18081            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
18082            // If this child was present, did it have the same shared user?
18083            for (int j = 0; j < oldChildCount; j++) {
18084                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
18085                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
18086                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
18087                    return newChildPkg.packageName;
18088                }
18089            }
18090        }
18091        return null;
18092    }
18093
18094    private void removeNativeBinariesLI(PackageSetting ps) {
18095        // Remove the lib path for the parent package
18096        if (ps != null) {
18097            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
18098            // Remove the lib path for the child packages
18099            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18100            for (int i = 0; i < childCount; i++) {
18101                PackageSetting childPs = null;
18102                synchronized (mPackages) {
18103                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18104                }
18105                if (childPs != null) {
18106                    NativeLibraryHelper.removeNativeBinariesLI(childPs
18107                            .legacyNativeLibraryPathString);
18108                }
18109            }
18110        }
18111    }
18112
18113    private void enableSystemPackageLPw(PackageParser.Package pkg) {
18114        // Enable the parent package
18115        mSettings.enableSystemPackageLPw(pkg.packageName);
18116        // Enable the child packages
18117        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18118        for (int i = 0; i < childCount; i++) {
18119            PackageParser.Package childPkg = pkg.childPackages.get(i);
18120            mSettings.enableSystemPackageLPw(childPkg.packageName);
18121        }
18122    }
18123
18124    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
18125            PackageParser.Package newPkg) {
18126        // Disable the parent package (parent always replaced)
18127        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
18128        // Disable the child packages
18129        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
18130        for (int i = 0; i < childCount; i++) {
18131            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
18132            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
18133            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
18134        }
18135        return disabled;
18136    }
18137
18138    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
18139            String installerPackageName) {
18140        // Enable the parent package
18141        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
18142        // Enable the child packages
18143        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18144        for (int i = 0; i < childCount; i++) {
18145            PackageParser.Package childPkg = pkg.childPackages.get(i);
18146            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
18147        }
18148    }
18149
18150    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
18151        // Collect all used permissions in the UID
18152        ArraySet<String> usedPermissions = new ArraySet<>();
18153        final int packageCount = su.packages.size();
18154        for (int i = 0; i < packageCount; i++) {
18155            PackageSetting ps = su.packages.valueAt(i);
18156            if (ps.pkg == null) {
18157                continue;
18158            }
18159            final int requestedPermCount = ps.pkg.requestedPermissions.size();
18160            for (int j = 0; j < requestedPermCount; j++) {
18161                String permission = ps.pkg.requestedPermissions.get(j);
18162                BasePermission bp = mSettings.mPermissions.get(permission);
18163                if (bp != null) {
18164                    usedPermissions.add(permission);
18165                }
18166            }
18167        }
18168
18169        PermissionsState permissionsState = su.getPermissionsState();
18170        // Prune install permissions
18171        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
18172        final int installPermCount = installPermStates.size();
18173        for (int i = installPermCount - 1; i >= 0;  i--) {
18174            PermissionState permissionState = installPermStates.get(i);
18175            if (!usedPermissions.contains(permissionState.getName())) {
18176                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
18177                if (bp != null) {
18178                    permissionsState.revokeInstallPermission(bp);
18179                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
18180                            PackageManager.MASK_PERMISSION_FLAGS, 0);
18181                }
18182            }
18183        }
18184
18185        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
18186
18187        // Prune runtime permissions
18188        for (int userId : allUserIds) {
18189            List<PermissionState> runtimePermStates = permissionsState
18190                    .getRuntimePermissionStates(userId);
18191            final int runtimePermCount = runtimePermStates.size();
18192            for (int i = runtimePermCount - 1; i >= 0; i--) {
18193                PermissionState permissionState = runtimePermStates.get(i);
18194                if (!usedPermissions.contains(permissionState.getName())) {
18195                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
18196                    if (bp != null) {
18197                        permissionsState.revokeRuntimePermission(bp, userId);
18198                        permissionsState.updatePermissionFlags(bp, userId,
18199                                PackageManager.MASK_PERMISSION_FLAGS, 0);
18200                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
18201                                runtimePermissionChangedUserIds, userId);
18202                    }
18203                }
18204            }
18205        }
18206
18207        return runtimePermissionChangedUserIds;
18208    }
18209
18210    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
18211            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
18212        // Update the parent package setting
18213        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
18214                res, user, installReason);
18215        // Update the child packages setting
18216        final int childCount = (newPackage.childPackages != null)
18217                ? newPackage.childPackages.size() : 0;
18218        for (int i = 0; i < childCount; i++) {
18219            PackageParser.Package childPackage = newPackage.childPackages.get(i);
18220            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
18221            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
18222                    childRes.origUsers, childRes, user, installReason);
18223        }
18224    }
18225
18226    private void updateSettingsInternalLI(PackageParser.Package newPackage,
18227            String installerPackageName, int[] allUsers, int[] installedForUsers,
18228            PackageInstalledInfo res, UserHandle user, int installReason) {
18229        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
18230
18231        String pkgName = newPackage.packageName;
18232        synchronized (mPackages) {
18233            //write settings. the installStatus will be incomplete at this stage.
18234            //note that the new package setting would have already been
18235            //added to mPackages. It hasn't been persisted yet.
18236            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
18237            // TODO: Remove this write? It's also written at the end of this method
18238            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
18239            mSettings.writeLPr();
18240            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18241        }
18242
18243        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
18244        synchronized (mPackages) {
18245            updatePermissionsLPw(newPackage.packageName, newPackage,
18246                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
18247                            ? UPDATE_PERMISSIONS_ALL : 0));
18248            // For system-bundled packages, we assume that installing an upgraded version
18249            // of the package implies that the user actually wants to run that new code,
18250            // so we enable the package.
18251            PackageSetting ps = mSettings.mPackages.get(pkgName);
18252            final int userId = user.getIdentifier();
18253            if (ps != null) {
18254                if (isSystemApp(newPackage)) {
18255                    if (DEBUG_INSTALL) {
18256                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
18257                    }
18258                    // Enable system package for requested users
18259                    if (res.origUsers != null) {
18260                        for (int origUserId : res.origUsers) {
18261                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
18262                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
18263                                        origUserId, installerPackageName);
18264                            }
18265                        }
18266                    }
18267                    // Also convey the prior install/uninstall state
18268                    if (allUsers != null && installedForUsers != null) {
18269                        for (int currentUserId : allUsers) {
18270                            final boolean installed = ArrayUtils.contains(
18271                                    installedForUsers, currentUserId);
18272                            if (DEBUG_INSTALL) {
18273                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
18274                            }
18275                            ps.setInstalled(installed, currentUserId);
18276                        }
18277                        // these install state changes will be persisted in the
18278                        // upcoming call to mSettings.writeLPr().
18279                    }
18280                }
18281                // It's implied that when a user requests installation, they want the app to be
18282                // installed and enabled.
18283                if (userId != UserHandle.USER_ALL) {
18284                    ps.setInstalled(true, userId);
18285                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
18286                }
18287
18288                // When replacing an existing package, preserve the original install reason for all
18289                // users that had the package installed before.
18290                final Set<Integer> previousUserIds = new ArraySet<>();
18291                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
18292                    final int installReasonCount = res.removedInfo.installReasons.size();
18293                    for (int i = 0; i < installReasonCount; i++) {
18294                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
18295                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
18296                        ps.setInstallReason(previousInstallReason, previousUserId);
18297                        previousUserIds.add(previousUserId);
18298                    }
18299                }
18300
18301                // Set install reason for users that are having the package newly installed.
18302                if (userId == UserHandle.USER_ALL) {
18303                    for (int currentUserId : sUserManager.getUserIds()) {
18304                        if (!previousUserIds.contains(currentUserId)) {
18305                            ps.setInstallReason(installReason, currentUserId);
18306                        }
18307                    }
18308                } else if (!previousUserIds.contains(userId)) {
18309                    ps.setInstallReason(installReason, userId);
18310                }
18311                mSettings.writeKernelMappingLPr(ps);
18312            }
18313            res.name = pkgName;
18314            res.uid = newPackage.applicationInfo.uid;
18315            res.pkg = newPackage;
18316            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
18317            mSettings.setInstallerPackageName(pkgName, installerPackageName);
18318            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18319            //to update install status
18320            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
18321            mSettings.writeLPr();
18322            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18323        }
18324
18325        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18326    }
18327
18328    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
18329        try {
18330            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
18331            installPackageLI(args, res);
18332        } finally {
18333            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18334        }
18335    }
18336
18337    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
18338        final int installFlags = args.installFlags;
18339        final String installerPackageName = args.installerPackageName;
18340        final String volumeUuid = args.volumeUuid;
18341        final File tmpPackageFile = new File(args.getCodePath());
18342        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
18343        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
18344                || (args.volumeUuid != null));
18345        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
18346        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
18347        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
18348        final boolean virtualPreload =
18349                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
18350        boolean replace = false;
18351        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
18352        if (args.move != null) {
18353            // moving a complete application; perform an initial scan on the new install location
18354            scanFlags |= SCAN_INITIAL;
18355        }
18356        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
18357            scanFlags |= SCAN_DONT_KILL_APP;
18358        }
18359        if (instantApp) {
18360            scanFlags |= SCAN_AS_INSTANT_APP;
18361        }
18362        if (fullApp) {
18363            scanFlags |= SCAN_AS_FULL_APP;
18364        }
18365        if (virtualPreload) {
18366            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
18367        }
18368
18369        // Result object to be returned
18370        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18371        res.installerPackageName = installerPackageName;
18372
18373        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
18374
18375        // Sanity check
18376        if (instantApp && (forwardLocked || onExternal)) {
18377            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
18378                    + " external=" + onExternal);
18379            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
18380            return;
18381        }
18382
18383        // Retrieve PackageSettings and parse package
18384        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
18385                | PackageParser.PARSE_ENFORCE_CODE
18386                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
18387                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
18388                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
18389                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
18390        PackageParser pp = new PackageParser();
18391        pp.setSeparateProcesses(mSeparateProcesses);
18392        pp.setDisplayMetrics(mMetrics);
18393        pp.setCallback(mPackageParserCallback);
18394
18395        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
18396        final PackageParser.Package pkg;
18397        try {
18398            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
18399        } catch (PackageParserException e) {
18400            res.setError("Failed parse during installPackageLI", e);
18401            return;
18402        } finally {
18403            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18404        }
18405
18406        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
18407        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
18408            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
18409            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18410                    "Instant app package must target O");
18411            return;
18412        }
18413        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
18414            Slog.w(TAG, "Instant app package " + pkg.packageName
18415                    + " does not target targetSandboxVersion 2");
18416            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18417                    "Instant app package must use targetSanboxVersion 2");
18418            return;
18419        }
18420
18421        if (pkg.applicationInfo.isStaticSharedLibrary()) {
18422            // Static shared libraries have synthetic package names
18423            renameStaticSharedLibraryPackage(pkg);
18424
18425            // No static shared libs on external storage
18426            if (onExternal) {
18427                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
18428                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18429                        "Packages declaring static-shared libs cannot be updated");
18430                return;
18431            }
18432        }
18433
18434        // If we are installing a clustered package add results for the children
18435        if (pkg.childPackages != null) {
18436            synchronized (mPackages) {
18437                final int childCount = pkg.childPackages.size();
18438                for (int i = 0; i < childCount; i++) {
18439                    PackageParser.Package childPkg = pkg.childPackages.get(i);
18440                    PackageInstalledInfo childRes = new PackageInstalledInfo();
18441                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18442                    childRes.pkg = childPkg;
18443                    childRes.name = childPkg.packageName;
18444                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18445                    if (childPs != null) {
18446                        childRes.origUsers = childPs.queryInstalledUsers(
18447                                sUserManager.getUserIds(), true);
18448                    }
18449                    if ((mPackages.containsKey(childPkg.packageName))) {
18450                        childRes.removedInfo = new PackageRemovedInfo(this);
18451                        childRes.removedInfo.removedPackage = childPkg.packageName;
18452                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
18453                    }
18454                    if (res.addedChildPackages == null) {
18455                        res.addedChildPackages = new ArrayMap<>();
18456                    }
18457                    res.addedChildPackages.put(childPkg.packageName, childRes);
18458                }
18459            }
18460        }
18461
18462        // If package doesn't declare API override, mark that we have an install
18463        // time CPU ABI override.
18464        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
18465            pkg.cpuAbiOverride = args.abiOverride;
18466        }
18467
18468        String pkgName = res.name = pkg.packageName;
18469        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
18470            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
18471                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
18472                return;
18473            }
18474        }
18475
18476        try {
18477            // either use what we've been given or parse directly from the APK
18478            if (args.certificates != null) {
18479                try {
18480                    PackageParser.populateCertificates(pkg, args.certificates);
18481                } catch (PackageParserException e) {
18482                    // there was something wrong with the certificates we were given;
18483                    // try to pull them from the APK
18484                    PackageParser.collectCertificates(pkg, parseFlags);
18485                }
18486            } else {
18487                PackageParser.collectCertificates(pkg, parseFlags);
18488            }
18489        } catch (PackageParserException e) {
18490            res.setError("Failed collect during installPackageLI", e);
18491            return;
18492        }
18493
18494        // Get rid of all references to package scan path via parser.
18495        pp = null;
18496        String oldCodePath = null;
18497        boolean systemApp = false;
18498        synchronized (mPackages) {
18499            // Check if installing already existing package
18500            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
18501                String oldName = mSettings.getRenamedPackageLPr(pkgName);
18502                if (pkg.mOriginalPackages != null
18503                        && pkg.mOriginalPackages.contains(oldName)
18504                        && mPackages.containsKey(oldName)) {
18505                    // This package is derived from an original package,
18506                    // and this device has been updating from that original
18507                    // name.  We must continue using the original name, so
18508                    // rename the new package here.
18509                    pkg.setPackageName(oldName);
18510                    pkgName = pkg.packageName;
18511                    replace = true;
18512                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
18513                            + oldName + " pkgName=" + pkgName);
18514                } else if (mPackages.containsKey(pkgName)) {
18515                    // This package, under its official name, already exists
18516                    // on the device; we should replace it.
18517                    replace = true;
18518                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
18519                }
18520
18521                // Child packages are installed through the parent package
18522                if (pkg.parentPackage != null) {
18523                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18524                            "Package " + pkg.packageName + " is child of package "
18525                                    + pkg.parentPackage.parentPackage + ". Child packages "
18526                                    + "can be updated only through the parent package.");
18527                    return;
18528                }
18529
18530                if (replace) {
18531                    // Prevent apps opting out from runtime permissions
18532                    PackageParser.Package oldPackage = mPackages.get(pkgName);
18533                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
18534                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
18535                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
18536                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
18537                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
18538                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
18539                                        + " doesn't support runtime permissions but the old"
18540                                        + " target SDK " + oldTargetSdk + " does.");
18541                        return;
18542                    }
18543                    // Prevent apps from downgrading their targetSandbox.
18544                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
18545                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
18546                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
18547                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18548                                "Package " + pkg.packageName + " new target sandbox "
18549                                + newTargetSandbox + " is incompatible with the previous value of"
18550                                + oldTargetSandbox + ".");
18551                        return;
18552                    }
18553
18554                    // Prevent installing of child packages
18555                    if (oldPackage.parentPackage != null) {
18556                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18557                                "Package " + pkg.packageName + " is child of package "
18558                                        + oldPackage.parentPackage + ". Child packages "
18559                                        + "can be updated only through the parent package.");
18560                        return;
18561                    }
18562                }
18563            }
18564
18565            PackageSetting ps = mSettings.mPackages.get(pkgName);
18566            if (ps != null) {
18567                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
18568
18569                // Static shared libs have same package with different versions where
18570                // we internally use a synthetic package name to allow multiple versions
18571                // of the same package, therefore we need to compare signatures against
18572                // the package setting for the latest library version.
18573                PackageSetting signatureCheckPs = ps;
18574                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18575                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
18576                    if (libraryEntry != null) {
18577                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
18578                    }
18579                }
18580
18581                // Quick sanity check that we're signed correctly if updating;
18582                // we'll check this again later when scanning, but we want to
18583                // bail early here before tripping over redefined permissions.
18584                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
18585                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
18586                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
18587                                + pkg.packageName + " upgrade keys do not match the "
18588                                + "previously installed version");
18589                        return;
18590                    }
18591                } else {
18592                    try {
18593                        verifySignaturesLP(signatureCheckPs, pkg);
18594                    } catch (PackageManagerException e) {
18595                        res.setError(e.error, e.getMessage());
18596                        return;
18597                    }
18598                }
18599
18600                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
18601                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
18602                    systemApp = (ps.pkg.applicationInfo.flags &
18603                            ApplicationInfo.FLAG_SYSTEM) != 0;
18604                }
18605                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18606            }
18607
18608            int N = pkg.permissions.size();
18609            for (int i = N-1; i >= 0; i--) {
18610                PackageParser.Permission perm = pkg.permissions.get(i);
18611                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
18612
18613                // Don't allow anyone but the system to define ephemeral permissions.
18614                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
18615                        && !systemApp) {
18616                    Slog.w(TAG, "Non-System package " + pkg.packageName
18617                            + " attempting to delcare ephemeral permission "
18618                            + perm.info.name + "; Removing ephemeral.");
18619                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
18620                }
18621                // Check whether the newly-scanned package wants to define an already-defined perm
18622                if (bp != null) {
18623                    // If the defining package is signed with our cert, it's okay.  This
18624                    // also includes the "updating the same package" case, of course.
18625                    // "updating same package" could also involve key-rotation.
18626                    final boolean sigsOk;
18627                    if (bp.sourcePackage.equals(pkg.packageName)
18628                            && (bp.packageSetting instanceof PackageSetting)
18629                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
18630                                    scanFlags))) {
18631                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
18632                    } else {
18633                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
18634                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18635                    }
18636                    if (!sigsOk) {
18637                        // If the owning package is the system itself, we log but allow
18638                        // install to proceed; we fail the install on all other permission
18639                        // redefinitions.
18640                        if (!bp.sourcePackage.equals("android")) {
18641                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18642                                    + pkg.packageName + " attempting to redeclare permission "
18643                                    + perm.info.name + " already owned by " + bp.sourcePackage);
18644                            res.origPermission = perm.info.name;
18645                            res.origPackage = bp.sourcePackage;
18646                            return;
18647                        } else {
18648                            Slog.w(TAG, "Package " + pkg.packageName
18649                                    + " attempting to redeclare system permission "
18650                                    + perm.info.name + "; ignoring new declaration");
18651                            pkg.permissions.remove(i);
18652                        }
18653                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18654                        // Prevent apps to change protection level to dangerous from any other
18655                        // type as this would allow a privilege escalation where an app adds a
18656                        // normal/signature permission in other app's group and later redefines
18657                        // it as dangerous leading to the group auto-grant.
18658                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18659                                == PermissionInfo.PROTECTION_DANGEROUS) {
18660                            if (bp != null && !bp.isRuntime()) {
18661                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18662                                        + "non-runtime permission " + perm.info.name
18663                                        + " to runtime; keeping old protection level");
18664                                perm.info.protectionLevel = bp.protectionLevel;
18665                            }
18666                        }
18667                    }
18668                }
18669            }
18670        }
18671
18672        if (systemApp) {
18673            if (onExternal) {
18674                // Abort update; system app can't be replaced with app on sdcard
18675                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18676                        "Cannot install updates to system apps on sdcard");
18677                return;
18678            } else if (instantApp) {
18679                // Abort update; system app can't be replaced with an instant app
18680                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18681                        "Cannot update a system app with an instant app");
18682                return;
18683            }
18684        }
18685
18686        if (args.move != null) {
18687            // We did an in-place move, so dex is ready to roll
18688            scanFlags |= SCAN_NO_DEX;
18689            scanFlags |= SCAN_MOVE;
18690
18691            synchronized (mPackages) {
18692                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18693                if (ps == null) {
18694                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18695                            "Missing settings for moved package " + pkgName);
18696                }
18697
18698                // We moved the entire application as-is, so bring over the
18699                // previously derived ABI information.
18700                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18701                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18702            }
18703
18704        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18705            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18706            scanFlags |= SCAN_NO_DEX;
18707
18708            try {
18709                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18710                    args.abiOverride : pkg.cpuAbiOverride);
18711                final boolean extractNativeLibs = !pkg.isLibrary();
18712                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18713                        extractNativeLibs, mAppLib32InstallDir);
18714            } catch (PackageManagerException pme) {
18715                Slog.e(TAG, "Error deriving application ABI", pme);
18716                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18717                return;
18718            }
18719
18720            // Shared libraries for the package need to be updated.
18721            synchronized (mPackages) {
18722                try {
18723                    updateSharedLibrariesLPr(pkg, null);
18724                } catch (PackageManagerException e) {
18725                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18726                }
18727            }
18728        }
18729
18730        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18731            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18732            return;
18733        }
18734
18735        // Verify if we need to dexopt the app.
18736        //
18737        // NOTE: it is *important* to call dexopt after doRename which will sync the
18738        // package data from PackageParser.Package and its corresponding ApplicationInfo.
18739        //
18740        // We only need to dexopt if the package meets ALL of the following conditions:
18741        //   1) it is not forward locked.
18742        //   2) it is not on on an external ASEC container.
18743        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
18744        //
18745        // Note that we do not dexopt instant apps by default. dexopt can take some time to
18746        // complete, so we skip this step during installation. Instead, we'll take extra time
18747        // the first time the instant app starts. It's preferred to do it this way to provide
18748        // continuous progress to the useur instead of mysteriously blocking somewhere in the
18749        // middle of running an instant app. The default behaviour can be overridden
18750        // via gservices.
18751        final boolean performDexopt = !forwardLocked
18752            && !pkg.applicationInfo.isExternalAsec()
18753            && (!instantApp || Global.getInt(mContext.getContentResolver(),
18754                    Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
18755
18756        if (performDexopt) {
18757            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18758            // Do not run PackageDexOptimizer through the local performDexOpt
18759            // method because `pkg` may not be in `mPackages` yet.
18760            //
18761            // Also, don't fail application installs if the dexopt step fails.
18762            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
18763                REASON_INSTALL,
18764                DexoptOptions.DEXOPT_BOOT_COMPLETE);
18765            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18766                null /* instructionSets */,
18767                getOrCreateCompilerPackageStats(pkg),
18768                mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
18769                dexoptOptions);
18770            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18771        }
18772
18773        // Notify BackgroundDexOptService that the package has been changed.
18774        // If this is an update of a package which used to fail to compile,
18775        // BackgroundDexOptService will remove it from its blacklist.
18776        // TODO: Layering violation
18777        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18778
18779        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18780
18781        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18782                "installPackageLI")) {
18783            if (replace) {
18784                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18785                    // Static libs have a synthetic package name containing the version
18786                    // and cannot be updated as an update would get a new package name,
18787                    // unless this is the exact same version code which is useful for
18788                    // development.
18789                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18790                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18791                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18792                                + "static-shared libs cannot be updated");
18793                        return;
18794                    }
18795                }
18796                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18797                        installerPackageName, res, args.installReason);
18798            } else {
18799                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18800                        args.user, installerPackageName, volumeUuid, res, args.installReason);
18801            }
18802        }
18803
18804        synchronized (mPackages) {
18805            final PackageSetting ps = mSettings.mPackages.get(pkgName);
18806            if (ps != null) {
18807                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18808                ps.setUpdateAvailable(false /*updateAvailable*/);
18809            }
18810
18811            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18812            for (int i = 0; i < childCount; i++) {
18813                PackageParser.Package childPkg = pkg.childPackages.get(i);
18814                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18815                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18816                if (childPs != null) {
18817                    childRes.newUsers = childPs.queryInstalledUsers(
18818                            sUserManager.getUserIds(), true);
18819                }
18820            }
18821
18822            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18823                updateSequenceNumberLP(ps, res.newUsers);
18824                updateInstantAppInstallerLocked(pkgName);
18825            }
18826        }
18827    }
18828
18829    private void startIntentFilterVerifications(int userId, boolean replacing,
18830            PackageParser.Package pkg) {
18831        if (mIntentFilterVerifierComponent == null) {
18832            Slog.w(TAG, "No IntentFilter verification will not be done as "
18833                    + "there is no IntentFilterVerifier available!");
18834            return;
18835        }
18836
18837        final int verifierUid = getPackageUid(
18838                mIntentFilterVerifierComponent.getPackageName(),
18839                MATCH_DEBUG_TRIAGED_MISSING,
18840                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18841
18842        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18843        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18844        mHandler.sendMessage(msg);
18845
18846        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18847        for (int i = 0; i < childCount; i++) {
18848            PackageParser.Package childPkg = pkg.childPackages.get(i);
18849            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18850            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18851            mHandler.sendMessage(msg);
18852        }
18853    }
18854
18855    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18856            PackageParser.Package pkg) {
18857        int size = pkg.activities.size();
18858        if (size == 0) {
18859            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18860                    "No activity, so no need to verify any IntentFilter!");
18861            return;
18862        }
18863
18864        final boolean hasDomainURLs = hasDomainURLs(pkg);
18865        if (!hasDomainURLs) {
18866            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18867                    "No domain URLs, so no need to verify any IntentFilter!");
18868            return;
18869        }
18870
18871        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18872                + " if any IntentFilter from the " + size
18873                + " Activities needs verification ...");
18874
18875        int count = 0;
18876        final String packageName = pkg.packageName;
18877
18878        synchronized (mPackages) {
18879            // If this is a new install and we see that we've already run verification for this
18880            // package, we have nothing to do: it means the state was restored from backup.
18881            if (!replacing) {
18882                IntentFilterVerificationInfo ivi =
18883                        mSettings.getIntentFilterVerificationLPr(packageName);
18884                if (ivi != null) {
18885                    if (DEBUG_DOMAIN_VERIFICATION) {
18886                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
18887                                + ivi.getStatusString());
18888                    }
18889                    return;
18890                }
18891            }
18892
18893            // If any filters need to be verified, then all need to be.
18894            boolean needToVerify = false;
18895            for (PackageParser.Activity a : pkg.activities) {
18896                for (ActivityIntentInfo filter : a.intents) {
18897                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18898                        if (DEBUG_DOMAIN_VERIFICATION) {
18899                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18900                        }
18901                        needToVerify = true;
18902                        break;
18903                    }
18904                }
18905            }
18906
18907            if (needToVerify) {
18908                final int verificationId = mIntentFilterVerificationToken++;
18909                for (PackageParser.Activity a : pkg.activities) {
18910                    for (ActivityIntentInfo filter : a.intents) {
18911                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
18912                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18913                                    "Verification needed for IntentFilter:" + filter.toString());
18914                            mIntentFilterVerifier.addOneIntentFilterVerification(
18915                                    verifierUid, userId, verificationId, filter, packageName);
18916                            count++;
18917                        }
18918                    }
18919                }
18920            }
18921        }
18922
18923        if (count > 0) {
18924            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
18925                    + " IntentFilter verification" + (count > 1 ? "s" : "")
18926                    +  " for userId:" + userId);
18927            mIntentFilterVerifier.startVerifications(userId);
18928        } else {
18929            if (DEBUG_DOMAIN_VERIFICATION) {
18930                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
18931            }
18932        }
18933    }
18934
18935    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
18936        final ComponentName cn  = filter.activity.getComponentName();
18937        final String packageName = cn.getPackageName();
18938
18939        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
18940                packageName);
18941        if (ivi == null) {
18942            return true;
18943        }
18944        int status = ivi.getStatus();
18945        switch (status) {
18946            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
18947            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
18948                return true;
18949
18950            default:
18951                // Nothing to do
18952                return false;
18953        }
18954    }
18955
18956    private static boolean isMultiArch(ApplicationInfo info) {
18957        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
18958    }
18959
18960    private static boolean isExternal(PackageParser.Package pkg) {
18961        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18962    }
18963
18964    private static boolean isExternal(PackageSetting ps) {
18965        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18966    }
18967
18968    private static boolean isSystemApp(PackageParser.Package pkg) {
18969        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
18970    }
18971
18972    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
18973        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
18974    }
18975
18976    private static boolean hasDomainURLs(PackageParser.Package pkg) {
18977        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
18978    }
18979
18980    private static boolean isSystemApp(PackageSetting ps) {
18981        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
18982    }
18983
18984    private static boolean isUpdatedSystemApp(PackageSetting ps) {
18985        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
18986    }
18987
18988    private int packageFlagsToInstallFlags(PackageSetting ps) {
18989        int installFlags = 0;
18990        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
18991            // This existing package was an external ASEC install when we have
18992            // the external flag without a UUID
18993            installFlags |= PackageManager.INSTALL_EXTERNAL;
18994        }
18995        if (ps.isForwardLocked()) {
18996            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
18997        }
18998        return installFlags;
18999    }
19000
19001    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
19002        if (isExternal(pkg)) {
19003            if (TextUtils.isEmpty(pkg.volumeUuid)) {
19004                return StorageManager.UUID_PRIMARY_PHYSICAL;
19005            } else {
19006                return pkg.volumeUuid;
19007            }
19008        } else {
19009            return StorageManager.UUID_PRIVATE_INTERNAL;
19010        }
19011    }
19012
19013    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
19014        if (isExternal(pkg)) {
19015            if (TextUtils.isEmpty(pkg.volumeUuid)) {
19016                return mSettings.getExternalVersion();
19017            } else {
19018                return mSettings.findOrCreateVersion(pkg.volumeUuid);
19019            }
19020        } else {
19021            return mSettings.getInternalVersion();
19022        }
19023    }
19024
19025    private void deleteTempPackageFiles() {
19026        final FilenameFilter filter = new FilenameFilter() {
19027            public boolean accept(File dir, String name) {
19028                return name.startsWith("vmdl") && name.endsWith(".tmp");
19029            }
19030        };
19031        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
19032            file.delete();
19033        }
19034    }
19035
19036    @Override
19037    public void deletePackageAsUser(String packageName, int versionCode,
19038            IPackageDeleteObserver observer, int userId, int flags) {
19039        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
19040                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
19041    }
19042
19043    @Override
19044    public void deletePackageVersioned(VersionedPackage versionedPackage,
19045            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
19046        final int callingUid = Binder.getCallingUid();
19047        mContext.enforceCallingOrSelfPermission(
19048                android.Manifest.permission.DELETE_PACKAGES, null);
19049        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
19050        Preconditions.checkNotNull(versionedPackage);
19051        Preconditions.checkNotNull(observer);
19052        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
19053                PackageManager.VERSION_CODE_HIGHEST,
19054                Integer.MAX_VALUE, "versionCode must be >= -1");
19055
19056        final String packageName = versionedPackage.getPackageName();
19057        final int versionCode = versionedPackage.getVersionCode();
19058        final String internalPackageName;
19059        synchronized (mPackages) {
19060            // Normalize package name to handle renamed packages and static libs
19061            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
19062                    versionedPackage.getVersionCode());
19063        }
19064
19065        final int uid = Binder.getCallingUid();
19066        if (!isOrphaned(internalPackageName)
19067                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
19068            try {
19069                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
19070                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
19071                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
19072                observer.onUserActionRequired(intent);
19073            } catch (RemoteException re) {
19074            }
19075            return;
19076        }
19077        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
19078        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
19079        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
19080            mContext.enforceCallingOrSelfPermission(
19081                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
19082                    "deletePackage for user " + userId);
19083        }
19084
19085        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
19086            try {
19087                observer.onPackageDeleted(packageName,
19088                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
19089            } catch (RemoteException re) {
19090            }
19091            return;
19092        }
19093
19094        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
19095            try {
19096                observer.onPackageDeleted(packageName,
19097                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
19098            } catch (RemoteException re) {
19099            }
19100            return;
19101        }
19102
19103        if (DEBUG_REMOVE) {
19104            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
19105                    + " deleteAllUsers: " + deleteAllUsers + " version="
19106                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
19107                    ? "VERSION_CODE_HIGHEST" : versionCode));
19108        }
19109        // Queue up an async operation since the package deletion may take a little while.
19110        mHandler.post(new Runnable() {
19111            public void run() {
19112                mHandler.removeCallbacks(this);
19113                int returnCode;
19114                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
19115                boolean doDeletePackage = true;
19116                if (ps != null) {
19117                    final boolean targetIsInstantApp =
19118                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19119                    doDeletePackage = !targetIsInstantApp
19120                            || canViewInstantApps;
19121                }
19122                if (doDeletePackage) {
19123                    if (!deleteAllUsers) {
19124                        returnCode = deletePackageX(internalPackageName, versionCode,
19125                                userId, deleteFlags);
19126                    } else {
19127                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
19128                                internalPackageName, users);
19129                        // If nobody is blocking uninstall, proceed with delete for all users
19130                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
19131                            returnCode = deletePackageX(internalPackageName, versionCode,
19132                                    userId, deleteFlags);
19133                        } else {
19134                            // Otherwise uninstall individually for users with blockUninstalls=false
19135                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
19136                            for (int userId : users) {
19137                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
19138                                    returnCode = deletePackageX(internalPackageName, versionCode,
19139                                            userId, userFlags);
19140                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
19141                                        Slog.w(TAG, "Package delete failed for user " + userId
19142                                                + ", returnCode " + returnCode);
19143                                    }
19144                                }
19145                            }
19146                            // The app has only been marked uninstalled for certain users.
19147                            // We still need to report that delete was blocked
19148                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
19149                        }
19150                    }
19151                } else {
19152                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19153                }
19154                try {
19155                    observer.onPackageDeleted(packageName, returnCode, null);
19156                } catch (RemoteException e) {
19157                    Log.i(TAG, "Observer no longer exists.");
19158                } //end catch
19159            } //end run
19160        });
19161    }
19162
19163    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
19164        if (pkg.staticSharedLibName != null) {
19165            return pkg.manifestPackageName;
19166        }
19167        return pkg.packageName;
19168    }
19169
19170    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
19171        // Handle renamed packages
19172        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
19173        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
19174
19175        // Is this a static library?
19176        SparseArray<SharedLibraryEntry> versionedLib =
19177                mStaticLibsByDeclaringPackage.get(packageName);
19178        if (versionedLib == null || versionedLib.size() <= 0) {
19179            return packageName;
19180        }
19181
19182        // Figure out which lib versions the caller can see
19183        SparseIntArray versionsCallerCanSee = null;
19184        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
19185        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
19186                && callingAppId != Process.ROOT_UID) {
19187            versionsCallerCanSee = new SparseIntArray();
19188            String libName = versionedLib.valueAt(0).info.getName();
19189            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
19190            if (uidPackages != null) {
19191                for (String uidPackage : uidPackages) {
19192                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
19193                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
19194                    if (libIdx >= 0) {
19195                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
19196                        versionsCallerCanSee.append(libVersion, libVersion);
19197                    }
19198                }
19199            }
19200        }
19201
19202        // Caller can see nothing - done
19203        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
19204            return packageName;
19205        }
19206
19207        // Find the version the caller can see and the app version code
19208        SharedLibraryEntry highestVersion = null;
19209        final int versionCount = versionedLib.size();
19210        for (int i = 0; i < versionCount; i++) {
19211            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
19212            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
19213                    libEntry.info.getVersion()) < 0) {
19214                continue;
19215            }
19216            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
19217            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
19218                if (libVersionCode == versionCode) {
19219                    return libEntry.apk;
19220                }
19221            } else if (highestVersion == null) {
19222                highestVersion = libEntry;
19223            } else if (libVersionCode  > highestVersion.info
19224                    .getDeclaringPackage().getVersionCode()) {
19225                highestVersion = libEntry;
19226            }
19227        }
19228
19229        if (highestVersion != null) {
19230            return highestVersion.apk;
19231        }
19232
19233        return packageName;
19234    }
19235
19236    boolean isCallerVerifier(int callingUid) {
19237        final int callingUserId = UserHandle.getUserId(callingUid);
19238        return mRequiredVerifierPackage != null &&
19239                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
19240    }
19241
19242    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
19243        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
19244              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19245            return true;
19246        }
19247        final int callingUserId = UserHandle.getUserId(callingUid);
19248        // If the caller installed the pkgName, then allow it to silently uninstall.
19249        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
19250            return true;
19251        }
19252
19253        // Allow package verifier to silently uninstall.
19254        if (mRequiredVerifierPackage != null &&
19255                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
19256            return true;
19257        }
19258
19259        // Allow package uninstaller to silently uninstall.
19260        if (mRequiredUninstallerPackage != null &&
19261                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
19262            return true;
19263        }
19264
19265        // Allow storage manager to silently uninstall.
19266        if (mStorageManagerPackage != null &&
19267                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
19268            return true;
19269        }
19270
19271        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
19272        // uninstall for device owner provisioning.
19273        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
19274                == PERMISSION_GRANTED) {
19275            return true;
19276        }
19277
19278        return false;
19279    }
19280
19281    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
19282        int[] result = EMPTY_INT_ARRAY;
19283        for (int userId : userIds) {
19284            if (getBlockUninstallForUser(packageName, userId)) {
19285                result = ArrayUtils.appendInt(result, userId);
19286            }
19287        }
19288        return result;
19289    }
19290
19291    @Override
19292    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
19293        final int callingUid = Binder.getCallingUid();
19294        if (getInstantAppPackageName(callingUid) != null
19295                && !isCallerSameApp(packageName, callingUid)) {
19296            return false;
19297        }
19298        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
19299    }
19300
19301    private boolean isPackageDeviceAdmin(String packageName, int userId) {
19302        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
19303                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
19304        try {
19305            if (dpm != null) {
19306                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
19307                        /* callingUserOnly =*/ false);
19308                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
19309                        : deviceOwnerComponentName.getPackageName();
19310                // Does the package contains the device owner?
19311                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
19312                // this check is probably not needed, since DO should be registered as a device
19313                // admin on some user too. (Original bug for this: b/17657954)
19314                if (packageName.equals(deviceOwnerPackageName)) {
19315                    return true;
19316                }
19317                // Does it contain a device admin for any user?
19318                int[] users;
19319                if (userId == UserHandle.USER_ALL) {
19320                    users = sUserManager.getUserIds();
19321                } else {
19322                    users = new int[]{userId};
19323                }
19324                for (int i = 0; i < users.length; ++i) {
19325                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
19326                        return true;
19327                    }
19328                }
19329            }
19330        } catch (RemoteException e) {
19331        }
19332        return false;
19333    }
19334
19335    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
19336        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
19337    }
19338
19339    /**
19340     *  This method is an internal method that could be get invoked either
19341     *  to delete an installed package or to clean up a failed installation.
19342     *  After deleting an installed package, a broadcast is sent to notify any
19343     *  listeners that the package has been removed. For cleaning up a failed
19344     *  installation, the broadcast is not necessary since the package's
19345     *  installation wouldn't have sent the initial broadcast either
19346     *  The key steps in deleting a package are
19347     *  deleting the package information in internal structures like mPackages,
19348     *  deleting the packages base directories through installd
19349     *  updating mSettings to reflect current status
19350     *  persisting settings for later use
19351     *  sending a broadcast if necessary
19352     */
19353    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
19354        final PackageRemovedInfo info = new PackageRemovedInfo(this);
19355        final boolean res;
19356
19357        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
19358                ? UserHandle.USER_ALL : userId;
19359
19360        if (isPackageDeviceAdmin(packageName, removeUser)) {
19361            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
19362            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
19363        }
19364
19365        PackageSetting uninstalledPs = null;
19366        PackageParser.Package pkg = null;
19367
19368        // for the uninstall-updates case and restricted profiles, remember the per-
19369        // user handle installed state
19370        int[] allUsers;
19371        synchronized (mPackages) {
19372            uninstalledPs = mSettings.mPackages.get(packageName);
19373            if (uninstalledPs == null) {
19374                Slog.w(TAG, "Not removing non-existent package " + packageName);
19375                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19376            }
19377
19378            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
19379                    && uninstalledPs.versionCode != versionCode) {
19380                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
19381                        + uninstalledPs.versionCode + " != " + versionCode);
19382                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19383            }
19384
19385            // Static shared libs can be declared by any package, so let us not
19386            // allow removing a package if it provides a lib others depend on.
19387            pkg = mPackages.get(packageName);
19388
19389            allUsers = sUserManager.getUserIds();
19390
19391            if (pkg != null && pkg.staticSharedLibName != null) {
19392                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
19393                        pkg.staticSharedLibVersion);
19394                if (libEntry != null) {
19395                    for (int currUserId : allUsers) {
19396                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
19397                            continue;
19398                        }
19399                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
19400                                libEntry.info, 0, currUserId);
19401                        if (!ArrayUtils.isEmpty(libClientPackages)) {
19402                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
19403                                    + " hosting lib " + libEntry.info.getName() + " version "
19404                                    + libEntry.info.getVersion() + " used by " + libClientPackages
19405                                    + " for user " + currUserId);
19406                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
19407                        }
19408                    }
19409                }
19410            }
19411
19412            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
19413        }
19414
19415        final int freezeUser;
19416        if (isUpdatedSystemApp(uninstalledPs)
19417                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
19418            // We're downgrading a system app, which will apply to all users, so
19419            // freeze them all during the downgrade
19420            freezeUser = UserHandle.USER_ALL;
19421        } else {
19422            freezeUser = removeUser;
19423        }
19424
19425        synchronized (mInstallLock) {
19426            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
19427            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
19428                    deleteFlags, "deletePackageX")) {
19429                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
19430                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
19431            }
19432            synchronized (mPackages) {
19433                if (res) {
19434                    if (pkg != null) {
19435                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
19436                    }
19437                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
19438                    updateInstantAppInstallerLocked(packageName);
19439                }
19440            }
19441        }
19442
19443        if (res) {
19444            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
19445            info.sendPackageRemovedBroadcasts(killApp);
19446            info.sendSystemPackageUpdatedBroadcasts();
19447            info.sendSystemPackageAppearedBroadcasts();
19448        }
19449        // Force a gc here.
19450        Runtime.getRuntime().gc();
19451        // Delete the resources here after sending the broadcast to let
19452        // other processes clean up before deleting resources.
19453        if (info.args != null) {
19454            synchronized (mInstallLock) {
19455                info.args.doPostDeleteLI(true);
19456            }
19457        }
19458
19459        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19460    }
19461
19462    static class PackageRemovedInfo {
19463        final PackageSender packageSender;
19464        String removedPackage;
19465        String installerPackageName;
19466        int uid = -1;
19467        int removedAppId = -1;
19468        int[] origUsers;
19469        int[] removedUsers = null;
19470        int[] broadcastUsers = null;
19471        SparseArray<Integer> installReasons;
19472        boolean isRemovedPackageSystemUpdate = false;
19473        boolean isUpdate;
19474        boolean dataRemoved;
19475        boolean removedForAllUsers;
19476        boolean isStaticSharedLib;
19477        // Clean up resources deleted packages.
19478        InstallArgs args = null;
19479        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
19480        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
19481
19482        PackageRemovedInfo(PackageSender packageSender) {
19483            this.packageSender = packageSender;
19484        }
19485
19486        void sendPackageRemovedBroadcasts(boolean killApp) {
19487            sendPackageRemovedBroadcastInternal(killApp);
19488            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
19489            for (int i = 0; i < childCount; i++) {
19490                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19491                childInfo.sendPackageRemovedBroadcastInternal(killApp);
19492            }
19493        }
19494
19495        void sendSystemPackageUpdatedBroadcasts() {
19496            if (isRemovedPackageSystemUpdate) {
19497                sendSystemPackageUpdatedBroadcastsInternal();
19498                final int childCount = (removedChildPackages != null)
19499                        ? removedChildPackages.size() : 0;
19500                for (int i = 0; i < childCount; i++) {
19501                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19502                    if (childInfo.isRemovedPackageSystemUpdate) {
19503                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
19504                    }
19505                }
19506            }
19507        }
19508
19509        void sendSystemPackageAppearedBroadcasts() {
19510            final int packageCount = (appearedChildPackages != null)
19511                    ? appearedChildPackages.size() : 0;
19512            for (int i = 0; i < packageCount; i++) {
19513                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
19514                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
19515                    true /*sendBootCompleted*/, false /*startReceiver*/,
19516                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
19517            }
19518        }
19519
19520        private void sendSystemPackageUpdatedBroadcastsInternal() {
19521            Bundle extras = new Bundle(2);
19522            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
19523            extras.putBoolean(Intent.EXTRA_REPLACING, true);
19524            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19525                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19526            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19527                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19528            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
19529                null, null, 0, removedPackage, null, null);
19530            if (installerPackageName != null) {
19531                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19532                        removedPackage, extras, 0 /*flags*/,
19533                        installerPackageName, null, null);
19534                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19535                        removedPackage, extras, 0 /*flags*/,
19536                        installerPackageName, null, null);
19537            }
19538        }
19539
19540        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
19541            // Don't send static shared library removal broadcasts as these
19542            // libs are visible only the the apps that depend on them an one
19543            // cannot remove the library if it has a dependency.
19544            if (isStaticSharedLib) {
19545                return;
19546            }
19547            Bundle extras = new Bundle(2);
19548            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
19549            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
19550            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
19551            if (isUpdate || isRemovedPackageSystemUpdate) {
19552                extras.putBoolean(Intent.EXTRA_REPLACING, true);
19553            }
19554            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
19555            if (removedPackage != null) {
19556                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19557                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
19558                if (installerPackageName != null) {
19559                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19560                            removedPackage, extras, 0 /*flags*/,
19561                            installerPackageName, null, broadcastUsers);
19562                }
19563                if (dataRemoved && !isRemovedPackageSystemUpdate) {
19564                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
19565                        removedPackage, extras,
19566                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19567                        null, null, broadcastUsers);
19568                }
19569            }
19570            if (removedAppId >= 0) {
19571                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
19572                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19573                    null, null, broadcastUsers);
19574            }
19575        }
19576
19577        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
19578            removedUsers = userIds;
19579            if (removedUsers == null) {
19580                broadcastUsers = null;
19581                return;
19582            }
19583
19584            broadcastUsers = EMPTY_INT_ARRAY;
19585            for (int i = userIds.length - 1; i >= 0; --i) {
19586                final int userId = userIds[i];
19587                if (deletedPackageSetting.getInstantApp(userId)) {
19588                    continue;
19589                }
19590                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
19591            }
19592        }
19593    }
19594
19595    /*
19596     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
19597     * flag is not set, the data directory is removed as well.
19598     * make sure this flag is set for partially installed apps. If not its meaningless to
19599     * delete a partially installed application.
19600     */
19601    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
19602            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
19603        String packageName = ps.name;
19604        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
19605        // Retrieve object to delete permissions for shared user later on
19606        final PackageParser.Package deletedPkg;
19607        final PackageSetting deletedPs;
19608        // reader
19609        synchronized (mPackages) {
19610            deletedPkg = mPackages.get(packageName);
19611            deletedPs = mSettings.mPackages.get(packageName);
19612            if (outInfo != null) {
19613                outInfo.removedPackage = packageName;
19614                outInfo.installerPackageName = ps.installerPackageName;
19615                outInfo.isStaticSharedLib = deletedPkg != null
19616                        && deletedPkg.staticSharedLibName != null;
19617                outInfo.populateUsers(deletedPs == null ? null
19618                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
19619            }
19620        }
19621
19622        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
19623
19624        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
19625            final PackageParser.Package resolvedPkg;
19626            if (deletedPkg != null) {
19627                resolvedPkg = deletedPkg;
19628            } else {
19629                // We don't have a parsed package when it lives on an ejected
19630                // adopted storage device, so fake something together
19631                resolvedPkg = new PackageParser.Package(ps.name);
19632                resolvedPkg.setVolumeUuid(ps.volumeUuid);
19633            }
19634            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
19635                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19636            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
19637            if (outInfo != null) {
19638                outInfo.dataRemoved = true;
19639            }
19640            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
19641        }
19642
19643        int removedAppId = -1;
19644
19645        // writer
19646        synchronized (mPackages) {
19647            boolean installedStateChanged = false;
19648            if (deletedPs != null) {
19649                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
19650                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
19651                    clearDefaultBrowserIfNeeded(packageName);
19652                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
19653                    removedAppId = mSettings.removePackageLPw(packageName);
19654                    if (outInfo != null) {
19655                        outInfo.removedAppId = removedAppId;
19656                    }
19657                    updatePermissionsLPw(deletedPs.name, null, 0);
19658                    if (deletedPs.sharedUser != null) {
19659                        // Remove permissions associated with package. Since runtime
19660                        // permissions are per user we have to kill the removed package
19661                        // or packages running under the shared user of the removed
19662                        // package if revoking the permissions requested only by the removed
19663                        // package is successful and this causes a change in gids.
19664                        for (int userId : UserManagerService.getInstance().getUserIds()) {
19665                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19666                                    userId);
19667                            if (userIdToKill == UserHandle.USER_ALL
19668                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
19669                                // If gids changed for this user, kill all affected packages.
19670                                mHandler.post(new Runnable() {
19671                                    @Override
19672                                    public void run() {
19673                                        // This has to happen with no lock held.
19674                                        killApplication(deletedPs.name, deletedPs.appId,
19675                                                KILL_APP_REASON_GIDS_CHANGED);
19676                                    }
19677                                });
19678                                break;
19679                            }
19680                        }
19681                    }
19682                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19683                }
19684                // make sure to preserve per-user disabled state if this removal was just
19685                // a downgrade of a system app to the factory package
19686                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19687                    if (DEBUG_REMOVE) {
19688                        Slog.d(TAG, "Propagating install state across downgrade");
19689                    }
19690                    for (int userId : allUserHandles) {
19691                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19692                        if (DEBUG_REMOVE) {
19693                            Slog.d(TAG, "    user " + userId + " => " + installed);
19694                        }
19695                        if (installed != ps.getInstalled(userId)) {
19696                            installedStateChanged = true;
19697                        }
19698                        ps.setInstalled(installed, userId);
19699                    }
19700                }
19701            }
19702            // can downgrade to reader
19703            if (writeSettings) {
19704                // Save settings now
19705                mSettings.writeLPr();
19706            }
19707            if (installedStateChanged) {
19708                mSettings.writeKernelMappingLPr(ps);
19709            }
19710        }
19711        if (removedAppId != -1) {
19712            // A user ID was deleted here. Go through all users and remove it
19713            // from KeyStore.
19714            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19715        }
19716    }
19717
19718    static boolean locationIsPrivileged(File path) {
19719        try {
19720            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19721                    .getCanonicalPath();
19722            return path.getCanonicalPath().startsWith(privilegedAppDir);
19723        } catch (IOException e) {
19724            Slog.e(TAG, "Unable to access code path " + path);
19725        }
19726        return false;
19727    }
19728
19729    /*
19730     * Tries to delete system package.
19731     */
19732    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19733            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19734            boolean writeSettings) {
19735        if (deletedPs.parentPackageName != null) {
19736            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19737            return false;
19738        }
19739
19740        final boolean applyUserRestrictions
19741                = (allUserHandles != null) && (outInfo.origUsers != null);
19742        final PackageSetting disabledPs;
19743        // Confirm if the system package has been updated
19744        // An updated system app can be deleted. This will also have to restore
19745        // the system pkg from system partition
19746        // reader
19747        synchronized (mPackages) {
19748            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19749        }
19750
19751        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19752                + " disabledPs=" + disabledPs);
19753
19754        if (disabledPs == null) {
19755            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19756            return false;
19757        } else if (DEBUG_REMOVE) {
19758            Slog.d(TAG, "Deleting system pkg from data partition");
19759        }
19760
19761        if (DEBUG_REMOVE) {
19762            if (applyUserRestrictions) {
19763                Slog.d(TAG, "Remembering install states:");
19764                for (int userId : allUserHandles) {
19765                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19766                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
19767                }
19768            }
19769        }
19770
19771        // Delete the updated package
19772        outInfo.isRemovedPackageSystemUpdate = true;
19773        if (outInfo.removedChildPackages != null) {
19774            final int childCount = (deletedPs.childPackageNames != null)
19775                    ? deletedPs.childPackageNames.size() : 0;
19776            for (int i = 0; i < childCount; i++) {
19777                String childPackageName = deletedPs.childPackageNames.get(i);
19778                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19779                        .contains(childPackageName)) {
19780                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19781                            childPackageName);
19782                    if (childInfo != null) {
19783                        childInfo.isRemovedPackageSystemUpdate = true;
19784                    }
19785                }
19786            }
19787        }
19788
19789        if (disabledPs.versionCode < deletedPs.versionCode) {
19790            // Delete data for downgrades
19791            flags &= ~PackageManager.DELETE_KEEP_DATA;
19792        } else {
19793            // Preserve data by setting flag
19794            flags |= PackageManager.DELETE_KEEP_DATA;
19795        }
19796
19797        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19798                outInfo, writeSettings, disabledPs.pkg);
19799        if (!ret) {
19800            return false;
19801        }
19802
19803        // writer
19804        synchronized (mPackages) {
19805            // NOTE: The system package always needs to be enabled; even if it's for
19806            // a compressed stub. If we don't, installing the system package fails
19807            // during scan [scanning checks the disabled packages]. We will reverse
19808            // this later, after we've "installed" the stub.
19809            // Reinstate the old system package
19810            enableSystemPackageLPw(disabledPs.pkg);
19811            // Remove any native libraries from the upgraded package.
19812            removeNativeBinariesLI(deletedPs);
19813        }
19814
19815        // Install the system package
19816        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19817        try {
19818            installPackageFromSystemLIF(disabledPs.codePath, false /*isPrivileged*/, allUserHandles,
19819                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
19820        } catch (PackageManagerException e) {
19821            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19822                    + e.getMessage());
19823            return false;
19824        } finally {
19825            if (disabledPs.pkg.isStub) {
19826                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
19827            }
19828        }
19829        return true;
19830    }
19831
19832    /**
19833     * Installs a package that's already on the system partition.
19834     */
19835    private PackageParser.Package installPackageFromSystemLIF(@NonNull File codePath,
19836            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
19837            @Nullable PermissionsState origPermissionState, boolean writeSettings)
19838                    throws PackageManagerException {
19839        int parseFlags = mDefParseFlags
19840                | PackageParser.PARSE_MUST_BE_APK
19841                | PackageParser.PARSE_IS_SYSTEM
19842                | PackageParser.PARSE_IS_SYSTEM_DIR;
19843        if (isPrivileged || locationIsPrivileged(codePath)) {
19844            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19845        }
19846
19847        final PackageParser.Package newPkg =
19848                scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/, 0 /*currentTime*/, null);
19849
19850        try {
19851            // update shared libraries for the newly re-installed system package
19852            updateSharedLibrariesLPr(newPkg, null);
19853        } catch (PackageManagerException e) {
19854            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19855        }
19856
19857        prepareAppDataAfterInstallLIF(newPkg);
19858
19859        // writer
19860        synchronized (mPackages) {
19861            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19862
19863            // Propagate the permissions state as we do not want to drop on the floor
19864            // runtime permissions. The update permissions method below will take
19865            // care of removing obsolete permissions and grant install permissions.
19866            if (origPermissionState != null) {
19867                ps.getPermissionsState().copyFrom(origPermissionState);
19868            }
19869            updatePermissionsLPw(newPkg.packageName, newPkg,
19870                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19871
19872            final boolean applyUserRestrictions
19873                    = (allUserHandles != null) && (origUserHandles != null);
19874            if (applyUserRestrictions) {
19875                boolean installedStateChanged = false;
19876                if (DEBUG_REMOVE) {
19877                    Slog.d(TAG, "Propagating install state across reinstall");
19878                }
19879                for (int userId : allUserHandles) {
19880                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
19881                    if (DEBUG_REMOVE) {
19882                        Slog.d(TAG, "    user " + userId + " => " + installed);
19883                    }
19884                    if (installed != ps.getInstalled(userId)) {
19885                        installedStateChanged = true;
19886                    }
19887                    ps.setInstalled(installed, userId);
19888
19889                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19890                }
19891                // Regardless of writeSettings we need to ensure that this restriction
19892                // state propagation is persisted
19893                mSettings.writeAllUsersPackageRestrictionsLPr();
19894                if (installedStateChanged) {
19895                    mSettings.writeKernelMappingLPr(ps);
19896                }
19897            }
19898            // can downgrade to reader here
19899            if (writeSettings) {
19900                mSettings.writeLPr();
19901            }
19902        }
19903        return newPkg;
19904    }
19905
19906    private boolean deleteInstalledPackageLIF(PackageSetting ps,
19907            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19908            PackageRemovedInfo outInfo, boolean writeSettings,
19909            PackageParser.Package replacingPackage) {
19910        synchronized (mPackages) {
19911            if (outInfo != null) {
19912                outInfo.uid = ps.appId;
19913            }
19914
19915            if (outInfo != null && outInfo.removedChildPackages != null) {
19916                final int childCount = (ps.childPackageNames != null)
19917                        ? ps.childPackageNames.size() : 0;
19918                for (int i = 0; i < childCount; i++) {
19919                    String childPackageName = ps.childPackageNames.get(i);
19920                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
19921                    if (childPs == null) {
19922                        return false;
19923                    }
19924                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19925                            childPackageName);
19926                    if (childInfo != null) {
19927                        childInfo.uid = childPs.appId;
19928                    }
19929                }
19930            }
19931        }
19932
19933        // Delete package data from internal structures and also remove data if flag is set
19934        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
19935
19936        // Delete the child packages data
19937        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
19938        for (int i = 0; i < childCount; i++) {
19939            PackageSetting childPs;
19940            synchronized (mPackages) {
19941                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
19942            }
19943            if (childPs != null) {
19944                PackageRemovedInfo childOutInfo = (outInfo != null
19945                        && outInfo.removedChildPackages != null)
19946                        ? outInfo.removedChildPackages.get(childPs.name) : null;
19947                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
19948                        && (replacingPackage != null
19949                        && !replacingPackage.hasChildPackage(childPs.name))
19950                        ? flags & ~DELETE_KEEP_DATA : flags;
19951                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
19952                        deleteFlags, writeSettings);
19953            }
19954        }
19955
19956        // Delete application code and resources only for parent packages
19957        if (ps.parentPackageName == null) {
19958            if (deleteCodeAndResources && (outInfo != null)) {
19959                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
19960                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
19961                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
19962            }
19963        }
19964
19965        return true;
19966    }
19967
19968    @Override
19969    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
19970            int userId) {
19971        mContext.enforceCallingOrSelfPermission(
19972                android.Manifest.permission.DELETE_PACKAGES, null);
19973        synchronized (mPackages) {
19974            // Cannot block uninstall of static shared libs as they are
19975            // considered a part of the using app (emulating static linking).
19976            // Also static libs are installed always on internal storage.
19977            PackageParser.Package pkg = mPackages.get(packageName);
19978            if (pkg != null && pkg.staticSharedLibName != null) {
19979                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
19980                        + " providing static shared library: " + pkg.staticSharedLibName);
19981                return false;
19982            }
19983            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
19984            mSettings.writePackageRestrictionsLPr(userId);
19985        }
19986        return true;
19987    }
19988
19989    @Override
19990    public boolean getBlockUninstallForUser(String packageName, int userId) {
19991        synchronized (mPackages) {
19992            final PackageSetting ps = mSettings.mPackages.get(packageName);
19993            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
19994                return false;
19995            }
19996            return mSettings.getBlockUninstallLPr(userId, packageName);
19997        }
19998    }
19999
20000    @Override
20001    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
20002        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
20003        synchronized (mPackages) {
20004            PackageSetting ps = mSettings.mPackages.get(packageName);
20005            if (ps == null) {
20006                Log.w(TAG, "Package doesn't exist: " + packageName);
20007                return false;
20008            }
20009            if (systemUserApp) {
20010                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
20011            } else {
20012                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
20013            }
20014            mSettings.writeLPr();
20015        }
20016        return true;
20017    }
20018
20019    /*
20020     * This method handles package deletion in general
20021     */
20022    private boolean deletePackageLIF(String packageName, UserHandle user,
20023            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
20024            PackageRemovedInfo outInfo, boolean writeSettings,
20025            PackageParser.Package replacingPackage) {
20026        if (packageName == null) {
20027            Slog.w(TAG, "Attempt to delete null packageName.");
20028            return false;
20029        }
20030
20031        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
20032
20033        PackageSetting ps;
20034        synchronized (mPackages) {
20035            ps = mSettings.mPackages.get(packageName);
20036            if (ps == null) {
20037                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
20038                return false;
20039            }
20040
20041            if (ps.parentPackageName != null && (!isSystemApp(ps)
20042                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
20043                if (DEBUG_REMOVE) {
20044                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
20045                            + ((user == null) ? UserHandle.USER_ALL : user));
20046                }
20047                final int removedUserId = (user != null) ? user.getIdentifier()
20048                        : UserHandle.USER_ALL;
20049                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
20050                    return false;
20051                }
20052                markPackageUninstalledForUserLPw(ps, user);
20053                scheduleWritePackageRestrictionsLocked(user);
20054                return true;
20055            }
20056        }
20057
20058        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
20059                && user.getIdentifier() != UserHandle.USER_ALL)) {
20060            // The caller is asking that the package only be deleted for a single
20061            // user.  To do this, we just mark its uninstalled state and delete
20062            // its data. If this is a system app, we only allow this to happen if
20063            // they have set the special DELETE_SYSTEM_APP which requests different
20064            // semantics than normal for uninstalling system apps.
20065            markPackageUninstalledForUserLPw(ps, user);
20066
20067            if (!isSystemApp(ps)) {
20068                // Do not uninstall the APK if an app should be cached
20069                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
20070                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
20071                    // Other user still have this package installed, so all
20072                    // we need to do is clear this user's data and save that
20073                    // it is uninstalled.
20074                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
20075                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
20076                        return false;
20077                    }
20078                    scheduleWritePackageRestrictionsLocked(user);
20079                    return true;
20080                } else {
20081                    // We need to set it back to 'installed' so the uninstall
20082                    // broadcasts will be sent correctly.
20083                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
20084                    ps.setInstalled(true, user.getIdentifier());
20085                    mSettings.writeKernelMappingLPr(ps);
20086                }
20087            } else {
20088                // This is a system app, so we assume that the
20089                // other users still have this package installed, so all
20090                // we need to do is clear this user's data and save that
20091                // it is uninstalled.
20092                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
20093                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
20094                    return false;
20095                }
20096                scheduleWritePackageRestrictionsLocked(user);
20097                return true;
20098            }
20099        }
20100
20101        // If we are deleting a composite package for all users, keep track
20102        // of result for each child.
20103        if (ps.childPackageNames != null && outInfo != null) {
20104            synchronized (mPackages) {
20105                final int childCount = ps.childPackageNames.size();
20106                outInfo.removedChildPackages = new ArrayMap<>(childCount);
20107                for (int i = 0; i < childCount; i++) {
20108                    String childPackageName = ps.childPackageNames.get(i);
20109                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
20110                    childInfo.removedPackage = childPackageName;
20111                    childInfo.installerPackageName = ps.installerPackageName;
20112                    outInfo.removedChildPackages.put(childPackageName, childInfo);
20113                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
20114                    if (childPs != null) {
20115                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
20116                    }
20117                }
20118            }
20119        }
20120
20121        boolean ret = false;
20122        if (isSystemApp(ps)) {
20123            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
20124            // When an updated system application is deleted we delete the existing resources
20125            // as well and fall back to existing code in system partition
20126            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
20127        } else {
20128            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
20129            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
20130                    outInfo, writeSettings, replacingPackage);
20131        }
20132
20133        // Take a note whether we deleted the package for all users
20134        if (outInfo != null) {
20135            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
20136            if (outInfo.removedChildPackages != null) {
20137                synchronized (mPackages) {
20138                    final int childCount = outInfo.removedChildPackages.size();
20139                    for (int i = 0; i < childCount; i++) {
20140                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
20141                        if (childInfo != null) {
20142                            childInfo.removedForAllUsers = mPackages.get(
20143                                    childInfo.removedPackage) == null;
20144                        }
20145                    }
20146                }
20147            }
20148            // If we uninstalled an update to a system app there may be some
20149            // child packages that appeared as they are declared in the system
20150            // app but were not declared in the update.
20151            if (isSystemApp(ps)) {
20152                synchronized (mPackages) {
20153                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
20154                    final int childCount = (updatedPs.childPackageNames != null)
20155                            ? updatedPs.childPackageNames.size() : 0;
20156                    for (int i = 0; i < childCount; i++) {
20157                        String childPackageName = updatedPs.childPackageNames.get(i);
20158                        if (outInfo.removedChildPackages == null
20159                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
20160                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
20161                            if (childPs == null) {
20162                                continue;
20163                            }
20164                            PackageInstalledInfo installRes = new PackageInstalledInfo();
20165                            installRes.name = childPackageName;
20166                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
20167                            installRes.pkg = mPackages.get(childPackageName);
20168                            installRes.uid = childPs.pkg.applicationInfo.uid;
20169                            if (outInfo.appearedChildPackages == null) {
20170                                outInfo.appearedChildPackages = new ArrayMap<>();
20171                            }
20172                            outInfo.appearedChildPackages.put(childPackageName, installRes);
20173                        }
20174                    }
20175                }
20176            }
20177        }
20178
20179        return ret;
20180    }
20181
20182    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
20183        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
20184                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
20185        for (int nextUserId : userIds) {
20186            if (DEBUG_REMOVE) {
20187                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
20188            }
20189            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
20190                    false /*installed*/,
20191                    true /*stopped*/,
20192                    true /*notLaunched*/,
20193                    false /*hidden*/,
20194                    false /*suspended*/,
20195                    false /*instantApp*/,
20196                    false /*virtualPreload*/,
20197                    null /*lastDisableAppCaller*/,
20198                    null /*enabledComponents*/,
20199                    null /*disabledComponents*/,
20200                    ps.readUserState(nextUserId).domainVerificationStatus,
20201                    0, PackageManager.INSTALL_REASON_UNKNOWN);
20202        }
20203        mSettings.writeKernelMappingLPr(ps);
20204    }
20205
20206    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
20207            PackageRemovedInfo outInfo) {
20208        final PackageParser.Package pkg;
20209        synchronized (mPackages) {
20210            pkg = mPackages.get(ps.name);
20211        }
20212
20213        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
20214                : new int[] {userId};
20215        for (int nextUserId : userIds) {
20216            if (DEBUG_REMOVE) {
20217                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
20218                        + nextUserId);
20219            }
20220
20221            destroyAppDataLIF(pkg, userId,
20222                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20223            destroyAppProfilesLIF(pkg, userId);
20224            clearDefaultBrowserIfNeededForUser(ps.name, userId);
20225            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
20226            schedulePackageCleaning(ps.name, nextUserId, false);
20227            synchronized (mPackages) {
20228                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
20229                    scheduleWritePackageRestrictionsLocked(nextUserId);
20230                }
20231                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
20232            }
20233        }
20234
20235        if (outInfo != null) {
20236            outInfo.removedPackage = ps.name;
20237            outInfo.installerPackageName = ps.installerPackageName;
20238            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
20239            outInfo.removedAppId = ps.appId;
20240            outInfo.removedUsers = userIds;
20241            outInfo.broadcastUsers = userIds;
20242        }
20243
20244        return true;
20245    }
20246
20247    private final class ClearStorageConnection implements ServiceConnection {
20248        IMediaContainerService mContainerService;
20249
20250        @Override
20251        public void onServiceConnected(ComponentName name, IBinder service) {
20252            synchronized (this) {
20253                mContainerService = IMediaContainerService.Stub
20254                        .asInterface(Binder.allowBlocking(service));
20255                notifyAll();
20256            }
20257        }
20258
20259        @Override
20260        public void onServiceDisconnected(ComponentName name) {
20261        }
20262    }
20263
20264    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
20265        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
20266
20267        final boolean mounted;
20268        if (Environment.isExternalStorageEmulated()) {
20269            mounted = true;
20270        } else {
20271            final String status = Environment.getExternalStorageState();
20272
20273            mounted = status.equals(Environment.MEDIA_MOUNTED)
20274                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
20275        }
20276
20277        if (!mounted) {
20278            return;
20279        }
20280
20281        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
20282        int[] users;
20283        if (userId == UserHandle.USER_ALL) {
20284            users = sUserManager.getUserIds();
20285        } else {
20286            users = new int[] { userId };
20287        }
20288        final ClearStorageConnection conn = new ClearStorageConnection();
20289        if (mContext.bindServiceAsUser(
20290                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
20291            try {
20292                for (int curUser : users) {
20293                    long timeout = SystemClock.uptimeMillis() + 5000;
20294                    synchronized (conn) {
20295                        long now;
20296                        while (conn.mContainerService == null &&
20297                                (now = SystemClock.uptimeMillis()) < timeout) {
20298                            try {
20299                                conn.wait(timeout - now);
20300                            } catch (InterruptedException e) {
20301                            }
20302                        }
20303                    }
20304                    if (conn.mContainerService == null) {
20305                        return;
20306                    }
20307
20308                    final UserEnvironment userEnv = new UserEnvironment(curUser);
20309                    clearDirectory(conn.mContainerService,
20310                            userEnv.buildExternalStorageAppCacheDirs(packageName));
20311                    if (allData) {
20312                        clearDirectory(conn.mContainerService,
20313                                userEnv.buildExternalStorageAppDataDirs(packageName));
20314                        clearDirectory(conn.mContainerService,
20315                                userEnv.buildExternalStorageAppMediaDirs(packageName));
20316                    }
20317                }
20318            } finally {
20319                mContext.unbindService(conn);
20320            }
20321        }
20322    }
20323
20324    @Override
20325    public void clearApplicationProfileData(String packageName) {
20326        enforceSystemOrRoot("Only the system can clear all profile data");
20327
20328        final PackageParser.Package pkg;
20329        synchronized (mPackages) {
20330            pkg = mPackages.get(packageName);
20331        }
20332
20333        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
20334            synchronized (mInstallLock) {
20335                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
20336            }
20337        }
20338    }
20339
20340    @Override
20341    public void clearApplicationUserData(final String packageName,
20342            final IPackageDataObserver observer, final int userId) {
20343        mContext.enforceCallingOrSelfPermission(
20344                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
20345
20346        final int callingUid = Binder.getCallingUid();
20347        enforceCrossUserPermission(callingUid, userId,
20348                true /* requireFullPermission */, false /* checkShell */, "clear application data");
20349
20350        final PackageSetting ps = mSettings.getPackageLPr(packageName);
20351        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
20352        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
20353            throw new SecurityException("Cannot clear data for a protected package: "
20354                    + packageName);
20355        }
20356        // Queue up an async operation since the package deletion may take a little while.
20357        mHandler.post(new Runnable() {
20358            public void run() {
20359                mHandler.removeCallbacks(this);
20360                final boolean succeeded;
20361                if (!filterApp) {
20362                    try (PackageFreezer freezer = freezePackage(packageName,
20363                            "clearApplicationUserData")) {
20364                        synchronized (mInstallLock) {
20365                            succeeded = clearApplicationUserDataLIF(packageName, userId);
20366                        }
20367                        clearExternalStorageDataSync(packageName, userId, true);
20368                        synchronized (mPackages) {
20369                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
20370                                    packageName, userId);
20371                        }
20372                    }
20373                    if (succeeded) {
20374                        // invoke DeviceStorageMonitor's update method to clear any notifications
20375                        DeviceStorageMonitorInternal dsm = LocalServices
20376                                .getService(DeviceStorageMonitorInternal.class);
20377                        if (dsm != null) {
20378                            dsm.checkMemory();
20379                        }
20380                    }
20381                } else {
20382                    succeeded = false;
20383                }
20384                if (observer != null) {
20385                    try {
20386                        observer.onRemoveCompleted(packageName, succeeded);
20387                    } catch (RemoteException e) {
20388                        Log.i(TAG, "Observer no longer exists.");
20389                    }
20390                } //end if observer
20391            } //end run
20392        });
20393    }
20394
20395    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
20396        if (packageName == null) {
20397            Slog.w(TAG, "Attempt to delete null packageName.");
20398            return false;
20399        }
20400
20401        // Try finding details about the requested package
20402        PackageParser.Package pkg;
20403        synchronized (mPackages) {
20404            pkg = mPackages.get(packageName);
20405            if (pkg == null) {
20406                final PackageSetting ps = mSettings.mPackages.get(packageName);
20407                if (ps != null) {
20408                    pkg = ps.pkg;
20409                }
20410            }
20411
20412            if (pkg == null) {
20413                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
20414                return false;
20415            }
20416
20417            PackageSetting ps = (PackageSetting) pkg.mExtras;
20418            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
20419        }
20420
20421        clearAppDataLIF(pkg, userId,
20422                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20423
20424        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20425        removeKeystoreDataIfNeeded(userId, appId);
20426
20427        UserManagerInternal umInternal = getUserManagerInternal();
20428        final int flags;
20429        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
20430            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
20431        } else if (umInternal.isUserRunning(userId)) {
20432            flags = StorageManager.FLAG_STORAGE_DE;
20433        } else {
20434            flags = 0;
20435        }
20436        prepareAppDataContentsLIF(pkg, userId, flags);
20437
20438        return true;
20439    }
20440
20441    /**
20442     * Reverts user permission state changes (permissions and flags) in
20443     * all packages for a given user.
20444     *
20445     * @param userId The device user for which to do a reset.
20446     */
20447    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
20448        final int packageCount = mPackages.size();
20449        for (int i = 0; i < packageCount; i++) {
20450            PackageParser.Package pkg = mPackages.valueAt(i);
20451            PackageSetting ps = (PackageSetting) pkg.mExtras;
20452            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
20453        }
20454    }
20455
20456    private void resetNetworkPolicies(int userId) {
20457        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
20458    }
20459
20460    /**
20461     * Reverts user permission state changes (permissions and flags).
20462     *
20463     * @param ps The package for which to reset.
20464     * @param userId The device user for which to do a reset.
20465     */
20466    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
20467            final PackageSetting ps, final int userId) {
20468        if (ps.pkg == null) {
20469            return;
20470        }
20471
20472        // These are flags that can change base on user actions.
20473        final int userSettableMask = FLAG_PERMISSION_USER_SET
20474                | FLAG_PERMISSION_USER_FIXED
20475                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
20476                | FLAG_PERMISSION_REVIEW_REQUIRED;
20477
20478        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
20479                | FLAG_PERMISSION_POLICY_FIXED;
20480
20481        boolean writeInstallPermissions = false;
20482        boolean writeRuntimePermissions = false;
20483
20484        final int permissionCount = ps.pkg.requestedPermissions.size();
20485        for (int i = 0; i < permissionCount; i++) {
20486            String permission = ps.pkg.requestedPermissions.get(i);
20487
20488            BasePermission bp = mSettings.mPermissions.get(permission);
20489            if (bp == null) {
20490                continue;
20491            }
20492
20493            // If shared user we just reset the state to which only this app contributed.
20494            if (ps.sharedUser != null) {
20495                boolean used = false;
20496                final int packageCount = ps.sharedUser.packages.size();
20497                for (int j = 0; j < packageCount; j++) {
20498                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
20499                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
20500                            && pkg.pkg.requestedPermissions.contains(permission)) {
20501                        used = true;
20502                        break;
20503                    }
20504                }
20505                if (used) {
20506                    continue;
20507                }
20508            }
20509
20510            PermissionsState permissionsState = ps.getPermissionsState();
20511
20512            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
20513
20514            // Always clear the user settable flags.
20515            final boolean hasInstallState = permissionsState.getInstallPermissionState(
20516                    bp.name) != null;
20517            // If permission review is enabled and this is a legacy app, mark the
20518            // permission as requiring a review as this is the initial state.
20519            int flags = 0;
20520            if (mPermissionReviewRequired
20521                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
20522                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
20523            }
20524            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
20525                if (hasInstallState) {
20526                    writeInstallPermissions = true;
20527                } else {
20528                    writeRuntimePermissions = true;
20529                }
20530            }
20531
20532            // Below is only runtime permission handling.
20533            if (!bp.isRuntime()) {
20534                continue;
20535            }
20536
20537            // Never clobber system or policy.
20538            if ((oldFlags & policyOrSystemFlags) != 0) {
20539                continue;
20540            }
20541
20542            // If this permission was granted by default, make sure it is.
20543            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
20544                if (permissionsState.grantRuntimePermission(bp, userId)
20545                        != PERMISSION_OPERATION_FAILURE) {
20546                    writeRuntimePermissions = true;
20547                }
20548            // If permission review is enabled the permissions for a legacy apps
20549            // are represented as constantly granted runtime ones, so don't revoke.
20550            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
20551                // Otherwise, reset the permission.
20552                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
20553                switch (revokeResult) {
20554                    case PERMISSION_OPERATION_SUCCESS:
20555                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
20556                        writeRuntimePermissions = true;
20557                        final int appId = ps.appId;
20558                        mHandler.post(new Runnable() {
20559                            @Override
20560                            public void run() {
20561                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
20562                            }
20563                        });
20564                    } break;
20565                }
20566            }
20567        }
20568
20569        // Synchronously write as we are taking permissions away.
20570        if (writeRuntimePermissions) {
20571            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
20572        }
20573
20574        // Synchronously write as we are taking permissions away.
20575        if (writeInstallPermissions) {
20576            mSettings.writeLPr();
20577        }
20578    }
20579
20580    /**
20581     * Remove entries from the keystore daemon. Will only remove it if the
20582     * {@code appId} is valid.
20583     */
20584    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
20585        if (appId < 0) {
20586            return;
20587        }
20588
20589        final KeyStore keyStore = KeyStore.getInstance();
20590        if (keyStore != null) {
20591            if (userId == UserHandle.USER_ALL) {
20592                for (final int individual : sUserManager.getUserIds()) {
20593                    keyStore.clearUid(UserHandle.getUid(individual, appId));
20594                }
20595            } else {
20596                keyStore.clearUid(UserHandle.getUid(userId, appId));
20597            }
20598        } else {
20599            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
20600        }
20601    }
20602
20603    @Override
20604    public void deleteApplicationCacheFiles(final String packageName,
20605            final IPackageDataObserver observer) {
20606        final int userId = UserHandle.getCallingUserId();
20607        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
20608    }
20609
20610    @Override
20611    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
20612            final IPackageDataObserver observer) {
20613        final int callingUid = Binder.getCallingUid();
20614        mContext.enforceCallingOrSelfPermission(
20615                android.Manifest.permission.DELETE_CACHE_FILES, null);
20616        enforceCrossUserPermission(callingUid, userId,
20617                /* requireFullPermission= */ true, /* checkShell= */ false,
20618                "delete application cache files");
20619        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
20620                android.Manifest.permission.ACCESS_INSTANT_APPS);
20621
20622        final PackageParser.Package pkg;
20623        synchronized (mPackages) {
20624            pkg = mPackages.get(packageName);
20625        }
20626
20627        // Queue up an async operation since the package deletion may take a little while.
20628        mHandler.post(new Runnable() {
20629            public void run() {
20630                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
20631                boolean doClearData = true;
20632                if (ps != null) {
20633                    final boolean targetIsInstantApp =
20634                            ps.getInstantApp(UserHandle.getUserId(callingUid));
20635                    doClearData = !targetIsInstantApp
20636                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
20637                }
20638                if (doClearData) {
20639                    synchronized (mInstallLock) {
20640                        final int flags = StorageManager.FLAG_STORAGE_DE
20641                                | StorageManager.FLAG_STORAGE_CE;
20642                        // We're only clearing cache files, so we don't care if the
20643                        // app is unfrozen and still able to run
20644                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
20645                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20646                    }
20647                    clearExternalStorageDataSync(packageName, userId, false);
20648                }
20649                if (observer != null) {
20650                    try {
20651                        observer.onRemoveCompleted(packageName, true);
20652                    } catch (RemoteException e) {
20653                        Log.i(TAG, "Observer no longer exists.");
20654                    }
20655                }
20656            }
20657        });
20658    }
20659
20660    @Override
20661    public void getPackageSizeInfo(final String packageName, int userHandle,
20662            final IPackageStatsObserver observer) {
20663        throw new UnsupportedOperationException(
20664                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
20665    }
20666
20667    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
20668        final PackageSetting ps;
20669        synchronized (mPackages) {
20670            ps = mSettings.mPackages.get(packageName);
20671            if (ps == null) {
20672                Slog.w(TAG, "Failed to find settings for " + packageName);
20673                return false;
20674            }
20675        }
20676
20677        final String[] packageNames = { packageName };
20678        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
20679        final String[] codePaths = { ps.codePathString };
20680
20681        try {
20682            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20683                    ps.appId, ceDataInodes, codePaths, stats);
20684
20685            // For now, ignore code size of packages on system partition
20686            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20687                stats.codeSize = 0;
20688            }
20689
20690            // External clients expect these to be tracked separately
20691            stats.dataSize -= stats.cacheSize;
20692
20693        } catch (InstallerException e) {
20694            Slog.w(TAG, String.valueOf(e));
20695            return false;
20696        }
20697
20698        return true;
20699    }
20700
20701    private int getUidTargetSdkVersionLockedLPr(int uid) {
20702        Object obj = mSettings.getUserIdLPr(uid);
20703        if (obj instanceof SharedUserSetting) {
20704            final SharedUserSetting sus = (SharedUserSetting) obj;
20705            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20706            final Iterator<PackageSetting> it = sus.packages.iterator();
20707            while (it.hasNext()) {
20708                final PackageSetting ps = it.next();
20709                if (ps.pkg != null) {
20710                    int v = ps.pkg.applicationInfo.targetSdkVersion;
20711                    if (v < vers) vers = v;
20712                }
20713            }
20714            return vers;
20715        } else if (obj instanceof PackageSetting) {
20716            final PackageSetting ps = (PackageSetting) obj;
20717            if (ps.pkg != null) {
20718                return ps.pkg.applicationInfo.targetSdkVersion;
20719            }
20720        }
20721        return Build.VERSION_CODES.CUR_DEVELOPMENT;
20722    }
20723
20724    @Override
20725    public void addPreferredActivity(IntentFilter filter, int match,
20726            ComponentName[] set, ComponentName activity, int userId) {
20727        addPreferredActivityInternal(filter, match, set, activity, true, userId,
20728                "Adding preferred");
20729    }
20730
20731    private void addPreferredActivityInternal(IntentFilter filter, int match,
20732            ComponentName[] set, ComponentName activity, boolean always, int userId,
20733            String opname) {
20734        // writer
20735        int callingUid = Binder.getCallingUid();
20736        enforceCrossUserPermission(callingUid, userId,
20737                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20738        if (filter.countActions() == 0) {
20739            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20740            return;
20741        }
20742        synchronized (mPackages) {
20743            if (mContext.checkCallingOrSelfPermission(
20744                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20745                    != PackageManager.PERMISSION_GRANTED) {
20746                if (getUidTargetSdkVersionLockedLPr(callingUid)
20747                        < Build.VERSION_CODES.FROYO) {
20748                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20749                            + callingUid);
20750                    return;
20751                }
20752                mContext.enforceCallingOrSelfPermission(
20753                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20754            }
20755
20756            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20757            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20758                    + userId + ":");
20759            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20760            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20761            scheduleWritePackageRestrictionsLocked(userId);
20762            postPreferredActivityChangedBroadcast(userId);
20763        }
20764    }
20765
20766    private void postPreferredActivityChangedBroadcast(int userId) {
20767        mHandler.post(() -> {
20768            final IActivityManager am = ActivityManager.getService();
20769            if (am == null) {
20770                return;
20771            }
20772
20773            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20774            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20775            try {
20776                am.broadcastIntent(null, intent, null, null,
20777                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
20778                        null, false, false, userId);
20779            } catch (RemoteException e) {
20780            }
20781        });
20782    }
20783
20784    @Override
20785    public void replacePreferredActivity(IntentFilter filter, int match,
20786            ComponentName[] set, ComponentName activity, int userId) {
20787        if (filter.countActions() != 1) {
20788            throw new IllegalArgumentException(
20789                    "replacePreferredActivity expects filter to have only 1 action.");
20790        }
20791        if (filter.countDataAuthorities() != 0
20792                || filter.countDataPaths() != 0
20793                || filter.countDataSchemes() > 1
20794                || filter.countDataTypes() != 0) {
20795            throw new IllegalArgumentException(
20796                    "replacePreferredActivity expects filter to have no data authorities, " +
20797                    "paths, or types; and at most one scheme.");
20798        }
20799
20800        final int callingUid = Binder.getCallingUid();
20801        enforceCrossUserPermission(callingUid, userId,
20802                true /* requireFullPermission */, false /* checkShell */,
20803                "replace preferred activity");
20804        synchronized (mPackages) {
20805            if (mContext.checkCallingOrSelfPermission(
20806                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20807                    != PackageManager.PERMISSION_GRANTED) {
20808                if (getUidTargetSdkVersionLockedLPr(callingUid)
20809                        < Build.VERSION_CODES.FROYO) {
20810                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20811                            + Binder.getCallingUid());
20812                    return;
20813                }
20814                mContext.enforceCallingOrSelfPermission(
20815                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20816            }
20817
20818            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20819            if (pir != null) {
20820                // Get all of the existing entries that exactly match this filter.
20821                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20822                if (existing != null && existing.size() == 1) {
20823                    PreferredActivity cur = existing.get(0);
20824                    if (DEBUG_PREFERRED) {
20825                        Slog.i(TAG, "Checking replace of preferred:");
20826                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20827                        if (!cur.mPref.mAlways) {
20828                            Slog.i(TAG, "  -- CUR; not mAlways!");
20829                        } else {
20830                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
20831                            Slog.i(TAG, "  -- CUR: mSet="
20832                                    + Arrays.toString(cur.mPref.mSetComponents));
20833                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
20834                            Slog.i(TAG, "  -- NEW: mMatch="
20835                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
20836                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
20837                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
20838                        }
20839                    }
20840                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20841                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20842                            && cur.mPref.sameSet(set)) {
20843                        // Setting the preferred activity to what it happens to be already
20844                        if (DEBUG_PREFERRED) {
20845                            Slog.i(TAG, "Replacing with same preferred activity "
20846                                    + cur.mPref.mShortComponent + " for user "
20847                                    + userId + ":");
20848                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20849                        }
20850                        return;
20851                    }
20852                }
20853
20854                if (existing != null) {
20855                    if (DEBUG_PREFERRED) {
20856                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
20857                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20858                    }
20859                    for (int i = 0; i < existing.size(); i++) {
20860                        PreferredActivity pa = existing.get(i);
20861                        if (DEBUG_PREFERRED) {
20862                            Slog.i(TAG, "Removing existing preferred activity "
20863                                    + pa.mPref.mComponent + ":");
20864                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
20865                        }
20866                        pir.removeFilter(pa);
20867                    }
20868                }
20869            }
20870            addPreferredActivityInternal(filter, match, set, activity, true, userId,
20871                    "Replacing preferred");
20872        }
20873    }
20874
20875    @Override
20876    public void clearPackagePreferredActivities(String packageName) {
20877        final int callingUid = Binder.getCallingUid();
20878        if (getInstantAppPackageName(callingUid) != null) {
20879            return;
20880        }
20881        // writer
20882        synchronized (mPackages) {
20883            PackageParser.Package pkg = mPackages.get(packageName);
20884            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20885                if (mContext.checkCallingOrSelfPermission(
20886                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20887                        != PackageManager.PERMISSION_GRANTED) {
20888                    if (getUidTargetSdkVersionLockedLPr(callingUid)
20889                            < Build.VERSION_CODES.FROYO) {
20890                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20891                                + callingUid);
20892                        return;
20893                    }
20894                    mContext.enforceCallingOrSelfPermission(
20895                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20896                }
20897            }
20898            final PackageSetting ps = mSettings.getPackageLPr(packageName);
20899            if (ps != null
20900                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20901                return;
20902            }
20903            int user = UserHandle.getCallingUserId();
20904            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20905                scheduleWritePackageRestrictionsLocked(user);
20906            }
20907        }
20908    }
20909
20910    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20911    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
20912        ArrayList<PreferredActivity> removed = null;
20913        boolean changed = false;
20914        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20915            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
20916            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20917            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
20918                continue;
20919            }
20920            Iterator<PreferredActivity> it = pir.filterIterator();
20921            while (it.hasNext()) {
20922                PreferredActivity pa = it.next();
20923                // Mark entry for removal only if it matches the package name
20924                // and the entry is of type "always".
20925                if (packageName == null ||
20926                        (pa.mPref.mComponent.getPackageName().equals(packageName)
20927                                && pa.mPref.mAlways)) {
20928                    if (removed == null) {
20929                        removed = new ArrayList<PreferredActivity>();
20930                    }
20931                    removed.add(pa);
20932                }
20933            }
20934            if (removed != null) {
20935                for (int j=0; j<removed.size(); j++) {
20936                    PreferredActivity pa = removed.get(j);
20937                    pir.removeFilter(pa);
20938                }
20939                changed = true;
20940            }
20941        }
20942        if (changed) {
20943            postPreferredActivityChangedBroadcast(userId);
20944        }
20945        return changed;
20946    }
20947
20948    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20949    private void clearIntentFilterVerificationsLPw(int userId) {
20950        final int packageCount = mPackages.size();
20951        for (int i = 0; i < packageCount; i++) {
20952            PackageParser.Package pkg = mPackages.valueAt(i);
20953            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
20954        }
20955    }
20956
20957    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20958    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
20959        if (userId == UserHandle.USER_ALL) {
20960            if (mSettings.removeIntentFilterVerificationLPw(packageName,
20961                    sUserManager.getUserIds())) {
20962                for (int oneUserId : sUserManager.getUserIds()) {
20963                    scheduleWritePackageRestrictionsLocked(oneUserId);
20964                }
20965            }
20966        } else {
20967            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
20968                scheduleWritePackageRestrictionsLocked(userId);
20969            }
20970        }
20971    }
20972
20973    /** Clears state for all users, and touches intent filter verification policy */
20974    void clearDefaultBrowserIfNeeded(String packageName) {
20975        for (int oneUserId : sUserManager.getUserIds()) {
20976            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
20977        }
20978    }
20979
20980    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
20981        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
20982        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
20983            if (packageName.equals(defaultBrowserPackageName)) {
20984                setDefaultBrowserPackageName(null, userId);
20985            }
20986        }
20987    }
20988
20989    @Override
20990    public void resetApplicationPreferences(int userId) {
20991        mContext.enforceCallingOrSelfPermission(
20992                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20993        final long identity = Binder.clearCallingIdentity();
20994        // writer
20995        try {
20996            synchronized (mPackages) {
20997                clearPackagePreferredActivitiesLPw(null, userId);
20998                mSettings.applyDefaultPreferredAppsLPw(this, userId);
20999                // TODO: We have to reset the default SMS and Phone. This requires
21000                // significant refactoring to keep all default apps in the package
21001                // manager (cleaner but more work) or have the services provide
21002                // callbacks to the package manager to request a default app reset.
21003                applyFactoryDefaultBrowserLPw(userId);
21004                clearIntentFilterVerificationsLPw(userId);
21005                primeDomainVerificationsLPw(userId);
21006                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
21007                scheduleWritePackageRestrictionsLocked(userId);
21008            }
21009            resetNetworkPolicies(userId);
21010        } finally {
21011            Binder.restoreCallingIdentity(identity);
21012        }
21013    }
21014
21015    @Override
21016    public int getPreferredActivities(List<IntentFilter> outFilters,
21017            List<ComponentName> outActivities, String packageName) {
21018        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21019            return 0;
21020        }
21021        int num = 0;
21022        final int userId = UserHandle.getCallingUserId();
21023        // reader
21024        synchronized (mPackages) {
21025            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
21026            if (pir != null) {
21027                final Iterator<PreferredActivity> it = pir.filterIterator();
21028                while (it.hasNext()) {
21029                    final PreferredActivity pa = it.next();
21030                    if (packageName == null
21031                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
21032                                    && pa.mPref.mAlways)) {
21033                        if (outFilters != null) {
21034                            outFilters.add(new IntentFilter(pa));
21035                        }
21036                        if (outActivities != null) {
21037                            outActivities.add(pa.mPref.mComponent);
21038                        }
21039                    }
21040                }
21041            }
21042        }
21043
21044        return num;
21045    }
21046
21047    @Override
21048    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
21049            int userId) {
21050        int callingUid = Binder.getCallingUid();
21051        if (callingUid != Process.SYSTEM_UID) {
21052            throw new SecurityException(
21053                    "addPersistentPreferredActivity can only be run by the system");
21054        }
21055        if (filter.countActions() == 0) {
21056            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
21057            return;
21058        }
21059        synchronized (mPackages) {
21060            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
21061                    ":");
21062            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
21063            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
21064                    new PersistentPreferredActivity(filter, activity));
21065            scheduleWritePackageRestrictionsLocked(userId);
21066            postPreferredActivityChangedBroadcast(userId);
21067        }
21068    }
21069
21070    @Override
21071    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
21072        int callingUid = Binder.getCallingUid();
21073        if (callingUid != Process.SYSTEM_UID) {
21074            throw new SecurityException(
21075                    "clearPackagePersistentPreferredActivities can only be run by the system");
21076        }
21077        ArrayList<PersistentPreferredActivity> removed = null;
21078        boolean changed = false;
21079        synchronized (mPackages) {
21080            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
21081                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
21082                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
21083                        .valueAt(i);
21084                if (userId != thisUserId) {
21085                    continue;
21086                }
21087                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
21088                while (it.hasNext()) {
21089                    PersistentPreferredActivity ppa = it.next();
21090                    // Mark entry for removal only if it matches the package name.
21091                    if (ppa.mComponent.getPackageName().equals(packageName)) {
21092                        if (removed == null) {
21093                            removed = new ArrayList<PersistentPreferredActivity>();
21094                        }
21095                        removed.add(ppa);
21096                    }
21097                }
21098                if (removed != null) {
21099                    for (int j=0; j<removed.size(); j++) {
21100                        PersistentPreferredActivity ppa = removed.get(j);
21101                        ppir.removeFilter(ppa);
21102                    }
21103                    changed = true;
21104                }
21105            }
21106
21107            if (changed) {
21108                scheduleWritePackageRestrictionsLocked(userId);
21109                postPreferredActivityChangedBroadcast(userId);
21110            }
21111        }
21112    }
21113
21114    /**
21115     * Common machinery for picking apart a restored XML blob and passing
21116     * it to a caller-supplied functor to be applied to the running system.
21117     */
21118    private void restoreFromXml(XmlPullParser parser, int userId,
21119            String expectedStartTag, BlobXmlRestorer functor)
21120            throws IOException, XmlPullParserException {
21121        int type;
21122        while ((type = parser.next()) != XmlPullParser.START_TAG
21123                && type != XmlPullParser.END_DOCUMENT) {
21124        }
21125        if (type != XmlPullParser.START_TAG) {
21126            // oops didn't find a start tag?!
21127            if (DEBUG_BACKUP) {
21128                Slog.e(TAG, "Didn't find start tag during restore");
21129            }
21130            return;
21131        }
21132Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
21133        // this is supposed to be TAG_PREFERRED_BACKUP
21134        if (!expectedStartTag.equals(parser.getName())) {
21135            if (DEBUG_BACKUP) {
21136                Slog.e(TAG, "Found unexpected tag " + parser.getName());
21137            }
21138            return;
21139        }
21140
21141        // skip interfering stuff, then we're aligned with the backing implementation
21142        while ((type = parser.next()) == XmlPullParser.TEXT) { }
21143Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
21144        functor.apply(parser, userId);
21145    }
21146
21147    private interface BlobXmlRestorer {
21148        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
21149    }
21150
21151    /**
21152     * Non-Binder method, support for the backup/restore mechanism: write the
21153     * full set of preferred activities in its canonical XML format.  Returns the
21154     * XML output as a byte array, or null if there is none.
21155     */
21156    @Override
21157    public byte[] getPreferredActivityBackup(int userId) {
21158        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21159            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
21160        }
21161
21162        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21163        try {
21164            final XmlSerializer serializer = new FastXmlSerializer();
21165            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21166            serializer.startDocument(null, true);
21167            serializer.startTag(null, TAG_PREFERRED_BACKUP);
21168
21169            synchronized (mPackages) {
21170                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
21171            }
21172
21173            serializer.endTag(null, TAG_PREFERRED_BACKUP);
21174            serializer.endDocument();
21175            serializer.flush();
21176        } catch (Exception e) {
21177            if (DEBUG_BACKUP) {
21178                Slog.e(TAG, "Unable to write preferred activities for backup", e);
21179            }
21180            return null;
21181        }
21182
21183        return dataStream.toByteArray();
21184    }
21185
21186    @Override
21187    public void restorePreferredActivities(byte[] backup, int userId) {
21188        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21189            throw new SecurityException("Only the system may call restorePreferredActivities()");
21190        }
21191
21192        try {
21193            final XmlPullParser parser = Xml.newPullParser();
21194            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21195            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
21196                    new BlobXmlRestorer() {
21197                        @Override
21198                        public void apply(XmlPullParser parser, int userId)
21199                                throws XmlPullParserException, IOException {
21200                            synchronized (mPackages) {
21201                                mSettings.readPreferredActivitiesLPw(parser, userId);
21202                            }
21203                        }
21204                    } );
21205        } catch (Exception e) {
21206            if (DEBUG_BACKUP) {
21207                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21208            }
21209        }
21210    }
21211
21212    /**
21213     * Non-Binder method, support for the backup/restore mechanism: write the
21214     * default browser (etc) settings in its canonical XML format.  Returns the default
21215     * browser XML representation as a byte array, or null if there is none.
21216     */
21217    @Override
21218    public byte[] getDefaultAppsBackup(int userId) {
21219        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21220            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
21221        }
21222
21223        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21224        try {
21225            final XmlSerializer serializer = new FastXmlSerializer();
21226            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21227            serializer.startDocument(null, true);
21228            serializer.startTag(null, TAG_DEFAULT_APPS);
21229
21230            synchronized (mPackages) {
21231                mSettings.writeDefaultAppsLPr(serializer, userId);
21232            }
21233
21234            serializer.endTag(null, TAG_DEFAULT_APPS);
21235            serializer.endDocument();
21236            serializer.flush();
21237        } catch (Exception e) {
21238            if (DEBUG_BACKUP) {
21239                Slog.e(TAG, "Unable to write default apps for backup", e);
21240            }
21241            return null;
21242        }
21243
21244        return dataStream.toByteArray();
21245    }
21246
21247    @Override
21248    public void restoreDefaultApps(byte[] backup, int userId) {
21249        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21250            throw new SecurityException("Only the system may call restoreDefaultApps()");
21251        }
21252
21253        try {
21254            final XmlPullParser parser = Xml.newPullParser();
21255            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21256            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
21257                    new BlobXmlRestorer() {
21258                        @Override
21259                        public void apply(XmlPullParser parser, int userId)
21260                                throws XmlPullParserException, IOException {
21261                            synchronized (mPackages) {
21262                                mSettings.readDefaultAppsLPw(parser, userId);
21263                            }
21264                        }
21265                    } );
21266        } catch (Exception e) {
21267            if (DEBUG_BACKUP) {
21268                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
21269            }
21270        }
21271    }
21272
21273    @Override
21274    public byte[] getIntentFilterVerificationBackup(int userId) {
21275        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21276            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
21277        }
21278
21279        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21280        try {
21281            final XmlSerializer serializer = new FastXmlSerializer();
21282            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21283            serializer.startDocument(null, true);
21284            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
21285
21286            synchronized (mPackages) {
21287                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
21288            }
21289
21290            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
21291            serializer.endDocument();
21292            serializer.flush();
21293        } catch (Exception e) {
21294            if (DEBUG_BACKUP) {
21295                Slog.e(TAG, "Unable to write default apps for backup", e);
21296            }
21297            return null;
21298        }
21299
21300        return dataStream.toByteArray();
21301    }
21302
21303    @Override
21304    public void restoreIntentFilterVerification(byte[] backup, int userId) {
21305        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21306            throw new SecurityException("Only the system may call restorePreferredActivities()");
21307        }
21308
21309        try {
21310            final XmlPullParser parser = Xml.newPullParser();
21311            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21312            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
21313                    new BlobXmlRestorer() {
21314                        @Override
21315                        public void apply(XmlPullParser parser, int userId)
21316                                throws XmlPullParserException, IOException {
21317                            synchronized (mPackages) {
21318                                mSettings.readAllDomainVerificationsLPr(parser, userId);
21319                                mSettings.writeLPr();
21320                            }
21321                        }
21322                    } );
21323        } catch (Exception e) {
21324            if (DEBUG_BACKUP) {
21325                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21326            }
21327        }
21328    }
21329
21330    @Override
21331    public byte[] getPermissionGrantBackup(int userId) {
21332        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21333            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
21334        }
21335
21336        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21337        try {
21338            final XmlSerializer serializer = new FastXmlSerializer();
21339            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21340            serializer.startDocument(null, true);
21341            serializer.startTag(null, TAG_PERMISSION_BACKUP);
21342
21343            synchronized (mPackages) {
21344                serializeRuntimePermissionGrantsLPr(serializer, userId);
21345            }
21346
21347            serializer.endTag(null, TAG_PERMISSION_BACKUP);
21348            serializer.endDocument();
21349            serializer.flush();
21350        } catch (Exception e) {
21351            if (DEBUG_BACKUP) {
21352                Slog.e(TAG, "Unable to write default apps for backup", e);
21353            }
21354            return null;
21355        }
21356
21357        return dataStream.toByteArray();
21358    }
21359
21360    @Override
21361    public void restorePermissionGrants(byte[] backup, int userId) {
21362        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21363            throw new SecurityException("Only the system may call restorePermissionGrants()");
21364        }
21365
21366        try {
21367            final XmlPullParser parser = Xml.newPullParser();
21368            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21369            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
21370                    new BlobXmlRestorer() {
21371                        @Override
21372                        public void apply(XmlPullParser parser, int userId)
21373                                throws XmlPullParserException, IOException {
21374                            synchronized (mPackages) {
21375                                processRestoredPermissionGrantsLPr(parser, userId);
21376                            }
21377                        }
21378                    } );
21379        } catch (Exception e) {
21380            if (DEBUG_BACKUP) {
21381                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21382            }
21383        }
21384    }
21385
21386    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
21387            throws IOException {
21388        serializer.startTag(null, TAG_ALL_GRANTS);
21389
21390        final int N = mSettings.mPackages.size();
21391        for (int i = 0; i < N; i++) {
21392            final PackageSetting ps = mSettings.mPackages.valueAt(i);
21393            boolean pkgGrantsKnown = false;
21394
21395            PermissionsState packagePerms = ps.getPermissionsState();
21396
21397            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
21398                final int grantFlags = state.getFlags();
21399                // only look at grants that are not system/policy fixed
21400                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
21401                    final boolean isGranted = state.isGranted();
21402                    // And only back up the user-twiddled state bits
21403                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
21404                        final String packageName = mSettings.mPackages.keyAt(i);
21405                        if (!pkgGrantsKnown) {
21406                            serializer.startTag(null, TAG_GRANT);
21407                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
21408                            pkgGrantsKnown = true;
21409                        }
21410
21411                        final boolean userSet =
21412                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
21413                        final boolean userFixed =
21414                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
21415                        final boolean revoke =
21416                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
21417
21418                        serializer.startTag(null, TAG_PERMISSION);
21419                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
21420                        if (isGranted) {
21421                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
21422                        }
21423                        if (userSet) {
21424                            serializer.attribute(null, ATTR_USER_SET, "true");
21425                        }
21426                        if (userFixed) {
21427                            serializer.attribute(null, ATTR_USER_FIXED, "true");
21428                        }
21429                        if (revoke) {
21430                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
21431                        }
21432                        serializer.endTag(null, TAG_PERMISSION);
21433                    }
21434                }
21435            }
21436
21437            if (pkgGrantsKnown) {
21438                serializer.endTag(null, TAG_GRANT);
21439            }
21440        }
21441
21442        serializer.endTag(null, TAG_ALL_GRANTS);
21443    }
21444
21445    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
21446            throws XmlPullParserException, IOException {
21447        String pkgName = null;
21448        int outerDepth = parser.getDepth();
21449        int type;
21450        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
21451                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
21452            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
21453                continue;
21454            }
21455
21456            final String tagName = parser.getName();
21457            if (tagName.equals(TAG_GRANT)) {
21458                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
21459                if (DEBUG_BACKUP) {
21460                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
21461                }
21462            } else if (tagName.equals(TAG_PERMISSION)) {
21463
21464                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
21465                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
21466
21467                int newFlagSet = 0;
21468                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
21469                    newFlagSet |= FLAG_PERMISSION_USER_SET;
21470                }
21471                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
21472                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
21473                }
21474                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
21475                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
21476                }
21477                if (DEBUG_BACKUP) {
21478                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
21479                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
21480                }
21481                final PackageSetting ps = mSettings.mPackages.get(pkgName);
21482                if (ps != null) {
21483                    // Already installed so we apply the grant immediately
21484                    if (DEBUG_BACKUP) {
21485                        Slog.v(TAG, "        + already installed; applying");
21486                    }
21487                    PermissionsState perms = ps.getPermissionsState();
21488                    BasePermission bp = mSettings.mPermissions.get(permName);
21489                    if (bp != null) {
21490                        if (isGranted) {
21491                            perms.grantRuntimePermission(bp, userId);
21492                        }
21493                        if (newFlagSet != 0) {
21494                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
21495                        }
21496                    }
21497                } else {
21498                    // Need to wait for post-restore install to apply the grant
21499                    if (DEBUG_BACKUP) {
21500                        Slog.v(TAG, "        - not yet installed; saving for later");
21501                    }
21502                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
21503                            isGranted, newFlagSet, userId);
21504                }
21505            } else {
21506                PackageManagerService.reportSettingsProblem(Log.WARN,
21507                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
21508                XmlUtils.skipCurrentTag(parser);
21509            }
21510        }
21511
21512        scheduleWriteSettingsLocked();
21513        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
21514    }
21515
21516    @Override
21517    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
21518            int sourceUserId, int targetUserId, int flags) {
21519        mContext.enforceCallingOrSelfPermission(
21520                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21521        int callingUid = Binder.getCallingUid();
21522        enforceOwnerRights(ownerPackage, callingUid);
21523        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21524        if (intentFilter.countActions() == 0) {
21525            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
21526            return;
21527        }
21528        synchronized (mPackages) {
21529            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
21530                    ownerPackage, targetUserId, flags);
21531            CrossProfileIntentResolver resolver =
21532                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21533            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
21534            // We have all those whose filter is equal. Now checking if the rest is equal as well.
21535            if (existing != null) {
21536                int size = existing.size();
21537                for (int i = 0; i < size; i++) {
21538                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
21539                        return;
21540                    }
21541                }
21542            }
21543            resolver.addFilter(newFilter);
21544            scheduleWritePackageRestrictionsLocked(sourceUserId);
21545        }
21546    }
21547
21548    @Override
21549    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
21550        mContext.enforceCallingOrSelfPermission(
21551                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21552        final int callingUid = Binder.getCallingUid();
21553        enforceOwnerRights(ownerPackage, callingUid);
21554        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21555        synchronized (mPackages) {
21556            CrossProfileIntentResolver resolver =
21557                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21558            ArraySet<CrossProfileIntentFilter> set =
21559                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
21560            for (CrossProfileIntentFilter filter : set) {
21561                if (filter.getOwnerPackage().equals(ownerPackage)) {
21562                    resolver.removeFilter(filter);
21563                }
21564            }
21565            scheduleWritePackageRestrictionsLocked(sourceUserId);
21566        }
21567    }
21568
21569    // Enforcing that callingUid is owning pkg on userId
21570    private void enforceOwnerRights(String pkg, int callingUid) {
21571        // The system owns everything.
21572        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
21573            return;
21574        }
21575        final int callingUserId = UserHandle.getUserId(callingUid);
21576        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
21577        if (pi == null) {
21578            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
21579                    + callingUserId);
21580        }
21581        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
21582            throw new SecurityException("Calling uid " + callingUid
21583                    + " does not own package " + pkg);
21584        }
21585    }
21586
21587    @Override
21588    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
21589        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21590            return null;
21591        }
21592        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
21593    }
21594
21595    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
21596        UserManagerService ums = UserManagerService.getInstance();
21597        if (ums != null) {
21598            final UserInfo parent = ums.getProfileParent(userId);
21599            final int launcherUid = (parent != null) ? parent.id : userId;
21600            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
21601            if (launcherComponent != null) {
21602                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
21603                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
21604                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
21605                        .setPackage(launcherComponent.getPackageName());
21606                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
21607            }
21608        }
21609    }
21610
21611    /**
21612     * Report the 'Home' activity which is currently set as "always use this one". If non is set
21613     * then reports the most likely home activity or null if there are more than one.
21614     */
21615    private ComponentName getDefaultHomeActivity(int userId) {
21616        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
21617        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
21618        if (cn != null) {
21619            return cn;
21620        }
21621
21622        // Find the launcher with the highest priority and return that component if there are no
21623        // other home activity with the same priority.
21624        int lastPriority = Integer.MIN_VALUE;
21625        ComponentName lastComponent = null;
21626        final int size = allHomeCandidates.size();
21627        for (int i = 0; i < size; i++) {
21628            final ResolveInfo ri = allHomeCandidates.get(i);
21629            if (ri.priority > lastPriority) {
21630                lastComponent = ri.activityInfo.getComponentName();
21631                lastPriority = ri.priority;
21632            } else if (ri.priority == lastPriority) {
21633                // Two components found with same priority.
21634                lastComponent = null;
21635            }
21636        }
21637        return lastComponent;
21638    }
21639
21640    private Intent getHomeIntent() {
21641        Intent intent = new Intent(Intent.ACTION_MAIN);
21642        intent.addCategory(Intent.CATEGORY_HOME);
21643        intent.addCategory(Intent.CATEGORY_DEFAULT);
21644        return intent;
21645    }
21646
21647    private IntentFilter getHomeFilter() {
21648        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
21649        filter.addCategory(Intent.CATEGORY_HOME);
21650        filter.addCategory(Intent.CATEGORY_DEFAULT);
21651        return filter;
21652    }
21653
21654    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21655            int userId) {
21656        Intent intent  = getHomeIntent();
21657        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
21658                PackageManager.GET_META_DATA, userId);
21659        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
21660                true, false, false, userId);
21661
21662        allHomeCandidates.clear();
21663        if (list != null) {
21664            for (ResolveInfo ri : list) {
21665                allHomeCandidates.add(ri);
21666            }
21667        }
21668        return (preferred == null || preferred.activityInfo == null)
21669                ? null
21670                : new ComponentName(preferred.activityInfo.packageName,
21671                        preferred.activityInfo.name);
21672    }
21673
21674    @Override
21675    public void setHomeActivity(ComponentName comp, int userId) {
21676        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21677            return;
21678        }
21679        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21680        getHomeActivitiesAsUser(homeActivities, userId);
21681
21682        boolean found = false;
21683
21684        final int size = homeActivities.size();
21685        final ComponentName[] set = new ComponentName[size];
21686        for (int i = 0; i < size; i++) {
21687            final ResolveInfo candidate = homeActivities.get(i);
21688            final ActivityInfo info = candidate.activityInfo;
21689            final ComponentName activityName = new ComponentName(info.packageName, info.name);
21690            set[i] = activityName;
21691            if (!found && activityName.equals(comp)) {
21692                found = true;
21693            }
21694        }
21695        if (!found) {
21696            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21697                    + userId);
21698        }
21699        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21700                set, comp, userId);
21701    }
21702
21703    private @Nullable String getSetupWizardPackageName() {
21704        final Intent intent = new Intent(Intent.ACTION_MAIN);
21705        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21706
21707        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21708                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21709                        | MATCH_DISABLED_COMPONENTS,
21710                UserHandle.myUserId());
21711        if (matches.size() == 1) {
21712            return matches.get(0).getComponentInfo().packageName;
21713        } else {
21714            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21715                    + ": matches=" + matches);
21716            return null;
21717        }
21718    }
21719
21720    private @Nullable String getStorageManagerPackageName() {
21721        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21722
21723        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21724                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21725                        | MATCH_DISABLED_COMPONENTS,
21726                UserHandle.myUserId());
21727        if (matches.size() == 1) {
21728            return matches.get(0).getComponentInfo().packageName;
21729        } else {
21730            Slog.e(TAG, "There should probably be exactly one storage manager; found "
21731                    + matches.size() + ": matches=" + matches);
21732            return null;
21733        }
21734    }
21735
21736    @Override
21737    public void setApplicationEnabledSetting(String appPackageName,
21738            int newState, int flags, int userId, String callingPackage) {
21739        if (!sUserManager.exists(userId)) return;
21740        if (callingPackage == null) {
21741            callingPackage = Integer.toString(Binder.getCallingUid());
21742        }
21743        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21744    }
21745
21746    @Override
21747    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21748        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21749        synchronized (mPackages) {
21750            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21751            if (pkgSetting != null) {
21752                pkgSetting.setUpdateAvailable(updateAvailable);
21753            }
21754        }
21755    }
21756
21757    @Override
21758    public void setComponentEnabledSetting(ComponentName componentName,
21759            int newState, int flags, int userId) {
21760        if (!sUserManager.exists(userId)) return;
21761        setEnabledSetting(componentName.getPackageName(),
21762                componentName.getClassName(), newState, flags, userId, null);
21763    }
21764
21765    private void setEnabledSetting(final String packageName, String className, int newState,
21766            final int flags, int userId, String callingPackage) {
21767        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21768              || newState == COMPONENT_ENABLED_STATE_ENABLED
21769              || newState == COMPONENT_ENABLED_STATE_DISABLED
21770              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21771              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21772            throw new IllegalArgumentException("Invalid new component state: "
21773                    + newState);
21774        }
21775        PackageSetting pkgSetting;
21776        final int callingUid = Binder.getCallingUid();
21777        final int permission;
21778        if (callingUid == Process.SYSTEM_UID) {
21779            permission = PackageManager.PERMISSION_GRANTED;
21780        } else {
21781            permission = mContext.checkCallingOrSelfPermission(
21782                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21783        }
21784        enforceCrossUserPermission(callingUid, userId,
21785                false /* requireFullPermission */, true /* checkShell */, "set enabled");
21786        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21787        boolean sendNow = false;
21788        boolean isApp = (className == null);
21789        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21790        String componentName = isApp ? packageName : className;
21791        int packageUid = -1;
21792        ArrayList<String> components;
21793
21794        // reader
21795        synchronized (mPackages) {
21796            pkgSetting = mSettings.mPackages.get(packageName);
21797            if (pkgSetting == null) {
21798                if (!isCallerInstantApp) {
21799                    if (className == null) {
21800                        throw new IllegalArgumentException("Unknown package: " + packageName);
21801                    }
21802                    throw new IllegalArgumentException(
21803                            "Unknown component: " + packageName + "/" + className);
21804                } else {
21805                    // throw SecurityException to prevent leaking package information
21806                    throw new SecurityException(
21807                            "Attempt to change component state; "
21808                            + "pid=" + Binder.getCallingPid()
21809                            + ", uid=" + callingUid
21810                            + (className == null
21811                                    ? ", package=" + packageName
21812                                    : ", component=" + packageName + "/" + className));
21813                }
21814            }
21815        }
21816
21817        // Limit who can change which apps
21818        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21819            // Don't allow apps that don't have permission to modify other apps
21820            if (!allowedByPermission
21821                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21822                throw new SecurityException(
21823                        "Attempt to change component state; "
21824                        + "pid=" + Binder.getCallingPid()
21825                        + ", uid=" + callingUid
21826                        + (className == null
21827                                ? ", package=" + packageName
21828                                : ", component=" + packageName + "/" + className));
21829            }
21830            // Don't allow changing protected packages.
21831            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21832                throw new SecurityException("Cannot disable a protected package: " + packageName);
21833            }
21834        }
21835
21836        synchronized (mPackages) {
21837            if (callingUid == Process.SHELL_UID
21838                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21839                // Shell can only change whole packages between ENABLED and DISABLED_USER states
21840                // unless it is a test package.
21841                int oldState = pkgSetting.getEnabled(userId);
21842                if (className == null
21843                        &&
21844                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21845                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21846                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21847                        &&
21848                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21849                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
21850                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21851                    // ok
21852                } else {
21853                    throw new SecurityException(
21854                            "Shell cannot change component state for " + packageName + "/"
21855                                    + className + " to " + newState);
21856                }
21857            }
21858        }
21859        if (className == null) {
21860            // We're dealing with an application/package level state change
21861            synchronized (mPackages) {
21862                if (pkgSetting.getEnabled(userId) == newState) {
21863                    // Nothing to do
21864                    return;
21865                }
21866            }
21867            // If we're enabling a system stub, there's a little more work to do.
21868            // Prior to enabling the package, we need to decompress the APK(s) to the
21869            // data partition and then replace the version on the system partition.
21870            final PackageParser.Package deletedPkg = pkgSetting.pkg;
21871            final boolean isSystemStub = deletedPkg.isStub
21872                    && deletedPkg.isSystemApp();
21873            if (isSystemStub
21874                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21875                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
21876                final File codePath = decompressPackage(deletedPkg);
21877                if (codePath == null) {
21878                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
21879                    return;
21880                }
21881                // TODO remove direct parsing of the package object during internal cleanup
21882                // of scan package
21883                // We need to call parse directly here for no other reason than we need
21884                // the new package in order to disable the old one [we use the information
21885                // for some internal optimization to optionally create a new package setting
21886                // object on replace]. However, we can't get the package from the scan
21887                // because the scan modifies live structures and we need to remove the
21888                // old [system] package from the system before a scan can be attempted.
21889                // Once scan is indempotent we can remove this parse and use the package
21890                // object we scanned, prior to adding it to package settings.
21891                final PackageParser pp = new PackageParser();
21892                pp.setSeparateProcesses(mSeparateProcesses);
21893                pp.setDisplayMetrics(mMetrics);
21894                pp.setCallback(mPackageParserCallback);
21895                final PackageParser.Package tmpPkg;
21896                try {
21897                    final int parseFlags = mDefParseFlags
21898                            | PackageParser.PARSE_MUST_BE_APK
21899                            | PackageParser.PARSE_IS_SYSTEM
21900                            | PackageParser.PARSE_IS_SYSTEM_DIR;
21901                    tmpPkg = pp.parsePackage(codePath, parseFlags);
21902                } catch (PackageParserException e) {
21903                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
21904                    return;
21905                }
21906                synchronized (mInstallLock) {
21907                    // Disable the stub and remove any package entries
21908                    removePackageLI(deletedPkg, true);
21909                    synchronized (mPackages) {
21910                        disableSystemPackageLPw(deletedPkg, tmpPkg);
21911                    }
21912                    final PackageParser.Package newPkg;
21913                    try (PackageFreezer freezer =
21914                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
21915                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
21916                                | PackageParser.PARSE_ENFORCE_CODE;
21917                        newPkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
21918                                0 /*currentTime*/, null /*user*/);
21919                        prepareAppDataAfterInstallLIF(newPkg);
21920                        synchronized (mPackages) {
21921                            try {
21922                                updateSharedLibrariesLPr(newPkg, null);
21923                            } catch (PackageManagerException e) {
21924                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
21925                            }
21926                            updatePermissionsLPw(newPkg.packageName, newPkg,
21927                                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
21928                            mSettings.writeLPr();
21929                        }
21930                    } catch (PackageManagerException e) {
21931                        // Whoops! Something went wrong; try to roll back to the stub
21932                        Slog.w(TAG, "Failed to install compressed system package:"
21933                                + pkgSetting.name, e);
21934                        // Remove the failed install
21935                        removeCodePathLI(codePath);
21936
21937                        // Install the system package
21938                        try (PackageFreezer freezer =
21939                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
21940                            synchronized (mPackages) {
21941                                // NOTE: The system package always needs to be enabled; even
21942                                // if it's for a compressed stub. If we don't, installing the
21943                                // system package fails during scan [scanning checks the disabled
21944                                // packages]. We will reverse this later, after we've "installed"
21945                                // the stub.
21946                                // This leaves us in a fragile state; the stub should never be
21947                                // enabled, so, cross your fingers and hope nothing goes wrong
21948                                // until we can disable the package later.
21949                                enableSystemPackageLPw(deletedPkg);
21950                            }
21951                            installPackageFromSystemLIF(new File(deletedPkg.codePath),
21952                                    false /*isPrivileged*/, null /*allUserHandles*/,
21953                                    null /*origUserHandles*/, null /*origPermissionsState*/,
21954                                    true /*writeSettings*/);
21955                        } catch (PackageManagerException pme) {
21956                            Slog.w(TAG, "Failed to restore system package:"
21957                                    + deletedPkg.packageName, pme);
21958                        } finally {
21959                            synchronized (mPackages) {
21960                                mSettings.disableSystemPackageLPw(
21961                                        deletedPkg.packageName, true /*replaced*/);
21962                                mSettings.writeLPr();
21963                            }
21964                        }
21965                        return;
21966                    }
21967                    clearAppDataLIF(newPkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
21968                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21969                    clearAppProfilesLIF(newPkg, UserHandle.USER_ALL);
21970                    mDexManager.notifyPackageUpdated(newPkg.packageName,
21971                            newPkg.baseCodePath, newPkg.splitCodePaths);
21972                }
21973            }
21974            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21975                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
21976                // Don't care about who enables an app.
21977                callingPackage = null;
21978            }
21979            synchronized (mPackages) {
21980                pkgSetting.setEnabled(newState, userId, callingPackage);
21981            }
21982        } else {
21983            synchronized (mPackages) {
21984                // We're dealing with a component level state change
21985                // First, verify that this is a valid class name.
21986                PackageParser.Package pkg = pkgSetting.pkg;
21987                if (pkg == null || !pkg.hasComponentClassName(className)) {
21988                    if (pkg != null &&
21989                            pkg.applicationInfo.targetSdkVersion >=
21990                                    Build.VERSION_CODES.JELLY_BEAN) {
21991                        throw new IllegalArgumentException("Component class " + className
21992                                + " does not exist in " + packageName);
21993                    } else {
21994                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
21995                                + className + " does not exist in " + packageName);
21996                    }
21997                }
21998                switch (newState) {
21999                    case COMPONENT_ENABLED_STATE_ENABLED:
22000                        if (!pkgSetting.enableComponentLPw(className, userId)) {
22001                            return;
22002                        }
22003                        break;
22004                    case COMPONENT_ENABLED_STATE_DISABLED:
22005                        if (!pkgSetting.disableComponentLPw(className, userId)) {
22006                            return;
22007                        }
22008                        break;
22009                    case COMPONENT_ENABLED_STATE_DEFAULT:
22010                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
22011                            return;
22012                        }
22013                        break;
22014                    default:
22015                        Slog.e(TAG, "Invalid new component state: " + newState);
22016                        return;
22017                }
22018            }
22019        }
22020        synchronized (mPackages) {
22021            scheduleWritePackageRestrictionsLocked(userId);
22022            updateSequenceNumberLP(pkgSetting, new int[] { userId });
22023            final long callingId = Binder.clearCallingIdentity();
22024            try {
22025                updateInstantAppInstallerLocked(packageName);
22026            } finally {
22027                Binder.restoreCallingIdentity(callingId);
22028            }
22029            components = mPendingBroadcasts.get(userId, packageName);
22030            final boolean newPackage = components == null;
22031            if (newPackage) {
22032                components = new ArrayList<String>();
22033            }
22034            if (!components.contains(componentName)) {
22035                components.add(componentName);
22036            }
22037            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
22038                sendNow = true;
22039                // Purge entry from pending broadcast list if another one exists already
22040                // since we are sending one right away.
22041                mPendingBroadcasts.remove(userId, packageName);
22042            } else {
22043                if (newPackage) {
22044                    mPendingBroadcasts.put(userId, packageName, components);
22045                }
22046                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
22047                    // Schedule a message
22048                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
22049                }
22050            }
22051        }
22052
22053        long callingId = Binder.clearCallingIdentity();
22054        try {
22055            if (sendNow) {
22056                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
22057                sendPackageChangedBroadcast(packageName,
22058                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
22059            }
22060        } finally {
22061            Binder.restoreCallingIdentity(callingId);
22062        }
22063    }
22064
22065    @Override
22066    public void flushPackageRestrictionsAsUser(int userId) {
22067        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
22068            return;
22069        }
22070        if (!sUserManager.exists(userId)) {
22071            return;
22072        }
22073        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
22074                false /* checkShell */, "flushPackageRestrictions");
22075        synchronized (mPackages) {
22076            mSettings.writePackageRestrictionsLPr(userId);
22077            mDirtyUsers.remove(userId);
22078            if (mDirtyUsers.isEmpty()) {
22079                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
22080            }
22081        }
22082    }
22083
22084    private void sendPackageChangedBroadcast(String packageName,
22085            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
22086        if (DEBUG_INSTALL)
22087            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
22088                    + componentNames);
22089        Bundle extras = new Bundle(4);
22090        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
22091        String nameList[] = new String[componentNames.size()];
22092        componentNames.toArray(nameList);
22093        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
22094        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
22095        extras.putInt(Intent.EXTRA_UID, packageUid);
22096        // If this is not reporting a change of the overall package, then only send it
22097        // to registered receivers.  We don't want to launch a swath of apps for every
22098        // little component state change.
22099        final int flags = !componentNames.contains(packageName)
22100                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
22101        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
22102                new int[] {UserHandle.getUserId(packageUid)});
22103    }
22104
22105    @Override
22106    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
22107        if (!sUserManager.exists(userId)) return;
22108        final int callingUid = Binder.getCallingUid();
22109        if (getInstantAppPackageName(callingUid) != null) {
22110            return;
22111        }
22112        final int permission = mContext.checkCallingOrSelfPermission(
22113                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
22114        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
22115        enforceCrossUserPermission(callingUid, userId,
22116                true /* requireFullPermission */, true /* checkShell */, "stop package");
22117        // writer
22118        synchronized (mPackages) {
22119            final PackageSetting ps = mSettings.mPackages.get(packageName);
22120            if (!filterAppAccessLPr(ps, callingUid, userId)
22121                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
22122                            allowedByPermission, callingUid, userId)) {
22123                scheduleWritePackageRestrictionsLocked(userId);
22124            }
22125        }
22126    }
22127
22128    @Override
22129    public String getInstallerPackageName(String packageName) {
22130        final int callingUid = Binder.getCallingUid();
22131        if (getInstantAppPackageName(callingUid) != null) {
22132            return null;
22133        }
22134        // reader
22135        synchronized (mPackages) {
22136            final PackageSetting ps = mSettings.mPackages.get(packageName);
22137            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
22138                return null;
22139            }
22140            return mSettings.getInstallerPackageNameLPr(packageName);
22141        }
22142    }
22143
22144    public boolean isOrphaned(String packageName) {
22145        // reader
22146        synchronized (mPackages) {
22147            return mSettings.isOrphaned(packageName);
22148        }
22149    }
22150
22151    @Override
22152    public int getApplicationEnabledSetting(String packageName, int userId) {
22153        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
22154        int callingUid = Binder.getCallingUid();
22155        enforceCrossUserPermission(callingUid, userId,
22156                false /* requireFullPermission */, false /* checkShell */, "get enabled");
22157        // reader
22158        synchronized (mPackages) {
22159            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
22160                return COMPONENT_ENABLED_STATE_DISABLED;
22161            }
22162            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
22163        }
22164    }
22165
22166    @Override
22167    public int getComponentEnabledSetting(ComponentName component, int userId) {
22168        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
22169        int callingUid = Binder.getCallingUid();
22170        enforceCrossUserPermission(callingUid, userId,
22171                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
22172        synchronized (mPackages) {
22173            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
22174                    component, TYPE_UNKNOWN, userId)) {
22175                return COMPONENT_ENABLED_STATE_DISABLED;
22176            }
22177            return mSettings.getComponentEnabledSettingLPr(component, userId);
22178        }
22179    }
22180
22181    @Override
22182    public void enterSafeMode() {
22183        enforceSystemOrRoot("Only the system can request entering safe mode");
22184
22185        if (!mSystemReady) {
22186            mSafeMode = true;
22187        }
22188    }
22189
22190    @Override
22191    public void systemReady() {
22192        enforceSystemOrRoot("Only the system can claim the system is ready");
22193
22194        mSystemReady = true;
22195        final ContentResolver resolver = mContext.getContentResolver();
22196        ContentObserver co = new ContentObserver(mHandler) {
22197            @Override
22198            public void onChange(boolean selfChange) {
22199                mEphemeralAppsDisabled =
22200                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
22201                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
22202            }
22203        };
22204        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
22205                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
22206                false, co, UserHandle.USER_SYSTEM);
22207        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
22208                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
22209        co.onChange(true);
22210
22211        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
22212        // disabled after already being started.
22213        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
22214                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
22215
22216        // Read the compatibilty setting when the system is ready.
22217        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
22218                mContext.getContentResolver(),
22219                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
22220        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
22221        if (DEBUG_SETTINGS) {
22222            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
22223        }
22224
22225        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
22226
22227        synchronized (mPackages) {
22228            // Verify that all of the preferred activity components actually
22229            // exist.  It is possible for applications to be updated and at
22230            // that point remove a previously declared activity component that
22231            // had been set as a preferred activity.  We try to clean this up
22232            // the next time we encounter that preferred activity, but it is
22233            // possible for the user flow to never be able to return to that
22234            // situation so here we do a sanity check to make sure we haven't
22235            // left any junk around.
22236            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
22237            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22238                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22239                removed.clear();
22240                for (PreferredActivity pa : pir.filterSet()) {
22241                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
22242                        removed.add(pa);
22243                    }
22244                }
22245                if (removed.size() > 0) {
22246                    for (int r=0; r<removed.size(); r++) {
22247                        PreferredActivity pa = removed.get(r);
22248                        Slog.w(TAG, "Removing dangling preferred activity: "
22249                                + pa.mPref.mComponent);
22250                        pir.removeFilter(pa);
22251                    }
22252                    mSettings.writePackageRestrictionsLPr(
22253                            mSettings.mPreferredActivities.keyAt(i));
22254                }
22255            }
22256
22257            for (int userId : UserManagerService.getInstance().getUserIds()) {
22258                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
22259                    grantPermissionsUserIds = ArrayUtils.appendInt(
22260                            grantPermissionsUserIds, userId);
22261                }
22262            }
22263        }
22264        sUserManager.systemReady();
22265
22266        // If we upgraded grant all default permissions before kicking off.
22267        for (int userId : grantPermissionsUserIds) {
22268            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22269        }
22270
22271        // If we did not grant default permissions, we preload from this the
22272        // default permission exceptions lazily to ensure we don't hit the
22273        // disk on a new user creation.
22274        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
22275            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
22276        }
22277
22278        // Kick off any messages waiting for system ready
22279        if (mPostSystemReadyMessages != null) {
22280            for (Message msg : mPostSystemReadyMessages) {
22281                msg.sendToTarget();
22282            }
22283            mPostSystemReadyMessages = null;
22284        }
22285
22286        // Watch for external volumes that come and go over time
22287        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22288        storage.registerListener(mStorageListener);
22289
22290        mInstallerService.systemReady();
22291        mPackageDexOptimizer.systemReady();
22292
22293        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
22294                StorageManagerInternal.class);
22295        StorageManagerInternal.addExternalStoragePolicy(
22296                new StorageManagerInternal.ExternalStorageMountPolicy() {
22297            @Override
22298            public int getMountMode(int uid, String packageName) {
22299                if (Process.isIsolated(uid)) {
22300                    return Zygote.MOUNT_EXTERNAL_NONE;
22301                }
22302                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
22303                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
22304                }
22305                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
22306                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
22307                }
22308                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
22309                    return Zygote.MOUNT_EXTERNAL_READ;
22310                }
22311                return Zygote.MOUNT_EXTERNAL_WRITE;
22312            }
22313
22314            @Override
22315            public boolean hasExternalStorage(int uid, String packageName) {
22316                return true;
22317            }
22318        });
22319
22320        // Now that we're mostly running, clean up stale users and apps
22321        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
22322        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
22323
22324        if (mPrivappPermissionsViolations != null) {
22325            Slog.wtf(TAG,"Signature|privileged permissions not in "
22326                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
22327            mPrivappPermissionsViolations = null;
22328        }
22329    }
22330
22331    public void waitForAppDataPrepared() {
22332        if (mPrepareAppDataFuture == null) {
22333            return;
22334        }
22335        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
22336        mPrepareAppDataFuture = null;
22337    }
22338
22339    @Override
22340    public boolean isSafeMode() {
22341        // allow instant applications
22342        return mSafeMode;
22343    }
22344
22345    @Override
22346    public boolean hasSystemUidErrors() {
22347        // allow instant applications
22348        return mHasSystemUidErrors;
22349    }
22350
22351    static String arrayToString(int[] array) {
22352        StringBuffer buf = new StringBuffer(128);
22353        buf.append('[');
22354        if (array != null) {
22355            for (int i=0; i<array.length; i++) {
22356                if (i > 0) buf.append(", ");
22357                buf.append(array[i]);
22358            }
22359        }
22360        buf.append(']');
22361        return buf.toString();
22362    }
22363
22364    static class DumpState {
22365        public static final int DUMP_LIBS = 1 << 0;
22366        public static final int DUMP_FEATURES = 1 << 1;
22367        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
22368        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
22369        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
22370        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
22371        public static final int DUMP_PERMISSIONS = 1 << 6;
22372        public static final int DUMP_PACKAGES = 1 << 7;
22373        public static final int DUMP_SHARED_USERS = 1 << 8;
22374        public static final int DUMP_MESSAGES = 1 << 9;
22375        public static final int DUMP_PROVIDERS = 1 << 10;
22376        public static final int DUMP_VERIFIERS = 1 << 11;
22377        public static final int DUMP_PREFERRED = 1 << 12;
22378        public static final int DUMP_PREFERRED_XML = 1 << 13;
22379        public static final int DUMP_KEYSETS = 1 << 14;
22380        public static final int DUMP_VERSION = 1 << 15;
22381        public static final int DUMP_INSTALLS = 1 << 16;
22382        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
22383        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
22384        public static final int DUMP_FROZEN = 1 << 19;
22385        public static final int DUMP_DEXOPT = 1 << 20;
22386        public static final int DUMP_COMPILER_STATS = 1 << 21;
22387        public static final int DUMP_CHANGES = 1 << 22;
22388        public static final int DUMP_VOLUMES = 1 << 23;
22389
22390        public static final int OPTION_SHOW_FILTERS = 1 << 0;
22391
22392        private int mTypes;
22393
22394        private int mOptions;
22395
22396        private boolean mTitlePrinted;
22397
22398        private SharedUserSetting mSharedUser;
22399
22400        public boolean isDumping(int type) {
22401            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
22402                return true;
22403            }
22404
22405            return (mTypes & type) != 0;
22406        }
22407
22408        public void setDump(int type) {
22409            mTypes |= type;
22410        }
22411
22412        public boolean isOptionEnabled(int option) {
22413            return (mOptions & option) != 0;
22414        }
22415
22416        public void setOptionEnabled(int option) {
22417            mOptions |= option;
22418        }
22419
22420        public boolean onTitlePrinted() {
22421            final boolean printed = mTitlePrinted;
22422            mTitlePrinted = true;
22423            return printed;
22424        }
22425
22426        public boolean getTitlePrinted() {
22427            return mTitlePrinted;
22428        }
22429
22430        public void setTitlePrinted(boolean enabled) {
22431            mTitlePrinted = enabled;
22432        }
22433
22434        public SharedUserSetting getSharedUser() {
22435            return mSharedUser;
22436        }
22437
22438        public void setSharedUser(SharedUserSetting user) {
22439            mSharedUser = user;
22440        }
22441    }
22442
22443    @Override
22444    public void onShellCommand(FileDescriptor in, FileDescriptor out,
22445            FileDescriptor err, String[] args, ShellCallback callback,
22446            ResultReceiver resultReceiver) {
22447        (new PackageManagerShellCommand(this)).exec(
22448                this, in, out, err, args, callback, resultReceiver);
22449    }
22450
22451    @Override
22452    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
22453        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
22454
22455        DumpState dumpState = new DumpState();
22456        boolean fullPreferred = false;
22457        boolean checkin = false;
22458
22459        String packageName = null;
22460        ArraySet<String> permissionNames = null;
22461
22462        int opti = 0;
22463        while (opti < args.length) {
22464            String opt = args[opti];
22465            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
22466                break;
22467            }
22468            opti++;
22469
22470            if ("-a".equals(opt)) {
22471                // Right now we only know how to print all.
22472            } else if ("-h".equals(opt)) {
22473                pw.println("Package manager dump options:");
22474                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
22475                pw.println("    --checkin: dump for a checkin");
22476                pw.println("    -f: print details of intent filters");
22477                pw.println("    -h: print this help");
22478                pw.println("  cmd may be one of:");
22479                pw.println("    l[ibraries]: list known shared libraries");
22480                pw.println("    f[eatures]: list device features");
22481                pw.println("    k[eysets]: print known keysets");
22482                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
22483                pw.println("    perm[issions]: dump permissions");
22484                pw.println("    permission [name ...]: dump declaration and use of given permission");
22485                pw.println("    pref[erred]: print preferred package settings");
22486                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
22487                pw.println("    prov[iders]: dump content providers");
22488                pw.println("    p[ackages]: dump installed packages");
22489                pw.println("    s[hared-users]: dump shared user IDs");
22490                pw.println("    m[essages]: print collected runtime messages");
22491                pw.println("    v[erifiers]: print package verifier info");
22492                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
22493                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
22494                pw.println("    version: print database version info");
22495                pw.println("    write: write current settings now");
22496                pw.println("    installs: details about install sessions");
22497                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
22498                pw.println("    dexopt: dump dexopt state");
22499                pw.println("    compiler-stats: dump compiler statistics");
22500                pw.println("    enabled-overlays: dump list of enabled overlay packages");
22501                pw.println("    <package.name>: info about given package");
22502                return;
22503            } else if ("--checkin".equals(opt)) {
22504                checkin = true;
22505            } else if ("-f".equals(opt)) {
22506                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
22507            } else if ("--proto".equals(opt)) {
22508                dumpProto(fd);
22509                return;
22510            } else {
22511                pw.println("Unknown argument: " + opt + "; use -h for help");
22512            }
22513        }
22514
22515        // Is the caller requesting to dump a particular piece of data?
22516        if (opti < args.length) {
22517            String cmd = args[opti];
22518            opti++;
22519            // Is this a package name?
22520            if ("android".equals(cmd) || cmd.contains(".")) {
22521                packageName = cmd;
22522                // When dumping a single package, we always dump all of its
22523                // filter information since the amount of data will be reasonable.
22524                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
22525            } else if ("check-permission".equals(cmd)) {
22526                if (opti >= args.length) {
22527                    pw.println("Error: check-permission missing permission argument");
22528                    return;
22529                }
22530                String perm = args[opti];
22531                opti++;
22532                if (opti >= args.length) {
22533                    pw.println("Error: check-permission missing package argument");
22534                    return;
22535                }
22536
22537                String pkg = args[opti];
22538                opti++;
22539                int user = UserHandle.getUserId(Binder.getCallingUid());
22540                if (opti < args.length) {
22541                    try {
22542                        user = Integer.parseInt(args[opti]);
22543                    } catch (NumberFormatException e) {
22544                        pw.println("Error: check-permission user argument is not a number: "
22545                                + args[opti]);
22546                        return;
22547                    }
22548                }
22549
22550                // Normalize package name to handle renamed packages and static libs
22551                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
22552
22553                pw.println(checkPermission(perm, pkg, user));
22554                return;
22555            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
22556                dumpState.setDump(DumpState.DUMP_LIBS);
22557            } else if ("f".equals(cmd) || "features".equals(cmd)) {
22558                dumpState.setDump(DumpState.DUMP_FEATURES);
22559            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
22560                if (opti >= args.length) {
22561                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
22562                            | DumpState.DUMP_SERVICE_RESOLVERS
22563                            | DumpState.DUMP_RECEIVER_RESOLVERS
22564                            | DumpState.DUMP_CONTENT_RESOLVERS);
22565                } else {
22566                    while (opti < args.length) {
22567                        String name = args[opti];
22568                        if ("a".equals(name) || "activity".equals(name)) {
22569                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
22570                        } else if ("s".equals(name) || "service".equals(name)) {
22571                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
22572                        } else if ("r".equals(name) || "receiver".equals(name)) {
22573                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
22574                        } else if ("c".equals(name) || "content".equals(name)) {
22575                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
22576                        } else {
22577                            pw.println("Error: unknown resolver table type: " + name);
22578                            return;
22579                        }
22580                        opti++;
22581                    }
22582                }
22583            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
22584                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
22585            } else if ("permission".equals(cmd)) {
22586                if (opti >= args.length) {
22587                    pw.println("Error: permission requires permission name");
22588                    return;
22589                }
22590                permissionNames = new ArraySet<>();
22591                while (opti < args.length) {
22592                    permissionNames.add(args[opti]);
22593                    opti++;
22594                }
22595                dumpState.setDump(DumpState.DUMP_PERMISSIONS
22596                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
22597            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
22598                dumpState.setDump(DumpState.DUMP_PREFERRED);
22599            } else if ("preferred-xml".equals(cmd)) {
22600                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
22601                if (opti < args.length && "--full".equals(args[opti])) {
22602                    fullPreferred = true;
22603                    opti++;
22604                }
22605            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
22606                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
22607            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
22608                dumpState.setDump(DumpState.DUMP_PACKAGES);
22609            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
22610                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
22611            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
22612                dumpState.setDump(DumpState.DUMP_PROVIDERS);
22613            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
22614                dumpState.setDump(DumpState.DUMP_MESSAGES);
22615            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
22616                dumpState.setDump(DumpState.DUMP_VERIFIERS);
22617            } else if ("i".equals(cmd) || "ifv".equals(cmd)
22618                    || "intent-filter-verifiers".equals(cmd)) {
22619                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
22620            } else if ("version".equals(cmd)) {
22621                dumpState.setDump(DumpState.DUMP_VERSION);
22622            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
22623                dumpState.setDump(DumpState.DUMP_KEYSETS);
22624            } else if ("installs".equals(cmd)) {
22625                dumpState.setDump(DumpState.DUMP_INSTALLS);
22626            } else if ("frozen".equals(cmd)) {
22627                dumpState.setDump(DumpState.DUMP_FROZEN);
22628            } else if ("volumes".equals(cmd)) {
22629                dumpState.setDump(DumpState.DUMP_VOLUMES);
22630            } else if ("dexopt".equals(cmd)) {
22631                dumpState.setDump(DumpState.DUMP_DEXOPT);
22632            } else if ("compiler-stats".equals(cmd)) {
22633                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
22634            } else if ("changes".equals(cmd)) {
22635                dumpState.setDump(DumpState.DUMP_CHANGES);
22636            } else if ("write".equals(cmd)) {
22637                synchronized (mPackages) {
22638                    mSettings.writeLPr();
22639                    pw.println("Settings written.");
22640                    return;
22641                }
22642            }
22643        }
22644
22645        if (checkin) {
22646            pw.println("vers,1");
22647        }
22648
22649        // reader
22650        synchronized (mPackages) {
22651            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
22652                if (!checkin) {
22653                    if (dumpState.onTitlePrinted())
22654                        pw.println();
22655                    pw.println("Database versions:");
22656                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
22657                }
22658            }
22659
22660            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
22661                if (!checkin) {
22662                    if (dumpState.onTitlePrinted())
22663                        pw.println();
22664                    pw.println("Verifiers:");
22665                    pw.print("  Required: ");
22666                    pw.print(mRequiredVerifierPackage);
22667                    pw.print(" (uid=");
22668                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22669                            UserHandle.USER_SYSTEM));
22670                    pw.println(")");
22671                } else if (mRequiredVerifierPackage != null) {
22672                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
22673                    pw.print(",");
22674                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22675                            UserHandle.USER_SYSTEM));
22676                }
22677            }
22678
22679            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
22680                    packageName == null) {
22681                if (mIntentFilterVerifierComponent != null) {
22682                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22683                    if (!checkin) {
22684                        if (dumpState.onTitlePrinted())
22685                            pw.println();
22686                        pw.println("Intent Filter Verifier:");
22687                        pw.print("  Using: ");
22688                        pw.print(verifierPackageName);
22689                        pw.print(" (uid=");
22690                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22691                                UserHandle.USER_SYSTEM));
22692                        pw.println(")");
22693                    } else if (verifierPackageName != null) {
22694                        pw.print("ifv,"); pw.print(verifierPackageName);
22695                        pw.print(",");
22696                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22697                                UserHandle.USER_SYSTEM));
22698                    }
22699                } else {
22700                    pw.println();
22701                    pw.println("No Intent Filter Verifier available!");
22702                }
22703            }
22704
22705            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
22706                boolean printedHeader = false;
22707                final Iterator<String> it = mSharedLibraries.keySet().iterator();
22708                while (it.hasNext()) {
22709                    String libName = it.next();
22710                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22711                    if (versionedLib == null) {
22712                        continue;
22713                    }
22714                    final int versionCount = versionedLib.size();
22715                    for (int i = 0; i < versionCount; i++) {
22716                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
22717                        if (!checkin) {
22718                            if (!printedHeader) {
22719                                if (dumpState.onTitlePrinted())
22720                                    pw.println();
22721                                pw.println("Libraries:");
22722                                printedHeader = true;
22723                            }
22724                            pw.print("  ");
22725                        } else {
22726                            pw.print("lib,");
22727                        }
22728                        pw.print(libEntry.info.getName());
22729                        if (libEntry.info.isStatic()) {
22730                            pw.print(" version=" + libEntry.info.getVersion());
22731                        }
22732                        if (!checkin) {
22733                            pw.print(" -> ");
22734                        }
22735                        if (libEntry.path != null) {
22736                            pw.print(" (jar) ");
22737                            pw.print(libEntry.path);
22738                        } else {
22739                            pw.print(" (apk) ");
22740                            pw.print(libEntry.apk);
22741                        }
22742                        pw.println();
22743                    }
22744                }
22745            }
22746
22747            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
22748                if (dumpState.onTitlePrinted())
22749                    pw.println();
22750                if (!checkin) {
22751                    pw.println("Features:");
22752                }
22753
22754                synchronized (mAvailableFeatures) {
22755                    for (FeatureInfo feat : mAvailableFeatures.values()) {
22756                        if (checkin) {
22757                            pw.print("feat,");
22758                            pw.print(feat.name);
22759                            pw.print(",");
22760                            pw.println(feat.version);
22761                        } else {
22762                            pw.print("  ");
22763                            pw.print(feat.name);
22764                            if (feat.version > 0) {
22765                                pw.print(" version=");
22766                                pw.print(feat.version);
22767                            }
22768                            pw.println();
22769                        }
22770                    }
22771                }
22772            }
22773
22774            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
22775                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
22776                        : "Activity Resolver Table:", "  ", packageName,
22777                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22778                    dumpState.setTitlePrinted(true);
22779                }
22780            }
22781            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
22782                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
22783                        : "Receiver Resolver Table:", "  ", packageName,
22784                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22785                    dumpState.setTitlePrinted(true);
22786                }
22787            }
22788            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
22789                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
22790                        : "Service Resolver Table:", "  ", packageName,
22791                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22792                    dumpState.setTitlePrinted(true);
22793                }
22794            }
22795            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
22796                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
22797                        : "Provider Resolver Table:", "  ", packageName,
22798                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22799                    dumpState.setTitlePrinted(true);
22800                }
22801            }
22802
22803            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22804                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22805                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22806                    int user = mSettings.mPreferredActivities.keyAt(i);
22807                    if (pir.dump(pw,
22808                            dumpState.getTitlePrinted()
22809                                ? "\nPreferred Activities User " + user + ":"
22810                                : "Preferred Activities User " + user + ":", "  ",
22811                            packageName, true, false)) {
22812                        dumpState.setTitlePrinted(true);
22813                    }
22814                }
22815            }
22816
22817            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22818                pw.flush();
22819                FileOutputStream fout = new FileOutputStream(fd);
22820                BufferedOutputStream str = new BufferedOutputStream(fout);
22821                XmlSerializer serializer = new FastXmlSerializer();
22822                try {
22823                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
22824                    serializer.startDocument(null, true);
22825                    serializer.setFeature(
22826                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22827                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22828                    serializer.endDocument();
22829                    serializer.flush();
22830                } catch (IllegalArgumentException e) {
22831                    pw.println("Failed writing: " + e);
22832                } catch (IllegalStateException e) {
22833                    pw.println("Failed writing: " + e);
22834                } catch (IOException e) {
22835                    pw.println("Failed writing: " + e);
22836                }
22837            }
22838
22839            if (!checkin
22840                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22841                    && packageName == null) {
22842                pw.println();
22843                int count = mSettings.mPackages.size();
22844                if (count == 0) {
22845                    pw.println("No applications!");
22846                    pw.println();
22847                } else {
22848                    final String prefix = "  ";
22849                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22850                    if (allPackageSettings.size() == 0) {
22851                        pw.println("No domain preferred apps!");
22852                        pw.println();
22853                    } else {
22854                        pw.println("App verification status:");
22855                        pw.println();
22856                        count = 0;
22857                        for (PackageSetting ps : allPackageSettings) {
22858                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22859                            if (ivi == null || ivi.getPackageName() == null) continue;
22860                            pw.println(prefix + "Package: " + ivi.getPackageName());
22861                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
22862                            pw.println(prefix + "Status:  " + ivi.getStatusString());
22863                            pw.println();
22864                            count++;
22865                        }
22866                        if (count == 0) {
22867                            pw.println(prefix + "No app verification established.");
22868                            pw.println();
22869                        }
22870                        for (int userId : sUserManager.getUserIds()) {
22871                            pw.println("App linkages for user " + userId + ":");
22872                            pw.println();
22873                            count = 0;
22874                            for (PackageSetting ps : allPackageSettings) {
22875                                final long status = ps.getDomainVerificationStatusForUser(userId);
22876                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22877                                        && !DEBUG_DOMAIN_VERIFICATION) {
22878                                    continue;
22879                                }
22880                                pw.println(prefix + "Package: " + ps.name);
22881                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22882                                String statusStr = IntentFilterVerificationInfo.
22883                                        getStatusStringFromValue(status);
22884                                pw.println(prefix + "Status:  " + statusStr);
22885                                pw.println();
22886                                count++;
22887                            }
22888                            if (count == 0) {
22889                                pw.println(prefix + "No configured app linkages.");
22890                                pw.println();
22891                            }
22892                        }
22893                    }
22894                }
22895            }
22896
22897            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22898                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22899                if (packageName == null && permissionNames == null) {
22900                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22901                        if (iperm == 0) {
22902                            if (dumpState.onTitlePrinted())
22903                                pw.println();
22904                            pw.println("AppOp Permissions:");
22905                        }
22906                        pw.print("  AppOp Permission ");
22907                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
22908                        pw.println(":");
22909                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
22910                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
22911                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
22912                        }
22913                    }
22914                }
22915            }
22916
22917            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
22918                boolean printedSomething = false;
22919                for (PackageParser.Provider p : mProviders.mProviders.values()) {
22920                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22921                        continue;
22922                    }
22923                    if (!printedSomething) {
22924                        if (dumpState.onTitlePrinted())
22925                            pw.println();
22926                        pw.println("Registered ContentProviders:");
22927                        printedSomething = true;
22928                    }
22929                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
22930                    pw.print("    "); pw.println(p.toString());
22931                }
22932                printedSomething = false;
22933                for (Map.Entry<String, PackageParser.Provider> entry :
22934                        mProvidersByAuthority.entrySet()) {
22935                    PackageParser.Provider p = entry.getValue();
22936                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22937                        continue;
22938                    }
22939                    if (!printedSomething) {
22940                        if (dumpState.onTitlePrinted())
22941                            pw.println();
22942                        pw.println("ContentProvider Authorities:");
22943                        printedSomething = true;
22944                    }
22945                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
22946                    pw.print("    "); pw.println(p.toString());
22947                    if (p.info != null && p.info.applicationInfo != null) {
22948                        final String appInfo = p.info.applicationInfo.toString();
22949                        pw.print("      applicationInfo="); pw.println(appInfo);
22950                    }
22951                }
22952            }
22953
22954            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
22955                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
22956            }
22957
22958            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
22959                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
22960            }
22961
22962            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
22963                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
22964            }
22965
22966            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
22967                if (dumpState.onTitlePrinted()) pw.println();
22968                pw.println("Package Changes:");
22969                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
22970                final int K = mChangedPackages.size();
22971                for (int i = 0; i < K; i++) {
22972                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
22973                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
22974                    final int N = changes.size();
22975                    if (N == 0) {
22976                        pw.print("    "); pw.println("No packages changed");
22977                    } else {
22978                        for (int j = 0; j < N; j++) {
22979                            final String pkgName = changes.valueAt(j);
22980                            final int sequenceNumber = changes.keyAt(j);
22981                            pw.print("    ");
22982                            pw.print("seq=");
22983                            pw.print(sequenceNumber);
22984                            pw.print(", package=");
22985                            pw.println(pkgName);
22986                        }
22987                    }
22988                }
22989            }
22990
22991            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
22992                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
22993            }
22994
22995            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
22996                // XXX should handle packageName != null by dumping only install data that
22997                // the given package is involved with.
22998                if (dumpState.onTitlePrinted()) pw.println();
22999
23000                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
23001                ipw.println();
23002                ipw.println("Frozen packages:");
23003                ipw.increaseIndent();
23004                if (mFrozenPackages.size() == 0) {
23005                    ipw.println("(none)");
23006                } else {
23007                    for (int i = 0; i < mFrozenPackages.size(); i++) {
23008                        ipw.println(mFrozenPackages.valueAt(i));
23009                    }
23010                }
23011                ipw.decreaseIndent();
23012            }
23013
23014            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
23015                if (dumpState.onTitlePrinted()) pw.println();
23016
23017                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
23018                ipw.println();
23019                ipw.println("Loaded volumes:");
23020                ipw.increaseIndent();
23021                if (mLoadedVolumes.size() == 0) {
23022                    ipw.println("(none)");
23023                } else {
23024                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
23025                        ipw.println(mLoadedVolumes.valueAt(i));
23026                    }
23027                }
23028                ipw.decreaseIndent();
23029            }
23030
23031            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
23032                if (dumpState.onTitlePrinted()) pw.println();
23033                dumpDexoptStateLPr(pw, packageName);
23034            }
23035
23036            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
23037                if (dumpState.onTitlePrinted()) pw.println();
23038                dumpCompilerStatsLPr(pw, packageName);
23039            }
23040
23041            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
23042                if (dumpState.onTitlePrinted()) pw.println();
23043                mSettings.dumpReadMessagesLPr(pw, dumpState);
23044
23045                pw.println();
23046                pw.println("Package warning messages:");
23047                BufferedReader in = null;
23048                String line = null;
23049                try {
23050                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
23051                    while ((line = in.readLine()) != null) {
23052                        if (line.contains("ignored: updated version")) continue;
23053                        pw.println(line);
23054                    }
23055                } catch (IOException ignored) {
23056                } finally {
23057                    IoUtils.closeQuietly(in);
23058                }
23059            }
23060
23061            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
23062                BufferedReader in = null;
23063                String line = null;
23064                try {
23065                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
23066                    while ((line = in.readLine()) != null) {
23067                        if (line.contains("ignored: updated version")) continue;
23068                        pw.print("msg,");
23069                        pw.println(line);
23070                    }
23071                } catch (IOException ignored) {
23072                } finally {
23073                    IoUtils.closeQuietly(in);
23074                }
23075            }
23076        }
23077
23078        // PackageInstaller should be called outside of mPackages lock
23079        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
23080            // XXX should handle packageName != null by dumping only install data that
23081            // the given package is involved with.
23082            if (dumpState.onTitlePrinted()) pw.println();
23083            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
23084        }
23085    }
23086
23087    private void dumpProto(FileDescriptor fd) {
23088        final ProtoOutputStream proto = new ProtoOutputStream(fd);
23089
23090        synchronized (mPackages) {
23091            final long requiredVerifierPackageToken =
23092                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
23093            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
23094            proto.write(
23095                    PackageServiceDumpProto.PackageShortProto.UID,
23096                    getPackageUid(
23097                            mRequiredVerifierPackage,
23098                            MATCH_DEBUG_TRIAGED_MISSING,
23099                            UserHandle.USER_SYSTEM));
23100            proto.end(requiredVerifierPackageToken);
23101
23102            if (mIntentFilterVerifierComponent != null) {
23103                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
23104                final long verifierPackageToken =
23105                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
23106                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
23107                proto.write(
23108                        PackageServiceDumpProto.PackageShortProto.UID,
23109                        getPackageUid(
23110                                verifierPackageName,
23111                                MATCH_DEBUG_TRIAGED_MISSING,
23112                                UserHandle.USER_SYSTEM));
23113                proto.end(verifierPackageToken);
23114            }
23115
23116            dumpSharedLibrariesProto(proto);
23117            dumpFeaturesProto(proto);
23118            mSettings.dumpPackagesProto(proto);
23119            mSettings.dumpSharedUsersProto(proto);
23120            dumpMessagesProto(proto);
23121        }
23122        proto.flush();
23123    }
23124
23125    private void dumpMessagesProto(ProtoOutputStream proto) {
23126        BufferedReader in = null;
23127        String line = null;
23128        try {
23129            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
23130            while ((line = in.readLine()) != null) {
23131                if (line.contains("ignored: updated version")) continue;
23132                proto.write(PackageServiceDumpProto.MESSAGES, line);
23133            }
23134        } catch (IOException ignored) {
23135        } finally {
23136            IoUtils.closeQuietly(in);
23137        }
23138    }
23139
23140    private void dumpFeaturesProto(ProtoOutputStream proto) {
23141        synchronized (mAvailableFeatures) {
23142            final int count = mAvailableFeatures.size();
23143            for (int i = 0; i < count; i++) {
23144                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
23145                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
23146                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
23147                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
23148                proto.end(featureToken);
23149            }
23150        }
23151    }
23152
23153    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
23154        final int count = mSharedLibraries.size();
23155        for (int i = 0; i < count; i++) {
23156            final String libName = mSharedLibraries.keyAt(i);
23157            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
23158            if (versionedLib == null) {
23159                continue;
23160            }
23161            final int versionCount = versionedLib.size();
23162            for (int j = 0; j < versionCount; j++) {
23163                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
23164                final long sharedLibraryToken =
23165                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
23166                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
23167                final boolean isJar = (libEntry.path != null);
23168                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
23169                if (isJar) {
23170                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
23171                } else {
23172                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
23173                }
23174                proto.end(sharedLibraryToken);
23175            }
23176        }
23177    }
23178
23179    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
23180        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
23181        ipw.println();
23182        ipw.println("Dexopt state:");
23183        ipw.increaseIndent();
23184        Collection<PackageParser.Package> packages = null;
23185        if (packageName != null) {
23186            PackageParser.Package targetPackage = mPackages.get(packageName);
23187            if (targetPackage != null) {
23188                packages = Collections.singletonList(targetPackage);
23189            } else {
23190                ipw.println("Unable to find package: " + packageName);
23191                return;
23192            }
23193        } else {
23194            packages = mPackages.values();
23195        }
23196
23197        for (PackageParser.Package pkg : packages) {
23198            ipw.println("[" + pkg.packageName + "]");
23199            ipw.increaseIndent();
23200            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
23201                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
23202            ipw.decreaseIndent();
23203        }
23204    }
23205
23206    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
23207        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
23208        ipw.println();
23209        ipw.println("Compiler stats:");
23210        ipw.increaseIndent();
23211        Collection<PackageParser.Package> packages = null;
23212        if (packageName != null) {
23213            PackageParser.Package targetPackage = mPackages.get(packageName);
23214            if (targetPackage != null) {
23215                packages = Collections.singletonList(targetPackage);
23216            } else {
23217                ipw.println("Unable to find package: " + packageName);
23218                return;
23219            }
23220        } else {
23221            packages = mPackages.values();
23222        }
23223
23224        for (PackageParser.Package pkg : packages) {
23225            ipw.println("[" + pkg.packageName + "]");
23226            ipw.increaseIndent();
23227
23228            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
23229            if (stats == null) {
23230                ipw.println("(No recorded stats)");
23231            } else {
23232                stats.dump(ipw);
23233            }
23234            ipw.decreaseIndent();
23235        }
23236    }
23237
23238    private String dumpDomainString(String packageName) {
23239        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
23240                .getList();
23241        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
23242
23243        ArraySet<String> result = new ArraySet<>();
23244        if (iviList.size() > 0) {
23245            for (IntentFilterVerificationInfo ivi : iviList) {
23246                for (String host : ivi.getDomains()) {
23247                    result.add(host);
23248                }
23249            }
23250        }
23251        if (filters != null && filters.size() > 0) {
23252            for (IntentFilter filter : filters) {
23253                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
23254                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
23255                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
23256                    result.addAll(filter.getHostsList());
23257                }
23258            }
23259        }
23260
23261        StringBuilder sb = new StringBuilder(result.size() * 16);
23262        for (String domain : result) {
23263            if (sb.length() > 0) sb.append(" ");
23264            sb.append(domain);
23265        }
23266        return sb.toString();
23267    }
23268
23269    // ------- apps on sdcard specific code -------
23270    static final boolean DEBUG_SD_INSTALL = false;
23271
23272    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
23273
23274    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
23275
23276    private boolean mMediaMounted = false;
23277
23278    static String getEncryptKey() {
23279        try {
23280            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
23281                    SD_ENCRYPTION_KEYSTORE_NAME);
23282            if (sdEncKey == null) {
23283                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
23284                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
23285                if (sdEncKey == null) {
23286                    Slog.e(TAG, "Failed to create encryption keys");
23287                    return null;
23288                }
23289            }
23290            return sdEncKey;
23291        } catch (NoSuchAlgorithmException nsae) {
23292            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
23293            return null;
23294        } catch (IOException ioe) {
23295            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
23296            return null;
23297        }
23298    }
23299
23300    /*
23301     * Update media status on PackageManager.
23302     */
23303    @Override
23304    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
23305        enforceSystemOrRoot("Media status can only be updated by the system");
23306        // reader; this apparently protects mMediaMounted, but should probably
23307        // be a different lock in that case.
23308        synchronized (mPackages) {
23309            Log.i(TAG, "Updating external media status from "
23310                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
23311                    + (mediaStatus ? "mounted" : "unmounted"));
23312            if (DEBUG_SD_INSTALL)
23313                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
23314                        + ", mMediaMounted=" + mMediaMounted);
23315            if (mediaStatus == mMediaMounted) {
23316                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
23317                        : 0, -1);
23318                mHandler.sendMessage(msg);
23319                return;
23320            }
23321            mMediaMounted = mediaStatus;
23322        }
23323        // Queue up an async operation since the package installation may take a
23324        // little while.
23325        mHandler.post(new Runnable() {
23326            public void run() {
23327                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
23328            }
23329        });
23330    }
23331
23332    /**
23333     * Called by StorageManagerService when the initial ASECs to scan are available.
23334     * Should block until all the ASEC containers are finished being scanned.
23335     */
23336    public void scanAvailableAsecs() {
23337        updateExternalMediaStatusInner(true, false, false);
23338    }
23339
23340    /*
23341     * Collect information of applications on external media, map them against
23342     * existing containers and update information based on current mount status.
23343     * Please note that we always have to report status if reportStatus has been
23344     * set to true especially when unloading packages.
23345     */
23346    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
23347            boolean externalStorage) {
23348        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
23349        int[] uidArr = EmptyArray.INT;
23350
23351        final String[] list = PackageHelper.getSecureContainerList();
23352        if (ArrayUtils.isEmpty(list)) {
23353            Log.i(TAG, "No secure containers found");
23354        } else {
23355            // Process list of secure containers and categorize them
23356            // as active or stale based on their package internal state.
23357
23358            // reader
23359            synchronized (mPackages) {
23360                for (String cid : list) {
23361                    // Leave stages untouched for now; installer service owns them
23362                    if (PackageInstallerService.isStageName(cid)) continue;
23363
23364                    if (DEBUG_SD_INSTALL)
23365                        Log.i(TAG, "Processing container " + cid);
23366                    String pkgName = getAsecPackageName(cid);
23367                    if (pkgName == null) {
23368                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
23369                        continue;
23370                    }
23371                    if (DEBUG_SD_INSTALL)
23372                        Log.i(TAG, "Looking for pkg : " + pkgName);
23373
23374                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
23375                    if (ps == null) {
23376                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
23377                        continue;
23378                    }
23379
23380                    /*
23381                     * Skip packages that are not external if we're unmounting
23382                     * external storage.
23383                     */
23384                    if (externalStorage && !isMounted && !isExternal(ps)) {
23385                        continue;
23386                    }
23387
23388                    final AsecInstallArgs args = new AsecInstallArgs(cid,
23389                            getAppDexInstructionSets(ps), ps.isForwardLocked());
23390                    // The package status is changed only if the code path
23391                    // matches between settings and the container id.
23392                    if (ps.codePathString != null
23393                            && ps.codePathString.startsWith(args.getCodePath())) {
23394                        if (DEBUG_SD_INSTALL) {
23395                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
23396                                    + " at code path: " + ps.codePathString);
23397                        }
23398
23399                        // We do have a valid package installed on sdcard
23400                        processCids.put(args, ps.codePathString);
23401                        final int uid = ps.appId;
23402                        if (uid != -1) {
23403                            uidArr = ArrayUtils.appendInt(uidArr, uid);
23404                        }
23405                    } else {
23406                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
23407                                + ps.codePathString);
23408                    }
23409                }
23410            }
23411
23412            Arrays.sort(uidArr);
23413        }
23414
23415        // Process packages with valid entries.
23416        if (isMounted) {
23417            if (DEBUG_SD_INSTALL)
23418                Log.i(TAG, "Loading packages");
23419            loadMediaPackages(processCids, uidArr, externalStorage);
23420            startCleaningPackages();
23421            mInstallerService.onSecureContainersAvailable();
23422        } else {
23423            if (DEBUG_SD_INSTALL)
23424                Log.i(TAG, "Unloading packages");
23425            unloadMediaPackages(processCids, uidArr, reportStatus);
23426        }
23427    }
23428
23429    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23430            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
23431        final int size = infos.size();
23432        final String[] packageNames = new String[size];
23433        final int[] packageUids = new int[size];
23434        for (int i = 0; i < size; i++) {
23435            final ApplicationInfo info = infos.get(i);
23436            packageNames[i] = info.packageName;
23437            packageUids[i] = info.uid;
23438        }
23439        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
23440                finishedReceiver);
23441    }
23442
23443    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23444            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
23445        sendResourcesChangedBroadcast(mediaStatus, replacing,
23446                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
23447    }
23448
23449    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23450            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
23451        int size = pkgList.length;
23452        if (size > 0) {
23453            // Send broadcasts here
23454            Bundle extras = new Bundle();
23455            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
23456            if (uidArr != null) {
23457                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
23458            }
23459            if (replacing) {
23460                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
23461            }
23462            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
23463                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
23464            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
23465        }
23466    }
23467
23468   /*
23469     * Look at potentially valid container ids from processCids If package
23470     * information doesn't match the one on record or package scanning fails,
23471     * the cid is added to list of removeCids. We currently don't delete stale
23472     * containers.
23473     */
23474    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
23475            boolean externalStorage) {
23476        ArrayList<String> pkgList = new ArrayList<String>();
23477        Set<AsecInstallArgs> keys = processCids.keySet();
23478
23479        for (AsecInstallArgs args : keys) {
23480            String codePath = processCids.get(args);
23481            if (DEBUG_SD_INSTALL)
23482                Log.i(TAG, "Loading container : " + args.cid);
23483            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
23484            try {
23485                // Make sure there are no container errors first.
23486                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
23487                    Slog.e(TAG, "Failed to mount cid : " + args.cid
23488                            + " when installing from sdcard");
23489                    continue;
23490                }
23491                // Check code path here.
23492                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
23493                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
23494                            + " does not match one in settings " + codePath);
23495                    continue;
23496                }
23497                // Parse package
23498                int parseFlags = mDefParseFlags;
23499                if (args.isExternalAsec()) {
23500                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
23501                }
23502                if (args.isFwdLocked()) {
23503                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
23504                }
23505
23506                synchronized (mInstallLock) {
23507                    PackageParser.Package pkg = null;
23508                    try {
23509                        // Sadly we don't know the package name yet to freeze it
23510                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
23511                                SCAN_IGNORE_FROZEN, 0, null);
23512                    } catch (PackageManagerException e) {
23513                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
23514                    }
23515                    // Scan the package
23516                    if (pkg != null) {
23517                        /*
23518                         * TODO why is the lock being held? doPostInstall is
23519                         * called in other places without the lock. This needs
23520                         * to be straightened out.
23521                         */
23522                        // writer
23523                        synchronized (mPackages) {
23524                            retCode = PackageManager.INSTALL_SUCCEEDED;
23525                            pkgList.add(pkg.packageName);
23526                            // Post process args
23527                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
23528                                    pkg.applicationInfo.uid);
23529                        }
23530                    } else {
23531                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
23532                    }
23533                }
23534
23535            } finally {
23536                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
23537                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
23538                }
23539            }
23540        }
23541        // writer
23542        synchronized (mPackages) {
23543            // If the platform SDK has changed since the last time we booted,
23544            // we need to re-grant app permission to catch any new ones that
23545            // appear. This is really a hack, and means that apps can in some
23546            // cases get permissions that the user didn't initially explicitly
23547            // allow... it would be nice to have some better way to handle
23548            // this situation.
23549            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
23550                    : mSettings.getInternalVersion();
23551            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
23552                    : StorageManager.UUID_PRIVATE_INTERNAL;
23553
23554            int updateFlags = UPDATE_PERMISSIONS_ALL;
23555            if (ver.sdkVersion != mSdkVersion) {
23556                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23557                        + mSdkVersion + "; regranting permissions for external");
23558                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23559            }
23560            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23561
23562            // Yay, everything is now upgraded
23563            ver.forceCurrent();
23564
23565            // can downgrade to reader
23566            // Persist settings
23567            mSettings.writeLPr();
23568        }
23569        // Send a broadcast to let everyone know we are done processing
23570        if (pkgList.size() > 0) {
23571            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
23572        }
23573    }
23574
23575   /*
23576     * Utility method to unload a list of specified containers
23577     */
23578    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
23579        // Just unmount all valid containers.
23580        for (AsecInstallArgs arg : cidArgs) {
23581            synchronized (mInstallLock) {
23582                arg.doPostDeleteLI(false);
23583           }
23584       }
23585   }
23586
23587    /*
23588     * Unload packages mounted on external media. This involves deleting package
23589     * data from internal structures, sending broadcasts about disabled packages,
23590     * gc'ing to free up references, unmounting all secure containers
23591     * corresponding to packages on external media, and posting a
23592     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
23593     * that we always have to post this message if status has been requested no
23594     * matter what.
23595     */
23596    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
23597            final boolean reportStatus) {
23598        if (DEBUG_SD_INSTALL)
23599            Log.i(TAG, "unloading media packages");
23600        ArrayList<String> pkgList = new ArrayList<String>();
23601        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
23602        final Set<AsecInstallArgs> keys = processCids.keySet();
23603        for (AsecInstallArgs args : keys) {
23604            String pkgName = args.getPackageName();
23605            if (DEBUG_SD_INSTALL)
23606                Log.i(TAG, "Trying to unload pkg : " + pkgName);
23607            // Delete package internally
23608            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23609            synchronized (mInstallLock) {
23610                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23611                final boolean res;
23612                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
23613                        "unloadMediaPackages")) {
23614                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
23615                            null);
23616                }
23617                if (res) {
23618                    pkgList.add(pkgName);
23619                } else {
23620                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
23621                    failedList.add(args);
23622                }
23623            }
23624        }
23625
23626        // reader
23627        synchronized (mPackages) {
23628            // We didn't update the settings after removing each package;
23629            // write them now for all packages.
23630            mSettings.writeLPr();
23631        }
23632
23633        // We have to absolutely send UPDATED_MEDIA_STATUS only
23634        // after confirming that all the receivers processed the ordered
23635        // broadcast when packages get disabled, force a gc to clean things up.
23636        // and unload all the containers.
23637        if (pkgList.size() > 0) {
23638            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
23639                    new IIntentReceiver.Stub() {
23640                public void performReceive(Intent intent, int resultCode, String data,
23641                        Bundle extras, boolean ordered, boolean sticky,
23642                        int sendingUser) throws RemoteException {
23643                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
23644                            reportStatus ? 1 : 0, 1, keys);
23645                    mHandler.sendMessage(msg);
23646                }
23647            });
23648        } else {
23649            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
23650                    keys);
23651            mHandler.sendMessage(msg);
23652        }
23653    }
23654
23655    private void loadPrivatePackages(final VolumeInfo vol) {
23656        mHandler.post(new Runnable() {
23657            @Override
23658            public void run() {
23659                loadPrivatePackagesInner(vol);
23660            }
23661        });
23662    }
23663
23664    private void loadPrivatePackagesInner(VolumeInfo vol) {
23665        final String volumeUuid = vol.fsUuid;
23666        if (TextUtils.isEmpty(volumeUuid)) {
23667            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
23668            return;
23669        }
23670
23671        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
23672        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
23673        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
23674
23675        final VersionInfo ver;
23676        final List<PackageSetting> packages;
23677        synchronized (mPackages) {
23678            ver = mSettings.findOrCreateVersion(volumeUuid);
23679            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23680        }
23681
23682        for (PackageSetting ps : packages) {
23683            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
23684            synchronized (mInstallLock) {
23685                final PackageParser.Package pkg;
23686                try {
23687                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
23688                    loaded.add(pkg.applicationInfo);
23689
23690                } catch (PackageManagerException e) {
23691                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
23692                }
23693
23694                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
23695                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
23696                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
23697                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
23698                }
23699            }
23700        }
23701
23702        // Reconcile app data for all started/unlocked users
23703        final StorageManager sm = mContext.getSystemService(StorageManager.class);
23704        final UserManager um = mContext.getSystemService(UserManager.class);
23705        UserManagerInternal umInternal = getUserManagerInternal();
23706        for (UserInfo user : um.getUsers()) {
23707            final int flags;
23708            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23709                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23710            } else if (umInternal.isUserRunning(user.id)) {
23711                flags = StorageManager.FLAG_STORAGE_DE;
23712            } else {
23713                continue;
23714            }
23715
23716            try {
23717                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
23718                synchronized (mInstallLock) {
23719                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
23720                }
23721            } catch (IllegalStateException e) {
23722                // Device was probably ejected, and we'll process that event momentarily
23723                Slog.w(TAG, "Failed to prepare storage: " + e);
23724            }
23725        }
23726
23727        synchronized (mPackages) {
23728            int updateFlags = UPDATE_PERMISSIONS_ALL;
23729            if (ver.sdkVersion != mSdkVersion) {
23730                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23731                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
23732                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23733            }
23734            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23735
23736            // Yay, everything is now upgraded
23737            ver.forceCurrent();
23738
23739            mSettings.writeLPr();
23740        }
23741
23742        for (PackageFreezer freezer : freezers) {
23743            freezer.close();
23744        }
23745
23746        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
23747        sendResourcesChangedBroadcast(true, false, loaded, null);
23748        mLoadedVolumes.add(vol.getId());
23749    }
23750
23751    private void unloadPrivatePackages(final VolumeInfo vol) {
23752        mHandler.post(new Runnable() {
23753            @Override
23754            public void run() {
23755                unloadPrivatePackagesInner(vol);
23756            }
23757        });
23758    }
23759
23760    private void unloadPrivatePackagesInner(VolumeInfo vol) {
23761        final String volumeUuid = vol.fsUuid;
23762        if (TextUtils.isEmpty(volumeUuid)) {
23763            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
23764            return;
23765        }
23766
23767        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
23768        synchronized (mInstallLock) {
23769        synchronized (mPackages) {
23770            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
23771            for (PackageSetting ps : packages) {
23772                if (ps.pkg == null) continue;
23773
23774                final ApplicationInfo info = ps.pkg.applicationInfo;
23775                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23776                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23777
23778                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
23779                        "unloadPrivatePackagesInner")) {
23780                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
23781                            false, null)) {
23782                        unloaded.add(info);
23783                    } else {
23784                        Slog.w(TAG, "Failed to unload " + ps.codePath);
23785                    }
23786                }
23787
23788                // Try very hard to release any references to this package
23789                // so we don't risk the system server being killed due to
23790                // open FDs
23791                AttributeCache.instance().removePackage(ps.name);
23792            }
23793
23794            mSettings.writeLPr();
23795        }
23796        }
23797
23798        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
23799        sendResourcesChangedBroadcast(false, false, unloaded, null);
23800        mLoadedVolumes.remove(vol.getId());
23801
23802        // Try very hard to release any references to this path so we don't risk
23803        // the system server being killed due to open FDs
23804        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
23805
23806        for (int i = 0; i < 3; i++) {
23807            System.gc();
23808            System.runFinalization();
23809        }
23810    }
23811
23812    private void assertPackageKnown(String volumeUuid, String packageName)
23813            throws PackageManagerException {
23814        synchronized (mPackages) {
23815            // Normalize package name to handle renamed packages
23816            packageName = normalizePackageNameLPr(packageName);
23817
23818            final PackageSetting ps = mSettings.mPackages.get(packageName);
23819            if (ps == null) {
23820                throw new PackageManagerException("Package " + packageName + " is unknown");
23821            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23822                throw new PackageManagerException(
23823                        "Package " + packageName + " found on unknown volume " + volumeUuid
23824                                + "; expected volume " + ps.volumeUuid);
23825            }
23826        }
23827    }
23828
23829    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23830            throws PackageManagerException {
23831        synchronized (mPackages) {
23832            // Normalize package name to handle renamed packages
23833            packageName = normalizePackageNameLPr(packageName);
23834
23835            final PackageSetting ps = mSettings.mPackages.get(packageName);
23836            if (ps == null) {
23837                throw new PackageManagerException("Package " + packageName + " is unknown");
23838            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23839                throw new PackageManagerException(
23840                        "Package " + packageName + " found on unknown volume " + volumeUuid
23841                                + "; expected volume " + ps.volumeUuid);
23842            } else if (!ps.getInstalled(userId)) {
23843                throw new PackageManagerException(
23844                        "Package " + packageName + " not installed for user " + userId);
23845            }
23846        }
23847    }
23848
23849    private List<String> collectAbsoluteCodePaths() {
23850        synchronized (mPackages) {
23851            List<String> codePaths = new ArrayList<>();
23852            final int packageCount = mSettings.mPackages.size();
23853            for (int i = 0; i < packageCount; i++) {
23854                final PackageSetting ps = mSettings.mPackages.valueAt(i);
23855                codePaths.add(ps.codePath.getAbsolutePath());
23856            }
23857            return codePaths;
23858        }
23859    }
23860
23861    /**
23862     * Examine all apps present on given mounted volume, and destroy apps that
23863     * aren't expected, either due to uninstallation or reinstallation on
23864     * another volume.
23865     */
23866    private void reconcileApps(String volumeUuid) {
23867        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
23868        List<File> filesToDelete = null;
23869
23870        final File[] files = FileUtils.listFilesOrEmpty(
23871                Environment.getDataAppDirectory(volumeUuid));
23872        for (File file : files) {
23873            final boolean isPackage = (isApkFile(file) || file.isDirectory())
23874                    && !PackageInstallerService.isStageName(file.getName());
23875            if (!isPackage) {
23876                // Ignore entries which are not packages
23877                continue;
23878            }
23879
23880            String absolutePath = file.getAbsolutePath();
23881
23882            boolean pathValid = false;
23883            final int absoluteCodePathCount = absoluteCodePaths.size();
23884            for (int i = 0; i < absoluteCodePathCount; i++) {
23885                String absoluteCodePath = absoluteCodePaths.get(i);
23886                if (absolutePath.startsWith(absoluteCodePath)) {
23887                    pathValid = true;
23888                    break;
23889                }
23890            }
23891
23892            if (!pathValid) {
23893                if (filesToDelete == null) {
23894                    filesToDelete = new ArrayList<>();
23895                }
23896                filesToDelete.add(file);
23897            }
23898        }
23899
23900        if (filesToDelete != null) {
23901            final int fileToDeleteCount = filesToDelete.size();
23902            for (int i = 0; i < fileToDeleteCount; i++) {
23903                File fileToDelete = filesToDelete.get(i);
23904                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23905                synchronized (mInstallLock) {
23906                    removeCodePathLI(fileToDelete);
23907                }
23908            }
23909        }
23910    }
23911
23912    /**
23913     * Reconcile all app data for the given user.
23914     * <p>
23915     * Verifies that directories exist and that ownership and labeling is
23916     * correct for all installed apps on all mounted volumes.
23917     */
23918    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
23919        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23920        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
23921            final String volumeUuid = vol.getFsUuid();
23922            synchronized (mInstallLock) {
23923                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
23924            }
23925        }
23926    }
23927
23928    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23929            boolean migrateAppData) {
23930        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
23931    }
23932
23933    /**
23934     * Reconcile all app data on given mounted volume.
23935     * <p>
23936     * Destroys app data that isn't expected, either due to uninstallation or
23937     * reinstallation on another volume.
23938     * <p>
23939     * Verifies that directories exist and that ownership and labeling is
23940     * correct for all installed apps.
23941     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
23942     */
23943    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23944            boolean migrateAppData, boolean onlyCoreApps) {
23945        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
23946                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
23947        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
23948
23949        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
23950        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
23951
23952        // First look for stale data that doesn't belong, and check if things
23953        // have changed since we did our last restorecon
23954        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23955            if (StorageManager.isFileEncryptedNativeOrEmulated()
23956                    && !StorageManager.isUserKeyUnlocked(userId)) {
23957                throw new RuntimeException(
23958                        "Yikes, someone asked us to reconcile CE storage while " + userId
23959                                + " was still locked; this would have caused massive data loss!");
23960            }
23961
23962            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
23963            for (File file : files) {
23964                final String packageName = file.getName();
23965                try {
23966                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23967                } catch (PackageManagerException e) {
23968                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23969                    try {
23970                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23971                                StorageManager.FLAG_STORAGE_CE, 0);
23972                    } catch (InstallerException e2) {
23973                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23974                    }
23975                }
23976            }
23977        }
23978        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
23979            final File[] files = FileUtils.listFilesOrEmpty(deDir);
23980            for (File file : files) {
23981                final String packageName = file.getName();
23982                try {
23983                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23984                } catch (PackageManagerException e) {
23985                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23986                    try {
23987                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23988                                StorageManager.FLAG_STORAGE_DE, 0);
23989                    } catch (InstallerException e2) {
23990                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23991                    }
23992                }
23993            }
23994        }
23995
23996        // Ensure that data directories are ready to roll for all packages
23997        // installed for this volume and user
23998        final List<PackageSetting> packages;
23999        synchronized (mPackages) {
24000            packages = mSettings.getVolumePackagesLPr(volumeUuid);
24001        }
24002        int preparedCount = 0;
24003        for (PackageSetting ps : packages) {
24004            final String packageName = ps.name;
24005            if (ps.pkg == null) {
24006                Slog.w(TAG, "Odd, missing scanned package " + packageName);
24007                // TODO: might be due to legacy ASEC apps; we should circle back
24008                // and reconcile again once they're scanned
24009                continue;
24010            }
24011            // Skip non-core apps if requested
24012            if (onlyCoreApps && !ps.pkg.coreApp) {
24013                result.add(packageName);
24014                continue;
24015            }
24016
24017            if (ps.getInstalled(userId)) {
24018                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
24019                preparedCount++;
24020            }
24021        }
24022
24023        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
24024        return result;
24025    }
24026
24027    /**
24028     * Prepare app data for the given app just after it was installed or
24029     * upgraded. This method carefully only touches users that it's installed
24030     * for, and it forces a restorecon to handle any seinfo changes.
24031     * <p>
24032     * Verifies that directories exist and that ownership and labeling is
24033     * correct for all installed apps. If there is an ownership mismatch, it
24034     * will try recovering system apps by wiping data; third-party app data is
24035     * left intact.
24036     * <p>
24037     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
24038     */
24039    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
24040        final PackageSetting ps;
24041        synchronized (mPackages) {
24042            ps = mSettings.mPackages.get(pkg.packageName);
24043            mSettings.writeKernelMappingLPr(ps);
24044        }
24045
24046        final UserManager um = mContext.getSystemService(UserManager.class);
24047        UserManagerInternal umInternal = getUserManagerInternal();
24048        for (UserInfo user : um.getUsers()) {
24049            final int flags;
24050            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
24051                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
24052            } else if (umInternal.isUserRunning(user.id)) {
24053                flags = StorageManager.FLAG_STORAGE_DE;
24054            } else {
24055                continue;
24056            }
24057
24058            if (ps.getInstalled(user.id)) {
24059                // TODO: when user data is locked, mark that we're still dirty
24060                prepareAppDataLIF(pkg, user.id, flags);
24061            }
24062        }
24063    }
24064
24065    /**
24066     * Prepare app data for the given app.
24067     * <p>
24068     * Verifies that directories exist and that ownership and labeling is
24069     * correct for all installed apps. If there is an ownership mismatch, this
24070     * will try recovering system apps by wiping data; third-party app data is
24071     * left intact.
24072     */
24073    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
24074        if (pkg == null) {
24075            Slog.wtf(TAG, "Package was null!", new Throwable());
24076            return;
24077        }
24078        prepareAppDataLeafLIF(pkg, userId, flags);
24079        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
24080        for (int i = 0; i < childCount; i++) {
24081            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
24082        }
24083    }
24084
24085    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
24086            boolean maybeMigrateAppData) {
24087        prepareAppDataLIF(pkg, userId, flags);
24088
24089        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
24090            // We may have just shuffled around app data directories, so
24091            // prepare them one more time
24092            prepareAppDataLIF(pkg, userId, flags);
24093        }
24094    }
24095
24096    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
24097        if (DEBUG_APP_DATA) {
24098            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
24099                    + Integer.toHexString(flags));
24100        }
24101
24102        final String volumeUuid = pkg.volumeUuid;
24103        final String packageName = pkg.packageName;
24104        final ApplicationInfo app = pkg.applicationInfo;
24105        final int appId = UserHandle.getAppId(app.uid);
24106
24107        Preconditions.checkNotNull(app.seInfo);
24108
24109        long ceDataInode = -1;
24110        try {
24111            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
24112                    appId, app.seInfo, app.targetSdkVersion);
24113        } catch (InstallerException e) {
24114            if (app.isSystemApp()) {
24115                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
24116                        + ", but trying to recover: " + e);
24117                destroyAppDataLeafLIF(pkg, userId, flags);
24118                try {
24119                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
24120                            appId, app.seInfo, app.targetSdkVersion);
24121                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
24122                } catch (InstallerException e2) {
24123                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
24124                }
24125            } else {
24126                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
24127            }
24128        }
24129
24130        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
24131            // TODO: mark this structure as dirty so we persist it!
24132            synchronized (mPackages) {
24133                final PackageSetting ps = mSettings.mPackages.get(packageName);
24134                if (ps != null) {
24135                    ps.setCeDataInode(ceDataInode, userId);
24136                }
24137            }
24138        }
24139
24140        prepareAppDataContentsLeafLIF(pkg, userId, flags);
24141    }
24142
24143    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
24144        if (pkg == null) {
24145            Slog.wtf(TAG, "Package was null!", new Throwable());
24146            return;
24147        }
24148        prepareAppDataContentsLeafLIF(pkg, userId, flags);
24149        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
24150        for (int i = 0; i < childCount; i++) {
24151            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
24152        }
24153    }
24154
24155    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
24156        final String volumeUuid = pkg.volumeUuid;
24157        final String packageName = pkg.packageName;
24158        final ApplicationInfo app = pkg.applicationInfo;
24159
24160        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
24161            // Create a native library symlink only if we have native libraries
24162            // and if the native libraries are 32 bit libraries. We do not provide
24163            // this symlink for 64 bit libraries.
24164            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
24165                final String nativeLibPath = app.nativeLibraryDir;
24166                try {
24167                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
24168                            nativeLibPath, userId);
24169                } catch (InstallerException e) {
24170                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
24171                }
24172            }
24173        }
24174    }
24175
24176    /**
24177     * For system apps on non-FBE devices, this method migrates any existing
24178     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
24179     * requested by the app.
24180     */
24181    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
24182        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
24183                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
24184            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
24185                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
24186            try {
24187                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
24188                        storageTarget);
24189            } catch (InstallerException e) {
24190                logCriticalInfo(Log.WARN,
24191                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
24192            }
24193            return true;
24194        } else {
24195            return false;
24196        }
24197    }
24198
24199    public PackageFreezer freezePackage(String packageName, String killReason) {
24200        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
24201    }
24202
24203    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
24204        return new PackageFreezer(packageName, userId, killReason);
24205    }
24206
24207    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
24208            String killReason) {
24209        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
24210    }
24211
24212    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
24213            String killReason) {
24214        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
24215            return new PackageFreezer();
24216        } else {
24217            return freezePackage(packageName, userId, killReason);
24218        }
24219    }
24220
24221    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
24222            String killReason) {
24223        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
24224    }
24225
24226    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
24227            String killReason) {
24228        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
24229            return new PackageFreezer();
24230        } else {
24231            return freezePackage(packageName, userId, killReason);
24232        }
24233    }
24234
24235    /**
24236     * Class that freezes and kills the given package upon creation, and
24237     * unfreezes it upon closing. This is typically used when doing surgery on
24238     * app code/data to prevent the app from running while you're working.
24239     */
24240    private class PackageFreezer implements AutoCloseable {
24241        private final String mPackageName;
24242        private final PackageFreezer[] mChildren;
24243
24244        private final boolean mWeFroze;
24245
24246        private final AtomicBoolean mClosed = new AtomicBoolean();
24247        private final CloseGuard mCloseGuard = CloseGuard.get();
24248
24249        /**
24250         * Create and return a stub freezer that doesn't actually do anything,
24251         * typically used when someone requested
24252         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
24253         * {@link PackageManager#DELETE_DONT_KILL_APP}.
24254         */
24255        public PackageFreezer() {
24256            mPackageName = null;
24257            mChildren = null;
24258            mWeFroze = false;
24259            mCloseGuard.open("close");
24260        }
24261
24262        public PackageFreezer(String packageName, int userId, String killReason) {
24263            synchronized (mPackages) {
24264                mPackageName = packageName;
24265                mWeFroze = mFrozenPackages.add(mPackageName);
24266
24267                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
24268                if (ps != null) {
24269                    killApplication(ps.name, ps.appId, userId, killReason);
24270                }
24271
24272                final PackageParser.Package p = mPackages.get(packageName);
24273                if (p != null && p.childPackages != null) {
24274                    final int N = p.childPackages.size();
24275                    mChildren = new PackageFreezer[N];
24276                    for (int i = 0; i < N; i++) {
24277                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
24278                                userId, killReason);
24279                    }
24280                } else {
24281                    mChildren = null;
24282                }
24283            }
24284            mCloseGuard.open("close");
24285        }
24286
24287        @Override
24288        protected void finalize() throws Throwable {
24289            try {
24290                if (mCloseGuard != null) {
24291                    mCloseGuard.warnIfOpen();
24292                }
24293
24294                close();
24295            } finally {
24296                super.finalize();
24297            }
24298        }
24299
24300        @Override
24301        public void close() {
24302            mCloseGuard.close();
24303            if (mClosed.compareAndSet(false, true)) {
24304                synchronized (mPackages) {
24305                    if (mWeFroze) {
24306                        mFrozenPackages.remove(mPackageName);
24307                    }
24308
24309                    if (mChildren != null) {
24310                        for (PackageFreezer freezer : mChildren) {
24311                            freezer.close();
24312                        }
24313                    }
24314                }
24315            }
24316        }
24317    }
24318
24319    /**
24320     * Verify that given package is currently frozen.
24321     */
24322    private void checkPackageFrozen(String packageName) {
24323        synchronized (mPackages) {
24324            if (!mFrozenPackages.contains(packageName)) {
24325                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
24326            }
24327        }
24328    }
24329
24330    @Override
24331    public int movePackage(final String packageName, final String volumeUuid) {
24332        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
24333
24334        final int callingUid = Binder.getCallingUid();
24335        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
24336        final int moveId = mNextMoveId.getAndIncrement();
24337        mHandler.post(new Runnable() {
24338            @Override
24339            public void run() {
24340                try {
24341                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
24342                } catch (PackageManagerException e) {
24343                    Slog.w(TAG, "Failed to move " + packageName, e);
24344                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
24345                }
24346            }
24347        });
24348        return moveId;
24349    }
24350
24351    private void movePackageInternal(final String packageName, final String volumeUuid,
24352            final int moveId, final int callingUid, UserHandle user)
24353                    throws PackageManagerException {
24354        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24355        final PackageManager pm = mContext.getPackageManager();
24356
24357        final boolean currentAsec;
24358        final String currentVolumeUuid;
24359        final File codeFile;
24360        final String installerPackageName;
24361        final String packageAbiOverride;
24362        final int appId;
24363        final String seinfo;
24364        final String label;
24365        final int targetSdkVersion;
24366        final PackageFreezer freezer;
24367        final int[] installedUserIds;
24368
24369        // reader
24370        synchronized (mPackages) {
24371            final PackageParser.Package pkg = mPackages.get(packageName);
24372            final PackageSetting ps = mSettings.mPackages.get(packageName);
24373            if (pkg == null
24374                    || ps == null
24375                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
24376                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
24377            }
24378            if (pkg.applicationInfo.isSystemApp()) {
24379                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
24380                        "Cannot move system application");
24381            }
24382
24383            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
24384            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
24385                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
24386            if (isInternalStorage && !allow3rdPartyOnInternal) {
24387                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
24388                        "3rd party apps are not allowed on internal storage");
24389            }
24390
24391            if (pkg.applicationInfo.isExternalAsec()) {
24392                currentAsec = true;
24393                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
24394            } else if (pkg.applicationInfo.isForwardLocked()) {
24395                currentAsec = true;
24396                currentVolumeUuid = "forward_locked";
24397            } else {
24398                currentAsec = false;
24399                currentVolumeUuid = ps.volumeUuid;
24400
24401                final File probe = new File(pkg.codePath);
24402                final File probeOat = new File(probe, "oat");
24403                if (!probe.isDirectory() || !probeOat.isDirectory()) {
24404                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24405                            "Move only supported for modern cluster style installs");
24406                }
24407            }
24408
24409            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
24410                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24411                        "Package already moved to " + volumeUuid);
24412            }
24413            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
24414                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
24415                        "Device admin cannot be moved");
24416            }
24417
24418            if (mFrozenPackages.contains(packageName)) {
24419                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
24420                        "Failed to move already frozen package");
24421            }
24422
24423            codeFile = new File(pkg.codePath);
24424            installerPackageName = ps.installerPackageName;
24425            packageAbiOverride = ps.cpuAbiOverrideString;
24426            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
24427            seinfo = pkg.applicationInfo.seInfo;
24428            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
24429            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
24430            freezer = freezePackage(packageName, "movePackageInternal");
24431            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
24432        }
24433
24434        final Bundle extras = new Bundle();
24435        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
24436        extras.putString(Intent.EXTRA_TITLE, label);
24437        mMoveCallbacks.notifyCreated(moveId, extras);
24438
24439        int installFlags;
24440        final boolean moveCompleteApp;
24441        final File measurePath;
24442
24443        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
24444            installFlags = INSTALL_INTERNAL;
24445            moveCompleteApp = !currentAsec;
24446            measurePath = Environment.getDataAppDirectory(volumeUuid);
24447        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
24448            installFlags = INSTALL_EXTERNAL;
24449            moveCompleteApp = false;
24450            measurePath = storage.getPrimaryPhysicalVolume().getPath();
24451        } else {
24452            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
24453            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
24454                    || !volume.isMountedWritable()) {
24455                freezer.close();
24456                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24457                        "Move location not mounted private volume");
24458            }
24459
24460            Preconditions.checkState(!currentAsec);
24461
24462            installFlags = INSTALL_INTERNAL;
24463            moveCompleteApp = true;
24464            measurePath = Environment.getDataAppDirectory(volumeUuid);
24465        }
24466
24467        // If we're moving app data around, we need all the users unlocked
24468        if (moveCompleteApp) {
24469            for (int userId : installedUserIds) {
24470                if (StorageManager.isFileEncryptedNativeOrEmulated()
24471                        && !StorageManager.isUserKeyUnlocked(userId)) {
24472                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
24473                            "User " + userId + " must be unlocked");
24474                }
24475            }
24476        }
24477
24478        final PackageStats stats = new PackageStats(null, -1);
24479        synchronized (mInstaller) {
24480            for (int userId : installedUserIds) {
24481                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
24482                    freezer.close();
24483                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24484                            "Failed to measure package size");
24485                }
24486            }
24487        }
24488
24489        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
24490                + stats.dataSize);
24491
24492        final long startFreeBytes = measurePath.getUsableSpace();
24493        final long sizeBytes;
24494        if (moveCompleteApp) {
24495            sizeBytes = stats.codeSize + stats.dataSize;
24496        } else {
24497            sizeBytes = stats.codeSize;
24498        }
24499
24500        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
24501            freezer.close();
24502            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24503                    "Not enough free space to move");
24504        }
24505
24506        mMoveCallbacks.notifyStatusChanged(moveId, 10);
24507
24508        final CountDownLatch installedLatch = new CountDownLatch(1);
24509        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
24510            @Override
24511            public void onUserActionRequired(Intent intent) throws RemoteException {
24512                throw new IllegalStateException();
24513            }
24514
24515            @Override
24516            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
24517                    Bundle extras) throws RemoteException {
24518                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
24519                        + PackageManager.installStatusToString(returnCode, msg));
24520
24521                installedLatch.countDown();
24522                freezer.close();
24523
24524                final int status = PackageManager.installStatusToPublicStatus(returnCode);
24525                switch (status) {
24526                    case PackageInstaller.STATUS_SUCCESS:
24527                        mMoveCallbacks.notifyStatusChanged(moveId,
24528                                PackageManager.MOVE_SUCCEEDED);
24529                        break;
24530                    case PackageInstaller.STATUS_FAILURE_STORAGE:
24531                        mMoveCallbacks.notifyStatusChanged(moveId,
24532                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
24533                        break;
24534                    default:
24535                        mMoveCallbacks.notifyStatusChanged(moveId,
24536                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
24537                        break;
24538                }
24539            }
24540        };
24541
24542        final MoveInfo move;
24543        if (moveCompleteApp) {
24544            // Kick off a thread to report progress estimates
24545            new Thread() {
24546                @Override
24547                public void run() {
24548                    while (true) {
24549                        try {
24550                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
24551                                break;
24552                            }
24553                        } catch (InterruptedException ignored) {
24554                        }
24555
24556                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
24557                        final int progress = 10 + (int) MathUtils.constrain(
24558                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
24559                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
24560                    }
24561                }
24562            }.start();
24563
24564            final String dataAppName = codeFile.getName();
24565            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
24566                    dataAppName, appId, seinfo, targetSdkVersion);
24567        } else {
24568            move = null;
24569        }
24570
24571        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
24572
24573        final Message msg = mHandler.obtainMessage(INIT_COPY);
24574        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
24575        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
24576                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
24577                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
24578                PackageManager.INSTALL_REASON_UNKNOWN);
24579        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
24580        msg.obj = params;
24581
24582        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
24583                System.identityHashCode(msg.obj));
24584        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
24585                System.identityHashCode(msg.obj));
24586
24587        mHandler.sendMessage(msg);
24588    }
24589
24590    @Override
24591    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
24592        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
24593
24594        final int realMoveId = mNextMoveId.getAndIncrement();
24595        final Bundle extras = new Bundle();
24596        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
24597        mMoveCallbacks.notifyCreated(realMoveId, extras);
24598
24599        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
24600            @Override
24601            public void onCreated(int moveId, Bundle extras) {
24602                // Ignored
24603            }
24604
24605            @Override
24606            public void onStatusChanged(int moveId, int status, long estMillis) {
24607                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
24608            }
24609        };
24610
24611        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24612        storage.setPrimaryStorageUuid(volumeUuid, callback);
24613        return realMoveId;
24614    }
24615
24616    @Override
24617    public int getMoveStatus(int moveId) {
24618        mContext.enforceCallingOrSelfPermission(
24619                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24620        return mMoveCallbacks.mLastStatus.get(moveId);
24621    }
24622
24623    @Override
24624    public void registerMoveCallback(IPackageMoveObserver callback) {
24625        mContext.enforceCallingOrSelfPermission(
24626                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24627        mMoveCallbacks.register(callback);
24628    }
24629
24630    @Override
24631    public void unregisterMoveCallback(IPackageMoveObserver callback) {
24632        mContext.enforceCallingOrSelfPermission(
24633                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24634        mMoveCallbacks.unregister(callback);
24635    }
24636
24637    @Override
24638    public boolean setInstallLocation(int loc) {
24639        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
24640                null);
24641        if (getInstallLocation() == loc) {
24642            return true;
24643        }
24644        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
24645                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
24646            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
24647                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
24648            return true;
24649        }
24650        return false;
24651   }
24652
24653    @Override
24654    public int getInstallLocation() {
24655        // allow instant app access
24656        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
24657                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
24658                PackageHelper.APP_INSTALL_AUTO);
24659    }
24660
24661    /** Called by UserManagerService */
24662    void cleanUpUser(UserManagerService userManager, int userHandle) {
24663        synchronized (mPackages) {
24664            mDirtyUsers.remove(userHandle);
24665            mUserNeedsBadging.delete(userHandle);
24666            mSettings.removeUserLPw(userHandle);
24667            mPendingBroadcasts.remove(userHandle);
24668            mInstantAppRegistry.onUserRemovedLPw(userHandle);
24669            removeUnusedPackagesLPw(userManager, userHandle);
24670        }
24671    }
24672
24673    /**
24674     * We're removing userHandle and would like to remove any downloaded packages
24675     * that are no longer in use by any other user.
24676     * @param userHandle the user being removed
24677     */
24678    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
24679        final boolean DEBUG_CLEAN_APKS = false;
24680        int [] users = userManager.getUserIds();
24681        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
24682        while (psit.hasNext()) {
24683            PackageSetting ps = psit.next();
24684            if (ps.pkg == null) {
24685                continue;
24686            }
24687            final String packageName = ps.pkg.packageName;
24688            // Skip over if system app
24689            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
24690                continue;
24691            }
24692            if (DEBUG_CLEAN_APKS) {
24693                Slog.i(TAG, "Checking package " + packageName);
24694            }
24695            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
24696            if (keep) {
24697                if (DEBUG_CLEAN_APKS) {
24698                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
24699                }
24700            } else {
24701                for (int i = 0; i < users.length; i++) {
24702                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
24703                        keep = true;
24704                        if (DEBUG_CLEAN_APKS) {
24705                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
24706                                    + users[i]);
24707                        }
24708                        break;
24709                    }
24710                }
24711            }
24712            if (!keep) {
24713                if (DEBUG_CLEAN_APKS) {
24714                    Slog.i(TAG, "  Removing package " + packageName);
24715                }
24716                mHandler.post(new Runnable() {
24717                    public void run() {
24718                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24719                                userHandle, 0);
24720                    } //end run
24721                });
24722            }
24723        }
24724    }
24725
24726    /** Called by UserManagerService */
24727    void createNewUser(int userId, String[] disallowedPackages) {
24728        synchronized (mInstallLock) {
24729            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
24730        }
24731        synchronized (mPackages) {
24732            scheduleWritePackageRestrictionsLocked(userId);
24733            scheduleWritePackageListLocked(userId);
24734            applyFactoryDefaultBrowserLPw(userId);
24735            primeDomainVerificationsLPw(userId);
24736        }
24737    }
24738
24739    void onNewUserCreated(final int userId) {
24740        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
24741        // If permission review for legacy apps is required, we represent
24742        // dagerous permissions for such apps as always granted runtime
24743        // permissions to keep per user flag state whether review is needed.
24744        // Hence, if a new user is added we have to propagate dangerous
24745        // permission grants for these legacy apps.
24746        if (mPermissionReviewRequired) {
24747            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
24748                    | UPDATE_PERMISSIONS_REPLACE_ALL);
24749        }
24750    }
24751
24752    @Override
24753    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
24754        mContext.enforceCallingOrSelfPermission(
24755                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
24756                "Only package verification agents can read the verifier device identity");
24757
24758        synchronized (mPackages) {
24759            return mSettings.getVerifierDeviceIdentityLPw();
24760        }
24761    }
24762
24763    @Override
24764    public void setPermissionEnforced(String permission, boolean enforced) {
24765        // TODO: Now that we no longer change GID for storage, this should to away.
24766        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
24767                "setPermissionEnforced");
24768        if (READ_EXTERNAL_STORAGE.equals(permission)) {
24769            synchronized (mPackages) {
24770                if (mSettings.mReadExternalStorageEnforced == null
24771                        || mSettings.mReadExternalStorageEnforced != enforced) {
24772                    mSettings.mReadExternalStorageEnforced = enforced;
24773                    mSettings.writeLPr();
24774                }
24775            }
24776            // kill any non-foreground processes so we restart them and
24777            // grant/revoke the GID.
24778            final IActivityManager am = ActivityManager.getService();
24779            if (am != null) {
24780                final long token = Binder.clearCallingIdentity();
24781                try {
24782                    am.killProcessesBelowForeground("setPermissionEnforcement");
24783                } catch (RemoteException e) {
24784                } finally {
24785                    Binder.restoreCallingIdentity(token);
24786                }
24787            }
24788        } else {
24789            throw new IllegalArgumentException("No selective enforcement for " + permission);
24790        }
24791    }
24792
24793    @Override
24794    @Deprecated
24795    public boolean isPermissionEnforced(String permission) {
24796        // allow instant applications
24797        return true;
24798    }
24799
24800    @Override
24801    public boolean isStorageLow() {
24802        // allow instant applications
24803        final long token = Binder.clearCallingIdentity();
24804        try {
24805            final DeviceStorageMonitorInternal
24806                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
24807            if (dsm != null) {
24808                return dsm.isMemoryLow();
24809            } else {
24810                return false;
24811            }
24812        } finally {
24813            Binder.restoreCallingIdentity(token);
24814        }
24815    }
24816
24817    @Override
24818    public IPackageInstaller getPackageInstaller() {
24819        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24820            return null;
24821        }
24822        return mInstallerService;
24823    }
24824
24825    private boolean userNeedsBadging(int userId) {
24826        int index = mUserNeedsBadging.indexOfKey(userId);
24827        if (index < 0) {
24828            final UserInfo userInfo;
24829            final long token = Binder.clearCallingIdentity();
24830            try {
24831                userInfo = sUserManager.getUserInfo(userId);
24832            } finally {
24833                Binder.restoreCallingIdentity(token);
24834            }
24835            final boolean b;
24836            if (userInfo != null && userInfo.isManagedProfile()) {
24837                b = true;
24838            } else {
24839                b = false;
24840            }
24841            mUserNeedsBadging.put(userId, b);
24842            return b;
24843        }
24844        return mUserNeedsBadging.valueAt(index);
24845    }
24846
24847    @Override
24848    public KeySet getKeySetByAlias(String packageName, String alias) {
24849        if (packageName == null || alias == null) {
24850            return null;
24851        }
24852        synchronized(mPackages) {
24853            final PackageParser.Package pkg = mPackages.get(packageName);
24854            if (pkg == null) {
24855                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24856                throw new IllegalArgumentException("Unknown package: " + packageName);
24857            }
24858            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24859            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24860                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24861                throw new IllegalArgumentException("Unknown package: " + packageName);
24862            }
24863            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24864            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24865        }
24866    }
24867
24868    @Override
24869    public KeySet getSigningKeySet(String packageName) {
24870        if (packageName == null) {
24871            return null;
24872        }
24873        synchronized(mPackages) {
24874            final int callingUid = Binder.getCallingUid();
24875            final int callingUserId = UserHandle.getUserId(callingUid);
24876            final PackageParser.Package pkg = mPackages.get(packageName);
24877            if (pkg == null) {
24878                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24879                throw new IllegalArgumentException("Unknown package: " + packageName);
24880            }
24881            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24882            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24883                // filter and pretend the package doesn't exist
24884                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24885                        + ", uid:" + callingUid);
24886                throw new IllegalArgumentException("Unknown package: " + packageName);
24887            }
24888            if (pkg.applicationInfo.uid != callingUid
24889                    && Process.SYSTEM_UID != callingUid) {
24890                throw new SecurityException("May not access signing KeySet of other apps.");
24891            }
24892            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24893            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24894        }
24895    }
24896
24897    @Override
24898    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
24899        final int callingUid = Binder.getCallingUid();
24900        if (getInstantAppPackageName(callingUid) != null) {
24901            return false;
24902        }
24903        if (packageName == null || ks == null) {
24904            return false;
24905        }
24906        synchronized(mPackages) {
24907            final PackageParser.Package pkg = mPackages.get(packageName);
24908            if (pkg == null
24909                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24910                            UserHandle.getUserId(callingUid))) {
24911                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24912                throw new IllegalArgumentException("Unknown package: " + packageName);
24913            }
24914            IBinder ksh = ks.getToken();
24915            if (ksh instanceof KeySetHandle) {
24916                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24917                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
24918            }
24919            return false;
24920        }
24921    }
24922
24923    @Override
24924    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
24925        final int callingUid = Binder.getCallingUid();
24926        if (getInstantAppPackageName(callingUid) != null) {
24927            return false;
24928        }
24929        if (packageName == null || ks == null) {
24930            return false;
24931        }
24932        synchronized(mPackages) {
24933            final PackageParser.Package pkg = mPackages.get(packageName);
24934            if (pkg == null
24935                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24936                            UserHandle.getUserId(callingUid))) {
24937                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24938                throw new IllegalArgumentException("Unknown package: " + packageName);
24939            }
24940            IBinder ksh = ks.getToken();
24941            if (ksh instanceof KeySetHandle) {
24942                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24943                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
24944            }
24945            return false;
24946        }
24947    }
24948
24949    private void deletePackageIfUnusedLPr(final String packageName) {
24950        PackageSetting ps = mSettings.mPackages.get(packageName);
24951        if (ps == null) {
24952            return;
24953        }
24954        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
24955            // TODO Implement atomic delete if package is unused
24956            // It is currently possible that the package will be deleted even if it is installed
24957            // after this method returns.
24958            mHandler.post(new Runnable() {
24959                public void run() {
24960                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24961                            0, PackageManager.DELETE_ALL_USERS);
24962                }
24963            });
24964        }
24965    }
24966
24967    /**
24968     * Check and throw if the given before/after packages would be considered a
24969     * downgrade.
24970     */
24971    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
24972            throws PackageManagerException {
24973        if (after.versionCode < before.mVersionCode) {
24974            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24975                    "Update version code " + after.versionCode + " is older than current "
24976                    + before.mVersionCode);
24977        } else if (after.versionCode == before.mVersionCode) {
24978            if (after.baseRevisionCode < before.baseRevisionCode) {
24979                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24980                        "Update base revision code " + after.baseRevisionCode
24981                        + " is older than current " + before.baseRevisionCode);
24982            }
24983
24984            if (!ArrayUtils.isEmpty(after.splitNames)) {
24985                for (int i = 0; i < after.splitNames.length; i++) {
24986                    final String splitName = after.splitNames[i];
24987                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
24988                    if (j != -1) {
24989                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
24990                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24991                                    "Update split " + splitName + " revision code "
24992                                    + after.splitRevisionCodes[i] + " is older than current "
24993                                    + before.splitRevisionCodes[j]);
24994                        }
24995                    }
24996                }
24997            }
24998        }
24999    }
25000
25001    private static class MoveCallbacks extends Handler {
25002        private static final int MSG_CREATED = 1;
25003        private static final int MSG_STATUS_CHANGED = 2;
25004
25005        private final RemoteCallbackList<IPackageMoveObserver>
25006                mCallbacks = new RemoteCallbackList<>();
25007
25008        private final SparseIntArray mLastStatus = new SparseIntArray();
25009
25010        public MoveCallbacks(Looper looper) {
25011            super(looper);
25012        }
25013
25014        public void register(IPackageMoveObserver callback) {
25015            mCallbacks.register(callback);
25016        }
25017
25018        public void unregister(IPackageMoveObserver callback) {
25019            mCallbacks.unregister(callback);
25020        }
25021
25022        @Override
25023        public void handleMessage(Message msg) {
25024            final SomeArgs args = (SomeArgs) msg.obj;
25025            final int n = mCallbacks.beginBroadcast();
25026            for (int i = 0; i < n; i++) {
25027                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
25028                try {
25029                    invokeCallback(callback, msg.what, args);
25030                } catch (RemoteException ignored) {
25031                }
25032            }
25033            mCallbacks.finishBroadcast();
25034            args.recycle();
25035        }
25036
25037        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
25038                throws RemoteException {
25039            switch (what) {
25040                case MSG_CREATED: {
25041                    callback.onCreated(args.argi1, (Bundle) args.arg2);
25042                    break;
25043                }
25044                case MSG_STATUS_CHANGED: {
25045                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
25046                    break;
25047                }
25048            }
25049        }
25050
25051        private void notifyCreated(int moveId, Bundle extras) {
25052            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
25053
25054            final SomeArgs args = SomeArgs.obtain();
25055            args.argi1 = moveId;
25056            args.arg2 = extras;
25057            obtainMessage(MSG_CREATED, args).sendToTarget();
25058        }
25059
25060        private void notifyStatusChanged(int moveId, int status) {
25061            notifyStatusChanged(moveId, status, -1);
25062        }
25063
25064        private void notifyStatusChanged(int moveId, int status, long estMillis) {
25065            Slog.v(TAG, "Move " + moveId + " status " + status);
25066
25067            final SomeArgs args = SomeArgs.obtain();
25068            args.argi1 = moveId;
25069            args.argi2 = status;
25070            args.arg3 = estMillis;
25071            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
25072
25073            synchronized (mLastStatus) {
25074                mLastStatus.put(moveId, status);
25075            }
25076        }
25077    }
25078
25079    private final static class OnPermissionChangeListeners extends Handler {
25080        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
25081
25082        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
25083                new RemoteCallbackList<>();
25084
25085        public OnPermissionChangeListeners(Looper looper) {
25086            super(looper);
25087        }
25088
25089        @Override
25090        public void handleMessage(Message msg) {
25091            switch (msg.what) {
25092                case MSG_ON_PERMISSIONS_CHANGED: {
25093                    final int uid = msg.arg1;
25094                    handleOnPermissionsChanged(uid);
25095                } break;
25096            }
25097        }
25098
25099        public void addListenerLocked(IOnPermissionsChangeListener listener) {
25100            mPermissionListeners.register(listener);
25101
25102        }
25103
25104        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
25105            mPermissionListeners.unregister(listener);
25106        }
25107
25108        public void onPermissionsChanged(int uid) {
25109            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
25110                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
25111            }
25112        }
25113
25114        private void handleOnPermissionsChanged(int uid) {
25115            final int count = mPermissionListeners.beginBroadcast();
25116            try {
25117                for (int i = 0; i < count; i++) {
25118                    IOnPermissionsChangeListener callback = mPermissionListeners
25119                            .getBroadcastItem(i);
25120                    try {
25121                        callback.onPermissionsChanged(uid);
25122                    } catch (RemoteException e) {
25123                        Log.e(TAG, "Permission listener is dead", e);
25124                    }
25125                }
25126            } finally {
25127                mPermissionListeners.finishBroadcast();
25128            }
25129        }
25130    }
25131
25132    private class PackageManagerNative extends IPackageManagerNative.Stub {
25133        @Override
25134        public String[] getNamesForUids(int[] uids) throws RemoteException {
25135            final String[] results = PackageManagerService.this.getNamesForUids(uids);
25136            // massage results so they can be parsed by the native binder
25137            for (int i = results.length - 1; i >= 0; --i) {
25138                if (results[i] == null) {
25139                    results[i] = "";
25140                }
25141            }
25142            return results;
25143        }
25144    }
25145
25146    private class PackageManagerInternalImpl extends PackageManagerInternal {
25147        @Override
25148        public void setLocationPackagesProvider(PackagesProvider provider) {
25149            synchronized (mPackages) {
25150                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
25151            }
25152        }
25153
25154        @Override
25155        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
25156            synchronized (mPackages) {
25157                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
25158            }
25159        }
25160
25161        @Override
25162        public void setSmsAppPackagesProvider(PackagesProvider provider) {
25163            synchronized (mPackages) {
25164                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
25165            }
25166        }
25167
25168        @Override
25169        public void setDialerAppPackagesProvider(PackagesProvider provider) {
25170            synchronized (mPackages) {
25171                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
25172            }
25173        }
25174
25175        @Override
25176        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
25177            synchronized (mPackages) {
25178                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
25179            }
25180        }
25181
25182        @Override
25183        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
25184            synchronized (mPackages) {
25185                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
25186            }
25187        }
25188
25189        @Override
25190        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
25191            synchronized (mPackages) {
25192                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
25193                        packageName, userId);
25194            }
25195        }
25196
25197        @Override
25198        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
25199            synchronized (mPackages) {
25200                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
25201                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
25202                        packageName, userId);
25203            }
25204        }
25205
25206        @Override
25207        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
25208            synchronized (mPackages) {
25209                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
25210                        packageName, userId);
25211            }
25212        }
25213
25214        @Override
25215        public void setKeepUninstalledPackages(final List<String> packageList) {
25216            Preconditions.checkNotNull(packageList);
25217            List<String> removedFromList = null;
25218            synchronized (mPackages) {
25219                if (mKeepUninstalledPackages != null) {
25220                    final int packagesCount = mKeepUninstalledPackages.size();
25221                    for (int i = 0; i < packagesCount; i++) {
25222                        String oldPackage = mKeepUninstalledPackages.get(i);
25223                        if (packageList != null && packageList.contains(oldPackage)) {
25224                            continue;
25225                        }
25226                        if (removedFromList == null) {
25227                            removedFromList = new ArrayList<>();
25228                        }
25229                        removedFromList.add(oldPackage);
25230                    }
25231                }
25232                mKeepUninstalledPackages = new ArrayList<>(packageList);
25233                if (removedFromList != null) {
25234                    final int removedCount = removedFromList.size();
25235                    for (int i = 0; i < removedCount; i++) {
25236                        deletePackageIfUnusedLPr(removedFromList.get(i));
25237                    }
25238                }
25239            }
25240        }
25241
25242        @Override
25243        public boolean isPermissionsReviewRequired(String packageName, int userId) {
25244            synchronized (mPackages) {
25245                // If we do not support permission review, done.
25246                if (!mPermissionReviewRequired) {
25247                    return false;
25248                }
25249
25250                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
25251                if (packageSetting == null) {
25252                    return false;
25253                }
25254
25255                // Permission review applies only to apps not supporting the new permission model.
25256                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
25257                    return false;
25258                }
25259
25260                // Legacy apps have the permission and get user consent on launch.
25261                PermissionsState permissionsState = packageSetting.getPermissionsState();
25262                return permissionsState.isPermissionReviewRequired(userId);
25263            }
25264        }
25265
25266        @Override
25267        public PackageInfo getPackageInfo(
25268                String packageName, int flags, int filterCallingUid, int userId) {
25269            return PackageManagerService.this
25270                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
25271                            flags, filterCallingUid, userId);
25272        }
25273
25274        @Override
25275        public ApplicationInfo getApplicationInfo(
25276                String packageName, int flags, int filterCallingUid, int userId) {
25277            return PackageManagerService.this
25278                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
25279        }
25280
25281        @Override
25282        public ActivityInfo getActivityInfo(
25283                ComponentName component, int flags, int filterCallingUid, int userId) {
25284            return PackageManagerService.this
25285                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
25286        }
25287
25288        @Override
25289        public List<ResolveInfo> queryIntentActivities(
25290                Intent intent, int flags, int filterCallingUid, int userId) {
25291            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
25292            return PackageManagerService.this
25293                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
25294                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
25295        }
25296
25297        @Override
25298        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
25299                int userId) {
25300            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
25301        }
25302
25303        @Override
25304        public void setDeviceAndProfileOwnerPackages(
25305                int deviceOwnerUserId, String deviceOwnerPackage,
25306                SparseArray<String> profileOwnerPackages) {
25307            mProtectedPackages.setDeviceAndProfileOwnerPackages(
25308                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
25309        }
25310
25311        @Override
25312        public boolean isPackageDataProtected(int userId, String packageName) {
25313            return mProtectedPackages.isPackageDataProtected(userId, packageName);
25314        }
25315
25316        @Override
25317        public boolean isPackageEphemeral(int userId, String packageName) {
25318            synchronized (mPackages) {
25319                final PackageSetting ps = mSettings.mPackages.get(packageName);
25320                return ps != null ? ps.getInstantApp(userId) : false;
25321            }
25322        }
25323
25324        @Override
25325        public boolean wasPackageEverLaunched(String packageName, int userId) {
25326            synchronized (mPackages) {
25327                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
25328            }
25329        }
25330
25331        @Override
25332        public void grantRuntimePermission(String packageName, String name, int userId,
25333                boolean overridePolicy) {
25334            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
25335                    overridePolicy);
25336        }
25337
25338        @Override
25339        public void revokeRuntimePermission(String packageName, String name, int userId,
25340                boolean overridePolicy) {
25341            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
25342                    overridePolicy);
25343        }
25344
25345        @Override
25346        public String getNameForUid(int uid) {
25347            return PackageManagerService.this.getNameForUid(uid);
25348        }
25349
25350        @Override
25351        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
25352                Intent origIntent, String resolvedType, String callingPackage,
25353                Bundle verificationBundle, int userId) {
25354            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
25355                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
25356                    userId);
25357        }
25358
25359        @Override
25360        public void grantEphemeralAccess(int userId, Intent intent,
25361                int targetAppId, int ephemeralAppId) {
25362            synchronized (mPackages) {
25363                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
25364                        targetAppId, ephemeralAppId);
25365            }
25366        }
25367
25368        @Override
25369        public boolean isInstantAppInstallerComponent(ComponentName component) {
25370            synchronized (mPackages) {
25371                return mInstantAppInstallerActivity != null
25372                        && mInstantAppInstallerActivity.getComponentName().equals(component);
25373            }
25374        }
25375
25376        @Override
25377        public void pruneInstantApps() {
25378            mInstantAppRegistry.pruneInstantApps();
25379        }
25380
25381        @Override
25382        public String getSetupWizardPackageName() {
25383            return mSetupWizardPackage;
25384        }
25385
25386        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
25387            if (policy != null) {
25388                mExternalSourcesPolicy = policy;
25389            }
25390        }
25391
25392        @Override
25393        public boolean isPackagePersistent(String packageName) {
25394            synchronized (mPackages) {
25395                PackageParser.Package pkg = mPackages.get(packageName);
25396                return pkg != null
25397                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
25398                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
25399                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
25400                        : false;
25401            }
25402        }
25403
25404        @Override
25405        public List<PackageInfo> getOverlayPackages(int userId) {
25406            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
25407            synchronized (mPackages) {
25408                for (PackageParser.Package p : mPackages.values()) {
25409                    if (p.mOverlayTarget != null) {
25410                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
25411                        if (pkg != null) {
25412                            overlayPackages.add(pkg);
25413                        }
25414                    }
25415                }
25416            }
25417            return overlayPackages;
25418        }
25419
25420        @Override
25421        public List<String> getTargetPackageNames(int userId) {
25422            List<String> targetPackages = new ArrayList<>();
25423            synchronized (mPackages) {
25424                for (PackageParser.Package p : mPackages.values()) {
25425                    if (p.mOverlayTarget == null) {
25426                        targetPackages.add(p.packageName);
25427                    }
25428                }
25429            }
25430            return targetPackages;
25431        }
25432
25433        @Override
25434        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
25435                @Nullable List<String> overlayPackageNames) {
25436            synchronized (mPackages) {
25437                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
25438                    Slog.e(TAG, "failed to find package " + targetPackageName);
25439                    return false;
25440                }
25441                ArrayList<String> overlayPaths = null;
25442                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
25443                    final int N = overlayPackageNames.size();
25444                    overlayPaths = new ArrayList<>(N);
25445                    for (int i = 0; i < N; i++) {
25446                        final String packageName = overlayPackageNames.get(i);
25447                        final PackageParser.Package pkg = mPackages.get(packageName);
25448                        if (pkg == null) {
25449                            Slog.e(TAG, "failed to find package " + packageName);
25450                            return false;
25451                        }
25452                        overlayPaths.add(pkg.baseCodePath);
25453                    }
25454                }
25455
25456                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
25457                ps.setOverlayPaths(overlayPaths, userId);
25458                return true;
25459            }
25460        }
25461
25462        @Override
25463        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
25464                int flags, int userId) {
25465            return resolveIntentInternal(
25466                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
25467        }
25468
25469        @Override
25470        public ResolveInfo resolveService(Intent intent, String resolvedType,
25471                int flags, int userId, int callingUid) {
25472            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
25473        }
25474
25475        @Override
25476        public void addIsolatedUid(int isolatedUid, int ownerUid) {
25477            synchronized (mPackages) {
25478                mIsolatedOwners.put(isolatedUid, ownerUid);
25479            }
25480        }
25481
25482        @Override
25483        public void removeIsolatedUid(int isolatedUid) {
25484            synchronized (mPackages) {
25485                mIsolatedOwners.delete(isolatedUid);
25486            }
25487        }
25488
25489        @Override
25490        public int getUidTargetSdkVersion(int uid) {
25491            synchronized (mPackages) {
25492                return getUidTargetSdkVersionLockedLPr(uid);
25493            }
25494        }
25495
25496        @Override
25497        public boolean canAccessInstantApps(int callingUid, int userId) {
25498            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
25499        }
25500
25501        @Override
25502        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
25503            synchronized (mPackages) {
25504                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
25505            }
25506        }
25507
25508        @Override
25509        public void notifyPackageUse(String packageName, int reason) {
25510            synchronized (mPackages) {
25511                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
25512            }
25513        }
25514    }
25515
25516    @Override
25517    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
25518        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
25519        synchronized (mPackages) {
25520            final long identity = Binder.clearCallingIdentity();
25521            try {
25522                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
25523                        packageNames, userId);
25524            } finally {
25525                Binder.restoreCallingIdentity(identity);
25526            }
25527        }
25528    }
25529
25530    @Override
25531    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
25532        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
25533        synchronized (mPackages) {
25534            final long identity = Binder.clearCallingIdentity();
25535            try {
25536                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
25537                        packageNames, userId);
25538            } finally {
25539                Binder.restoreCallingIdentity(identity);
25540            }
25541        }
25542    }
25543
25544    private static void enforceSystemOrPhoneCaller(String tag) {
25545        int callingUid = Binder.getCallingUid();
25546        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
25547            throw new SecurityException(
25548                    "Cannot call " + tag + " from UID " + callingUid);
25549        }
25550    }
25551
25552    boolean isHistoricalPackageUsageAvailable() {
25553        return mPackageUsage.isHistoricalPackageUsageAvailable();
25554    }
25555
25556    /**
25557     * Return a <b>copy</b> of the collection of packages known to the package manager.
25558     * @return A copy of the values of mPackages.
25559     */
25560    Collection<PackageParser.Package> getPackages() {
25561        synchronized (mPackages) {
25562            return new ArrayList<>(mPackages.values());
25563        }
25564    }
25565
25566    /**
25567     * Logs process start information (including base APK hash) to the security log.
25568     * @hide
25569     */
25570    @Override
25571    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
25572            String apkFile, int pid) {
25573        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25574            return;
25575        }
25576        if (!SecurityLog.isLoggingEnabled()) {
25577            return;
25578        }
25579        Bundle data = new Bundle();
25580        data.putLong("startTimestamp", System.currentTimeMillis());
25581        data.putString("processName", processName);
25582        data.putInt("uid", uid);
25583        data.putString("seinfo", seinfo);
25584        data.putString("apkFile", apkFile);
25585        data.putInt("pid", pid);
25586        Message msg = mProcessLoggingHandler.obtainMessage(
25587                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
25588        msg.setData(data);
25589        mProcessLoggingHandler.sendMessage(msg);
25590    }
25591
25592    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
25593        return mCompilerStats.getPackageStats(pkgName);
25594    }
25595
25596    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
25597        return getOrCreateCompilerPackageStats(pkg.packageName);
25598    }
25599
25600    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
25601        return mCompilerStats.getOrCreatePackageStats(pkgName);
25602    }
25603
25604    public void deleteCompilerPackageStats(String pkgName) {
25605        mCompilerStats.deletePackageStats(pkgName);
25606    }
25607
25608    @Override
25609    public int getInstallReason(String packageName, int userId) {
25610        final int callingUid = Binder.getCallingUid();
25611        enforceCrossUserPermission(callingUid, userId,
25612                true /* requireFullPermission */, false /* checkShell */,
25613                "get install reason");
25614        synchronized (mPackages) {
25615            final PackageSetting ps = mSettings.mPackages.get(packageName);
25616            if (filterAppAccessLPr(ps, callingUid, userId)) {
25617                return PackageManager.INSTALL_REASON_UNKNOWN;
25618            }
25619            if (ps != null) {
25620                return ps.getInstallReason(userId);
25621            }
25622        }
25623        return PackageManager.INSTALL_REASON_UNKNOWN;
25624    }
25625
25626    @Override
25627    public boolean canRequestPackageInstalls(String packageName, int userId) {
25628        return canRequestPackageInstallsInternal(packageName, 0, userId,
25629                true /* throwIfPermNotDeclared*/);
25630    }
25631
25632    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
25633            boolean throwIfPermNotDeclared) {
25634        int callingUid = Binder.getCallingUid();
25635        int uid = getPackageUid(packageName, 0, userId);
25636        if (callingUid != uid && callingUid != Process.ROOT_UID
25637                && callingUid != Process.SYSTEM_UID) {
25638            throw new SecurityException(
25639                    "Caller uid " + callingUid + " does not own package " + packageName);
25640        }
25641        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
25642        if (info == null) {
25643            return false;
25644        }
25645        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
25646            return false;
25647        }
25648        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
25649        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
25650        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
25651            if (throwIfPermNotDeclared) {
25652                throw new SecurityException("Need to declare " + appOpPermission
25653                        + " to call this api");
25654            } else {
25655                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
25656                return false;
25657            }
25658        }
25659        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
25660            return false;
25661        }
25662        if (mExternalSourcesPolicy != null) {
25663            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
25664            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
25665                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
25666            }
25667        }
25668        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
25669    }
25670
25671    @Override
25672    public ComponentName getInstantAppResolverSettingsComponent() {
25673        return mInstantAppResolverSettingsComponent;
25674    }
25675
25676    @Override
25677    public ComponentName getInstantAppInstallerComponent() {
25678        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25679            return null;
25680        }
25681        return mInstantAppInstallerActivity == null
25682                ? null : mInstantAppInstallerActivity.getComponentName();
25683    }
25684
25685    @Override
25686    public String getInstantAppAndroidId(String packageName, int userId) {
25687        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
25688                "getInstantAppAndroidId");
25689        enforceCrossUserPermission(Binder.getCallingUid(), userId,
25690                true /* requireFullPermission */, false /* checkShell */,
25691                "getInstantAppAndroidId");
25692        // Make sure the target is an Instant App.
25693        if (!isInstantApp(packageName, userId)) {
25694            return null;
25695        }
25696        synchronized (mPackages) {
25697            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
25698        }
25699    }
25700
25701    boolean canHaveOatDir(String packageName) {
25702        synchronized (mPackages) {
25703            PackageParser.Package p = mPackages.get(packageName);
25704            if (p == null) {
25705                return false;
25706            }
25707            return p.canHaveOatDir();
25708        }
25709    }
25710
25711    private String getOatDir(PackageParser.Package pkg) {
25712        if (!pkg.canHaveOatDir()) {
25713            return null;
25714        }
25715        File codePath = new File(pkg.codePath);
25716        if (codePath.isDirectory()) {
25717            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
25718        }
25719        return null;
25720    }
25721
25722    void deleteOatArtifactsOfPackage(String packageName) {
25723        final String[] instructionSets;
25724        final List<String> codePaths;
25725        final String oatDir;
25726        final PackageParser.Package pkg;
25727        synchronized (mPackages) {
25728            pkg = mPackages.get(packageName);
25729        }
25730        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
25731        codePaths = pkg.getAllCodePaths();
25732        oatDir = getOatDir(pkg);
25733
25734        for (String codePath : codePaths) {
25735            for (String isa : instructionSets) {
25736                try {
25737                    mInstaller.deleteOdex(codePath, isa, oatDir);
25738                } catch (InstallerException e) {
25739                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
25740                }
25741            }
25742        }
25743    }
25744
25745    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
25746        Set<String> unusedPackages = new HashSet<>();
25747        long currentTimeInMillis = System.currentTimeMillis();
25748        synchronized (mPackages) {
25749            for (PackageParser.Package pkg : mPackages.values()) {
25750                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
25751                if (ps == null) {
25752                    continue;
25753                }
25754                PackageDexUsage.PackageUseInfo packageUseInfo =
25755                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
25756                if (PackageManagerServiceUtils
25757                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
25758                                downgradeTimeThresholdMillis, packageUseInfo,
25759                                pkg.getLatestPackageUseTimeInMills(),
25760                                pkg.getLatestForegroundPackageUseTimeInMills())) {
25761                    unusedPackages.add(pkg.packageName);
25762                }
25763            }
25764        }
25765        return unusedPackages;
25766    }
25767}
25768
25769interface PackageSender {
25770    void sendPackageBroadcast(final String action, final String pkg,
25771        final Bundle extras, final int flags, final String targetPkg,
25772        final IIntentReceiver finishedReceiver, final int[] userIds);
25773    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
25774        boolean includeStopped, int appId, int... userIds);
25775}
25776