PackageManagerService.java revision df113c36a70474584bc9ef5bc1b3008a25fa86e0
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
581    public static final int REASON_LAST = REASON_INACTIVE_PACKAGE_DOWNGRADE;
582
583    /** All dangerous permission names in the same order as the events in MetricsEvent */
584    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
585            Manifest.permission.READ_CALENDAR,
586            Manifest.permission.WRITE_CALENDAR,
587            Manifest.permission.CAMERA,
588            Manifest.permission.READ_CONTACTS,
589            Manifest.permission.WRITE_CONTACTS,
590            Manifest.permission.GET_ACCOUNTS,
591            Manifest.permission.ACCESS_FINE_LOCATION,
592            Manifest.permission.ACCESS_COARSE_LOCATION,
593            Manifest.permission.RECORD_AUDIO,
594            Manifest.permission.READ_PHONE_STATE,
595            Manifest.permission.CALL_PHONE,
596            Manifest.permission.READ_CALL_LOG,
597            Manifest.permission.WRITE_CALL_LOG,
598            Manifest.permission.ADD_VOICEMAIL,
599            Manifest.permission.USE_SIP,
600            Manifest.permission.PROCESS_OUTGOING_CALLS,
601            Manifest.permission.READ_CELL_BROADCASTS,
602            Manifest.permission.BODY_SENSORS,
603            Manifest.permission.SEND_SMS,
604            Manifest.permission.RECEIVE_SMS,
605            Manifest.permission.READ_SMS,
606            Manifest.permission.RECEIVE_WAP_PUSH,
607            Manifest.permission.RECEIVE_MMS,
608            Manifest.permission.READ_EXTERNAL_STORAGE,
609            Manifest.permission.WRITE_EXTERNAL_STORAGE,
610            Manifest.permission.READ_PHONE_NUMBERS,
611            Manifest.permission.ANSWER_PHONE_CALLS);
612
613
614    /**
615     * Version number for the package parser cache. Increment this whenever the format or
616     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
617     */
618    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
619
620    /**
621     * Whether the package parser cache is enabled.
622     */
623    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
624
625    final ServiceThread mHandlerThread;
626
627    final PackageHandler mHandler;
628
629    private final ProcessLoggingHandler mProcessLoggingHandler;
630
631    /**
632     * Messages for {@link #mHandler} that need to wait for system ready before
633     * being dispatched.
634     */
635    private ArrayList<Message> mPostSystemReadyMessages;
636
637    final int mSdkVersion = Build.VERSION.SDK_INT;
638
639    final Context mContext;
640    final boolean mFactoryTest;
641    final boolean mOnlyCore;
642    final DisplayMetrics mMetrics;
643    final int mDefParseFlags;
644    final String[] mSeparateProcesses;
645    final boolean mIsUpgrade;
646    final boolean mIsPreNUpgrade;
647    final boolean mIsPreNMR1Upgrade;
648
649    // Have we told the Activity Manager to whitelist the default container service by uid yet?
650    @GuardedBy("mPackages")
651    boolean mDefaultContainerWhitelisted = false;
652
653    @GuardedBy("mPackages")
654    private boolean mDexOptDialogShown;
655
656    /** The location for ASEC container files on internal storage. */
657    final String mAsecInternalPath;
658
659    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
660    // LOCK HELD.  Can be called with mInstallLock held.
661    @GuardedBy("mInstallLock")
662    final Installer mInstaller;
663
664    /** Directory where installed third-party apps stored */
665    final File mAppInstallDir;
666
667    /**
668     * Directory to which applications installed internally have their
669     * 32 bit native libraries copied.
670     */
671    private File mAppLib32InstallDir;
672
673    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
674    // apps.
675    final File mDrmAppPrivateInstallDir;
676
677    // ----------------------------------------------------------------
678
679    // Lock for state used when installing and doing other long running
680    // operations.  Methods that must be called with this lock held have
681    // the suffix "LI".
682    final Object mInstallLock = new Object();
683
684    // ----------------------------------------------------------------
685
686    // Keys are String (package name), values are Package.  This also serves
687    // as the lock for the global state.  Methods that must be called with
688    // this lock held have the prefix "LP".
689    @GuardedBy("mPackages")
690    final ArrayMap<String, PackageParser.Package> mPackages =
691            new ArrayMap<String, PackageParser.Package>();
692
693    final ArrayMap<String, Set<String>> mKnownCodebase =
694            new ArrayMap<String, Set<String>>();
695
696    // Keys are isolated uids and values are the uid of the application
697    // that created the isolated proccess.
698    @GuardedBy("mPackages")
699    final SparseIntArray mIsolatedOwners = new SparseIntArray();
700
701    /**
702     * Tracks new system packages [received in an OTA] that we expect to
703     * find updated user-installed versions. Keys are package name, values
704     * are package location.
705     */
706    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
707    /**
708     * Tracks high priority intent filters for protected actions. During boot, certain
709     * filter actions are protected and should never be allowed to have a high priority
710     * intent filter for them. However, there is one, and only one exception -- the
711     * setup wizard. It must be able to define a high priority intent filter for these
712     * actions to ensure there are no escapes from the wizard. We need to delay processing
713     * of these during boot as we need to look at all of the system packages in order
714     * to know which component is the setup wizard.
715     */
716    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
717    /**
718     * Whether or not processing protected filters should be deferred.
719     */
720    private boolean mDeferProtectedFilters = true;
721
722    /**
723     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
724     */
725    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
726    /**
727     * Whether or not system app permissions should be promoted from install to runtime.
728     */
729    boolean mPromoteSystemApps;
730
731    @GuardedBy("mPackages")
732    final Settings mSettings;
733
734    /**
735     * Set of package names that are currently "frozen", which means active
736     * surgery is being done on the code/data for that package. The platform
737     * will refuse to launch frozen packages to avoid race conditions.
738     *
739     * @see PackageFreezer
740     */
741    @GuardedBy("mPackages")
742    final ArraySet<String> mFrozenPackages = new ArraySet<>();
743
744    final ProtectedPackages mProtectedPackages;
745
746    @GuardedBy("mLoadedVolumes")
747    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
748
749    boolean mFirstBoot;
750
751    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
752
753    // System configuration read by SystemConfig.
754    final int[] mGlobalGids;
755    final SparseArray<ArraySet<String>> mSystemPermissions;
756    @GuardedBy("mAvailableFeatures")
757    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
758
759    // If mac_permissions.xml was found for seinfo labeling.
760    boolean mFoundPolicyFile;
761
762    private final InstantAppRegistry mInstantAppRegistry;
763
764    @GuardedBy("mPackages")
765    int mChangedPackagesSequenceNumber;
766    /**
767     * List of changed [installed, removed or updated] packages.
768     * mapping from user id -> sequence number -> package name
769     */
770    @GuardedBy("mPackages")
771    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
772    /**
773     * The sequence number of the last change to a package.
774     * mapping from user id -> package name -> sequence number
775     */
776    @GuardedBy("mPackages")
777    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
778
779    class PackageParserCallback implements PackageParser.Callback {
780        @Override public final boolean hasFeature(String feature) {
781            return PackageManagerService.this.hasSystemFeature(feature, 0);
782        }
783
784        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
785                Collection<PackageParser.Package> allPackages, String targetPackageName) {
786            List<PackageParser.Package> overlayPackages = null;
787            for (PackageParser.Package p : allPackages) {
788                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
789                    if (overlayPackages == null) {
790                        overlayPackages = new ArrayList<PackageParser.Package>();
791                    }
792                    overlayPackages.add(p);
793                }
794            }
795            if (overlayPackages != null) {
796                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
797                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
798                        return p1.mOverlayPriority - p2.mOverlayPriority;
799                    }
800                };
801                Collections.sort(overlayPackages, cmp);
802            }
803            return overlayPackages;
804        }
805
806        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
807                String targetPackageName, String targetPath) {
808            if ("android".equals(targetPackageName)) {
809                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
810                // native AssetManager.
811                return null;
812            }
813            List<PackageParser.Package> overlayPackages =
814                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
815            if (overlayPackages == null || overlayPackages.isEmpty()) {
816                return null;
817            }
818            List<String> overlayPathList = null;
819            for (PackageParser.Package overlayPackage : overlayPackages) {
820                if (targetPath == null) {
821                    if (overlayPathList == null) {
822                        overlayPathList = new ArrayList<String>();
823                    }
824                    overlayPathList.add(overlayPackage.baseCodePath);
825                    continue;
826                }
827
828                try {
829                    // Creates idmaps for system to parse correctly the Android manifest of the
830                    // target package.
831                    //
832                    // OverlayManagerService will update each of them with a correct gid from its
833                    // target package app id.
834                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
835                            UserHandle.getSharedAppGid(
836                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
837                    if (overlayPathList == null) {
838                        overlayPathList = new ArrayList<String>();
839                    }
840                    overlayPathList.add(overlayPackage.baseCodePath);
841                } catch (InstallerException e) {
842                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
843                            overlayPackage.baseCodePath);
844                }
845            }
846            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
847        }
848
849        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
850            synchronized (mPackages) {
851                return getStaticOverlayPathsLocked(
852                        mPackages.values(), targetPackageName, targetPath);
853            }
854        }
855
856        @Override public final String[] getOverlayApks(String targetPackageName) {
857            return getStaticOverlayPaths(targetPackageName, null);
858        }
859
860        @Override public final String[] getOverlayPaths(String targetPackageName,
861                String targetPath) {
862            return getStaticOverlayPaths(targetPackageName, targetPath);
863        }
864    };
865
866    class ParallelPackageParserCallback extends PackageParserCallback {
867        List<PackageParser.Package> mOverlayPackages = null;
868
869        void findStaticOverlayPackages() {
870            synchronized (mPackages) {
871                for (PackageParser.Package p : mPackages.values()) {
872                    if (p.mIsStaticOverlay) {
873                        if (mOverlayPackages == null) {
874                            mOverlayPackages = new ArrayList<PackageParser.Package>();
875                        }
876                        mOverlayPackages.add(p);
877                    }
878                }
879            }
880        }
881
882        @Override
883        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
884            // We can trust mOverlayPackages without holding mPackages because package uninstall
885            // can't happen while running parallel parsing.
886            // Moreover holding mPackages on each parsing thread causes dead-lock.
887            return mOverlayPackages == null ? null :
888                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
889        }
890    }
891
892    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
893    final ParallelPackageParserCallback mParallelPackageParserCallback =
894            new ParallelPackageParserCallback();
895
896    public static final class SharedLibraryEntry {
897        public final @Nullable String path;
898        public final @Nullable String apk;
899        public final @NonNull SharedLibraryInfo info;
900
901        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
902                String declaringPackageName, int declaringPackageVersionCode) {
903            path = _path;
904            apk = _apk;
905            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
906                    declaringPackageName, declaringPackageVersionCode), null);
907        }
908    }
909
910    // Currently known shared libraries.
911    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
912    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
913            new ArrayMap<>();
914
915    // All available activities, for your resolving pleasure.
916    final ActivityIntentResolver mActivities =
917            new ActivityIntentResolver();
918
919    // All available receivers, for your resolving pleasure.
920    final ActivityIntentResolver mReceivers =
921            new ActivityIntentResolver();
922
923    // All available services, for your resolving pleasure.
924    final ServiceIntentResolver mServices = new ServiceIntentResolver();
925
926    // All available providers, for your resolving pleasure.
927    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
928
929    // Mapping from provider base names (first directory in content URI codePath)
930    // to the provider information.
931    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
932            new ArrayMap<String, PackageParser.Provider>();
933
934    // Mapping from instrumentation class names to info about them.
935    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
936            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
937
938    // Mapping from permission names to info about them.
939    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
940            new ArrayMap<String, PackageParser.PermissionGroup>();
941
942    // Packages whose data we have transfered into another package, thus
943    // should no longer exist.
944    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
945
946    // Broadcast actions that are only available to the system.
947    @GuardedBy("mProtectedBroadcasts")
948    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
949
950    /** List of packages waiting for verification. */
951    final SparseArray<PackageVerificationState> mPendingVerification
952            = new SparseArray<PackageVerificationState>();
953
954    /** Set of packages associated with each app op permission. */
955    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
956
957    final PackageInstallerService mInstallerService;
958
959    private final PackageDexOptimizer mPackageDexOptimizer;
960    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
961    // is used by other apps).
962    private final DexManager mDexManager;
963
964    private AtomicInteger mNextMoveId = new AtomicInteger();
965    private final MoveCallbacks mMoveCallbacks;
966
967    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
968
969    // Cache of users who need badging.
970    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
971
972    /** Token for keys in mPendingVerification. */
973    private int mPendingVerificationToken = 0;
974
975    volatile boolean mSystemReady;
976    volatile boolean mSafeMode;
977    volatile boolean mHasSystemUidErrors;
978    private volatile boolean mEphemeralAppsDisabled;
979
980    ApplicationInfo mAndroidApplication;
981    final ActivityInfo mResolveActivity = new ActivityInfo();
982    final ResolveInfo mResolveInfo = new ResolveInfo();
983    ComponentName mResolveComponentName;
984    PackageParser.Package mPlatformPackage;
985    ComponentName mCustomResolverComponentName;
986
987    boolean mResolverReplaced = false;
988
989    private final @Nullable ComponentName mIntentFilterVerifierComponent;
990    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
991
992    private int mIntentFilterVerificationToken = 0;
993
994    /** The service connection to the ephemeral resolver */
995    final EphemeralResolverConnection mInstantAppResolverConnection;
996    /** Component used to show resolver settings for Instant Apps */
997    final ComponentName mInstantAppResolverSettingsComponent;
998
999    /** Activity used to install instant applications */
1000    ActivityInfo mInstantAppInstallerActivity;
1001    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
1002
1003    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
1004            = new SparseArray<IntentFilterVerificationState>();
1005
1006    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
1007
1008    // List of packages names to keep cached, even if they are uninstalled for all users
1009    private List<String> mKeepUninstalledPackages;
1010
1011    private UserManagerInternal mUserManagerInternal;
1012
1013    private DeviceIdleController.LocalService mDeviceIdleController;
1014
1015    private File mCacheDir;
1016
1017    private ArraySet<String> mPrivappPermissionsViolations;
1018
1019    private Future<?> mPrepareAppDataFuture;
1020
1021    private static class IFVerificationParams {
1022        PackageParser.Package pkg;
1023        boolean replacing;
1024        int userId;
1025        int verifierUid;
1026
1027        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1028                int _userId, int _verifierUid) {
1029            pkg = _pkg;
1030            replacing = _replacing;
1031            userId = _userId;
1032            replacing = _replacing;
1033            verifierUid = _verifierUid;
1034        }
1035    }
1036
1037    private interface IntentFilterVerifier<T extends IntentFilter> {
1038        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1039                                               T filter, String packageName);
1040        void startVerifications(int userId);
1041        void receiveVerificationResponse(int verificationId);
1042    }
1043
1044    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1045        private Context mContext;
1046        private ComponentName mIntentFilterVerifierComponent;
1047        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1048
1049        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1050            mContext = context;
1051            mIntentFilterVerifierComponent = verifierComponent;
1052        }
1053
1054        private String getDefaultScheme() {
1055            return IntentFilter.SCHEME_HTTPS;
1056        }
1057
1058        @Override
1059        public void startVerifications(int userId) {
1060            // Launch verifications requests
1061            int count = mCurrentIntentFilterVerifications.size();
1062            for (int n=0; n<count; n++) {
1063                int verificationId = mCurrentIntentFilterVerifications.get(n);
1064                final IntentFilterVerificationState ivs =
1065                        mIntentFilterVerificationStates.get(verificationId);
1066
1067                String packageName = ivs.getPackageName();
1068
1069                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1070                final int filterCount = filters.size();
1071                ArraySet<String> domainsSet = new ArraySet<>();
1072                for (int m=0; m<filterCount; m++) {
1073                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1074                    domainsSet.addAll(filter.getHostsList());
1075                }
1076                synchronized (mPackages) {
1077                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1078                            packageName, domainsSet) != null) {
1079                        scheduleWriteSettingsLocked();
1080                    }
1081                }
1082                sendVerificationRequest(verificationId, ivs);
1083            }
1084            mCurrentIntentFilterVerifications.clear();
1085        }
1086
1087        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1088            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1089            verificationIntent.putExtra(
1090                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1091                    verificationId);
1092            verificationIntent.putExtra(
1093                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1094                    getDefaultScheme());
1095            verificationIntent.putExtra(
1096                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1097                    ivs.getHostsString());
1098            verificationIntent.putExtra(
1099                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1100                    ivs.getPackageName());
1101            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1102            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1103
1104            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1105            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1106                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1107                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1108
1109            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1110            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1111                    "Sending IntentFilter verification broadcast");
1112        }
1113
1114        public void receiveVerificationResponse(int verificationId) {
1115            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1116
1117            final boolean verified = ivs.isVerified();
1118
1119            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1120            final int count = filters.size();
1121            if (DEBUG_DOMAIN_VERIFICATION) {
1122                Slog.i(TAG, "Received verification response " + verificationId
1123                        + " for " + count + " filters, verified=" + verified);
1124            }
1125            for (int n=0; n<count; n++) {
1126                PackageParser.ActivityIntentInfo filter = filters.get(n);
1127                filter.setVerified(verified);
1128
1129                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1130                        + " verified with result:" + verified + " and hosts:"
1131                        + ivs.getHostsString());
1132            }
1133
1134            mIntentFilterVerificationStates.remove(verificationId);
1135
1136            final String packageName = ivs.getPackageName();
1137            IntentFilterVerificationInfo ivi = null;
1138
1139            synchronized (mPackages) {
1140                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1141            }
1142            if (ivi == null) {
1143                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1144                        + verificationId + " packageName:" + packageName);
1145                return;
1146            }
1147            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1148                    "Updating IntentFilterVerificationInfo for package " + packageName
1149                            +" verificationId:" + verificationId);
1150
1151            synchronized (mPackages) {
1152                if (verified) {
1153                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1154                } else {
1155                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1156                }
1157                scheduleWriteSettingsLocked();
1158
1159                final int userId = ivs.getUserId();
1160                if (userId != UserHandle.USER_ALL) {
1161                    final int userStatus =
1162                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1163
1164                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1165                    boolean needUpdate = false;
1166
1167                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1168                    // already been set by the User thru the Disambiguation dialog
1169                    switch (userStatus) {
1170                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1171                            if (verified) {
1172                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1173                            } else {
1174                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1175                            }
1176                            needUpdate = true;
1177                            break;
1178
1179                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1180                            if (verified) {
1181                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1182                                needUpdate = true;
1183                            }
1184                            break;
1185
1186                        default:
1187                            // Nothing to do
1188                    }
1189
1190                    if (needUpdate) {
1191                        mSettings.updateIntentFilterVerificationStatusLPw(
1192                                packageName, updatedStatus, userId);
1193                        scheduleWritePackageRestrictionsLocked(userId);
1194                    }
1195                }
1196            }
1197        }
1198
1199        @Override
1200        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1201                    ActivityIntentInfo filter, String packageName) {
1202            if (!hasValidDomains(filter)) {
1203                return false;
1204            }
1205            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1206            if (ivs == null) {
1207                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1208                        packageName);
1209            }
1210            if (DEBUG_DOMAIN_VERIFICATION) {
1211                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1212            }
1213            ivs.addFilter(filter);
1214            return true;
1215        }
1216
1217        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1218                int userId, int verificationId, String packageName) {
1219            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1220                    verifierUid, userId, packageName);
1221            ivs.setPendingState();
1222            synchronized (mPackages) {
1223                mIntentFilterVerificationStates.append(verificationId, ivs);
1224                mCurrentIntentFilterVerifications.add(verificationId);
1225            }
1226            return ivs;
1227        }
1228    }
1229
1230    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1231        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1232                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1233                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1234    }
1235
1236    // Set of pending broadcasts for aggregating enable/disable of components.
1237    static class PendingPackageBroadcasts {
1238        // for each user id, a map of <package name -> components within that package>
1239        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1240
1241        public PendingPackageBroadcasts() {
1242            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1243        }
1244
1245        public ArrayList<String> get(int userId, String packageName) {
1246            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1247            return packages.get(packageName);
1248        }
1249
1250        public void put(int userId, String packageName, ArrayList<String> components) {
1251            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1252            packages.put(packageName, components);
1253        }
1254
1255        public void remove(int userId, String packageName) {
1256            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1257            if (packages != null) {
1258                packages.remove(packageName);
1259            }
1260        }
1261
1262        public void remove(int userId) {
1263            mUidMap.remove(userId);
1264        }
1265
1266        public int userIdCount() {
1267            return mUidMap.size();
1268        }
1269
1270        public int userIdAt(int n) {
1271            return mUidMap.keyAt(n);
1272        }
1273
1274        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1275            return mUidMap.get(userId);
1276        }
1277
1278        public int size() {
1279            // total number of pending broadcast entries across all userIds
1280            int num = 0;
1281            for (int i = 0; i< mUidMap.size(); i++) {
1282                num += mUidMap.valueAt(i).size();
1283            }
1284            return num;
1285        }
1286
1287        public void clear() {
1288            mUidMap.clear();
1289        }
1290
1291        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1292            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1293            if (map == null) {
1294                map = new ArrayMap<String, ArrayList<String>>();
1295                mUidMap.put(userId, map);
1296            }
1297            return map;
1298        }
1299    }
1300    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1301
1302    // Service Connection to remote media container service to copy
1303    // package uri's from external media onto secure containers
1304    // or internal storage.
1305    private IMediaContainerService mContainerService = null;
1306
1307    static final int SEND_PENDING_BROADCAST = 1;
1308    static final int MCS_BOUND = 3;
1309    static final int END_COPY = 4;
1310    static final int INIT_COPY = 5;
1311    static final int MCS_UNBIND = 6;
1312    static final int START_CLEANING_PACKAGE = 7;
1313    static final int FIND_INSTALL_LOC = 8;
1314    static final int POST_INSTALL = 9;
1315    static final int MCS_RECONNECT = 10;
1316    static final int MCS_GIVE_UP = 11;
1317    static final int UPDATED_MEDIA_STATUS = 12;
1318    static final int WRITE_SETTINGS = 13;
1319    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1320    static final int PACKAGE_VERIFIED = 15;
1321    static final int CHECK_PENDING_VERIFICATION = 16;
1322    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1323    static final int INTENT_FILTER_VERIFIED = 18;
1324    static final int WRITE_PACKAGE_LIST = 19;
1325    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1326
1327    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1328
1329    // Delay time in millisecs
1330    static final int BROADCAST_DELAY = 10 * 1000;
1331
1332    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1333            2 * 60 * 60 * 1000L; /* two hours */
1334
1335    static UserManagerService sUserManager;
1336
1337    // Stores a list of users whose package restrictions file needs to be updated
1338    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1339
1340    final private DefaultContainerConnection mDefContainerConn =
1341            new DefaultContainerConnection();
1342    class DefaultContainerConnection implements ServiceConnection {
1343        public void onServiceConnected(ComponentName name, IBinder service) {
1344            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1345            final IMediaContainerService imcs = IMediaContainerService.Stub
1346                    .asInterface(Binder.allowBlocking(service));
1347            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1348        }
1349
1350        public void onServiceDisconnected(ComponentName name) {
1351            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1352        }
1353    }
1354
1355    // Recordkeeping of restore-after-install operations that are currently in flight
1356    // between the Package Manager and the Backup Manager
1357    static class PostInstallData {
1358        public InstallArgs args;
1359        public PackageInstalledInfo res;
1360
1361        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1362            args = _a;
1363            res = _r;
1364        }
1365    }
1366
1367    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1368    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1369
1370    // XML tags for backup/restore of various bits of state
1371    private static final String TAG_PREFERRED_BACKUP = "pa";
1372    private static final String TAG_DEFAULT_APPS = "da";
1373    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1374
1375    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1376    private static final String TAG_ALL_GRANTS = "rt-grants";
1377    private static final String TAG_GRANT = "grant";
1378    private static final String ATTR_PACKAGE_NAME = "pkg";
1379
1380    private static final String TAG_PERMISSION = "perm";
1381    private static final String ATTR_PERMISSION_NAME = "name";
1382    private static final String ATTR_IS_GRANTED = "g";
1383    private static final String ATTR_USER_SET = "set";
1384    private static final String ATTR_USER_FIXED = "fixed";
1385    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1386
1387    // System/policy permission grants are not backed up
1388    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1389            FLAG_PERMISSION_POLICY_FIXED
1390            | FLAG_PERMISSION_SYSTEM_FIXED
1391            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1392
1393    // And we back up these user-adjusted states
1394    private static final int USER_RUNTIME_GRANT_MASK =
1395            FLAG_PERMISSION_USER_SET
1396            | FLAG_PERMISSION_USER_FIXED
1397            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1398
1399    final @Nullable String mRequiredVerifierPackage;
1400    final @NonNull String mRequiredInstallerPackage;
1401    final @NonNull String mRequiredUninstallerPackage;
1402    final @Nullable String mSetupWizardPackage;
1403    final @Nullable String mStorageManagerPackage;
1404    final @NonNull String mServicesSystemSharedLibraryPackageName;
1405    final @NonNull String mSharedSystemSharedLibraryPackageName;
1406
1407    final boolean mPermissionReviewRequired;
1408
1409    private final PackageUsage mPackageUsage = new PackageUsage();
1410    private final CompilerStats mCompilerStats = new CompilerStats();
1411
1412    class PackageHandler extends Handler {
1413        private boolean mBound = false;
1414        final ArrayList<HandlerParams> mPendingInstalls =
1415            new ArrayList<HandlerParams>();
1416
1417        private boolean connectToService() {
1418            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1419                    " DefaultContainerService");
1420            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1421            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1422            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1423                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1424                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1425                mBound = true;
1426                return true;
1427            }
1428            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1429            return false;
1430        }
1431
1432        private void disconnectService() {
1433            mContainerService = null;
1434            mBound = false;
1435            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1436            mContext.unbindService(mDefContainerConn);
1437            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1438        }
1439
1440        PackageHandler(Looper looper) {
1441            super(looper);
1442        }
1443
1444        public void handleMessage(Message msg) {
1445            try {
1446                doHandleMessage(msg);
1447            } finally {
1448                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1449            }
1450        }
1451
1452        void doHandleMessage(Message msg) {
1453            switch (msg.what) {
1454                case INIT_COPY: {
1455                    HandlerParams params = (HandlerParams) msg.obj;
1456                    int idx = mPendingInstalls.size();
1457                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1458                    // If a bind was already initiated we dont really
1459                    // need to do anything. The pending install
1460                    // will be processed later on.
1461                    if (!mBound) {
1462                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1463                                System.identityHashCode(mHandler));
1464                        // If this is the only one pending we might
1465                        // have to bind to the service again.
1466                        if (!connectToService()) {
1467                            Slog.e(TAG, "Failed to bind to media container service");
1468                            params.serviceError();
1469                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1470                                    System.identityHashCode(mHandler));
1471                            if (params.traceMethod != null) {
1472                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1473                                        params.traceCookie);
1474                            }
1475                            return;
1476                        } else {
1477                            // Once we bind to the service, the first
1478                            // pending request will be processed.
1479                            mPendingInstalls.add(idx, params);
1480                        }
1481                    } else {
1482                        mPendingInstalls.add(idx, params);
1483                        // Already bound to the service. Just make
1484                        // sure we trigger off processing the first request.
1485                        if (idx == 0) {
1486                            mHandler.sendEmptyMessage(MCS_BOUND);
1487                        }
1488                    }
1489                    break;
1490                }
1491                case MCS_BOUND: {
1492                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1493                    if (msg.obj != null) {
1494                        mContainerService = (IMediaContainerService) msg.obj;
1495                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1496                                System.identityHashCode(mHandler));
1497                    }
1498                    if (mContainerService == null) {
1499                        if (!mBound) {
1500                            // Something seriously wrong since we are not bound and we are not
1501                            // waiting for connection. Bail out.
1502                            Slog.e(TAG, "Cannot bind to media container service");
1503                            for (HandlerParams params : mPendingInstalls) {
1504                                // Indicate service bind error
1505                                params.serviceError();
1506                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1507                                        System.identityHashCode(params));
1508                                if (params.traceMethod != null) {
1509                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1510                                            params.traceMethod, params.traceCookie);
1511                                }
1512                                return;
1513                            }
1514                            mPendingInstalls.clear();
1515                        } else {
1516                            Slog.w(TAG, "Waiting to connect to media container service");
1517                        }
1518                    } else if (mPendingInstalls.size() > 0) {
1519                        HandlerParams params = mPendingInstalls.get(0);
1520                        if (params != null) {
1521                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1522                                    System.identityHashCode(params));
1523                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1524                            if (params.startCopy()) {
1525                                // We are done...  look for more work or to
1526                                // go idle.
1527                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1528                                        "Checking for more work or unbind...");
1529                                // Delete pending install
1530                                if (mPendingInstalls.size() > 0) {
1531                                    mPendingInstalls.remove(0);
1532                                }
1533                                if (mPendingInstalls.size() == 0) {
1534                                    if (mBound) {
1535                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1536                                                "Posting delayed MCS_UNBIND");
1537                                        removeMessages(MCS_UNBIND);
1538                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1539                                        // Unbind after a little delay, to avoid
1540                                        // continual thrashing.
1541                                        sendMessageDelayed(ubmsg, 10000);
1542                                    }
1543                                } else {
1544                                    // There are more pending requests in queue.
1545                                    // Just post MCS_BOUND message to trigger processing
1546                                    // of next pending install.
1547                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1548                                            "Posting MCS_BOUND for next work");
1549                                    mHandler.sendEmptyMessage(MCS_BOUND);
1550                                }
1551                            }
1552                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1553                        }
1554                    } else {
1555                        // Should never happen ideally.
1556                        Slog.w(TAG, "Empty queue");
1557                    }
1558                    break;
1559                }
1560                case MCS_RECONNECT: {
1561                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1562                    if (mPendingInstalls.size() > 0) {
1563                        if (mBound) {
1564                            disconnectService();
1565                        }
1566                        if (!connectToService()) {
1567                            Slog.e(TAG, "Failed to bind to media container service");
1568                            for (HandlerParams params : mPendingInstalls) {
1569                                // Indicate service bind error
1570                                params.serviceError();
1571                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1572                                        System.identityHashCode(params));
1573                            }
1574                            mPendingInstalls.clear();
1575                        }
1576                    }
1577                    break;
1578                }
1579                case MCS_UNBIND: {
1580                    // If there is no actual work left, then time to unbind.
1581                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1582
1583                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1584                        if (mBound) {
1585                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1586
1587                            disconnectService();
1588                        }
1589                    } else if (mPendingInstalls.size() > 0) {
1590                        // There are more pending requests in queue.
1591                        // Just post MCS_BOUND message to trigger processing
1592                        // of next pending install.
1593                        mHandler.sendEmptyMessage(MCS_BOUND);
1594                    }
1595
1596                    break;
1597                }
1598                case MCS_GIVE_UP: {
1599                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1600                    HandlerParams params = mPendingInstalls.remove(0);
1601                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1602                            System.identityHashCode(params));
1603                    break;
1604                }
1605                case SEND_PENDING_BROADCAST: {
1606                    String packages[];
1607                    ArrayList<String> components[];
1608                    int size = 0;
1609                    int uids[];
1610                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1611                    synchronized (mPackages) {
1612                        if (mPendingBroadcasts == null) {
1613                            return;
1614                        }
1615                        size = mPendingBroadcasts.size();
1616                        if (size <= 0) {
1617                            // Nothing to be done. Just return
1618                            return;
1619                        }
1620                        packages = new String[size];
1621                        components = new ArrayList[size];
1622                        uids = new int[size];
1623                        int i = 0;  // filling out the above arrays
1624
1625                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1626                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1627                            Iterator<Map.Entry<String, ArrayList<String>>> it
1628                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1629                                            .entrySet().iterator();
1630                            while (it.hasNext() && i < size) {
1631                                Map.Entry<String, ArrayList<String>> ent = it.next();
1632                                packages[i] = ent.getKey();
1633                                components[i] = ent.getValue();
1634                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1635                                uids[i] = (ps != null)
1636                                        ? UserHandle.getUid(packageUserId, ps.appId)
1637                                        : -1;
1638                                i++;
1639                            }
1640                        }
1641                        size = i;
1642                        mPendingBroadcasts.clear();
1643                    }
1644                    // Send broadcasts
1645                    for (int i = 0; i < size; i++) {
1646                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1647                    }
1648                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1649                    break;
1650                }
1651                case START_CLEANING_PACKAGE: {
1652                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1653                    final String packageName = (String)msg.obj;
1654                    final int userId = msg.arg1;
1655                    final boolean andCode = msg.arg2 != 0;
1656                    synchronized (mPackages) {
1657                        if (userId == UserHandle.USER_ALL) {
1658                            int[] users = sUserManager.getUserIds();
1659                            for (int user : users) {
1660                                mSettings.addPackageToCleanLPw(
1661                                        new PackageCleanItem(user, packageName, andCode));
1662                            }
1663                        } else {
1664                            mSettings.addPackageToCleanLPw(
1665                                    new PackageCleanItem(userId, packageName, andCode));
1666                        }
1667                    }
1668                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1669                    startCleaningPackages();
1670                } break;
1671                case POST_INSTALL: {
1672                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1673
1674                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1675                    final boolean didRestore = (msg.arg2 != 0);
1676                    mRunningInstalls.delete(msg.arg1);
1677
1678                    if (data != null) {
1679                        InstallArgs args = data.args;
1680                        PackageInstalledInfo parentRes = data.res;
1681
1682                        final boolean grantPermissions = (args.installFlags
1683                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1684                        final boolean killApp = (args.installFlags
1685                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1686                        final boolean virtualPreload = ((args.installFlags
1687                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1688                        final String[] grantedPermissions = args.installGrantPermissions;
1689
1690                        // Handle the parent package
1691                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1692                                virtualPreload, grantedPermissions, didRestore,
1693                                args.installerPackageName, args.observer);
1694
1695                        // Handle the child packages
1696                        final int childCount = (parentRes.addedChildPackages != null)
1697                                ? parentRes.addedChildPackages.size() : 0;
1698                        for (int i = 0; i < childCount; i++) {
1699                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1700                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1701                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1702                                    args.installerPackageName, args.observer);
1703                        }
1704
1705                        // Log tracing if needed
1706                        if (args.traceMethod != null) {
1707                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1708                                    args.traceCookie);
1709                        }
1710                    } else {
1711                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1712                    }
1713
1714                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1715                } break;
1716                case UPDATED_MEDIA_STATUS: {
1717                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1718                    boolean reportStatus = msg.arg1 == 1;
1719                    boolean doGc = msg.arg2 == 1;
1720                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1721                    if (doGc) {
1722                        // Force a gc to clear up stale containers.
1723                        Runtime.getRuntime().gc();
1724                    }
1725                    if (msg.obj != null) {
1726                        @SuppressWarnings("unchecked")
1727                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1728                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1729                        // Unload containers
1730                        unloadAllContainers(args);
1731                    }
1732                    if (reportStatus) {
1733                        try {
1734                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1735                                    "Invoking StorageManagerService call back");
1736                            PackageHelper.getStorageManager().finishMediaUpdate();
1737                        } catch (RemoteException e) {
1738                            Log.e(TAG, "StorageManagerService not running?");
1739                        }
1740                    }
1741                } break;
1742                case WRITE_SETTINGS: {
1743                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1744                    synchronized (mPackages) {
1745                        removeMessages(WRITE_SETTINGS);
1746                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1747                        mSettings.writeLPr();
1748                        mDirtyUsers.clear();
1749                    }
1750                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1751                } break;
1752                case WRITE_PACKAGE_RESTRICTIONS: {
1753                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1754                    synchronized (mPackages) {
1755                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1756                        for (int userId : mDirtyUsers) {
1757                            mSettings.writePackageRestrictionsLPr(userId);
1758                        }
1759                        mDirtyUsers.clear();
1760                    }
1761                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1762                } break;
1763                case WRITE_PACKAGE_LIST: {
1764                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1765                    synchronized (mPackages) {
1766                        removeMessages(WRITE_PACKAGE_LIST);
1767                        mSettings.writePackageListLPr(msg.arg1);
1768                    }
1769                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1770                } break;
1771                case CHECK_PENDING_VERIFICATION: {
1772                    final int verificationId = msg.arg1;
1773                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1774
1775                    if ((state != null) && !state.timeoutExtended()) {
1776                        final InstallArgs args = state.getInstallArgs();
1777                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1778
1779                        Slog.i(TAG, "Verification timed out for " + originUri);
1780                        mPendingVerification.remove(verificationId);
1781
1782                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1783
1784                        final UserHandle user = args.getUser();
1785                        if (getDefaultVerificationResponse(user)
1786                                == PackageManager.VERIFICATION_ALLOW) {
1787                            Slog.i(TAG, "Continuing with installation of " + originUri);
1788                            state.setVerifierResponse(Binder.getCallingUid(),
1789                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1790                            broadcastPackageVerified(verificationId, originUri,
1791                                    PackageManager.VERIFICATION_ALLOW, user);
1792                            try {
1793                                ret = args.copyApk(mContainerService, true);
1794                            } catch (RemoteException e) {
1795                                Slog.e(TAG, "Could not contact the ContainerService");
1796                            }
1797                        } else {
1798                            broadcastPackageVerified(verificationId, originUri,
1799                                    PackageManager.VERIFICATION_REJECT, user);
1800                        }
1801
1802                        Trace.asyncTraceEnd(
1803                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1804
1805                        processPendingInstall(args, ret);
1806                        mHandler.sendEmptyMessage(MCS_UNBIND);
1807                    }
1808                    break;
1809                }
1810                case PACKAGE_VERIFIED: {
1811                    final int verificationId = msg.arg1;
1812
1813                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1814                    if (state == null) {
1815                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1816                        break;
1817                    }
1818
1819                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1820
1821                    state.setVerifierResponse(response.callerUid, response.code);
1822
1823                    if (state.isVerificationComplete()) {
1824                        mPendingVerification.remove(verificationId);
1825
1826                        final InstallArgs args = state.getInstallArgs();
1827                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1828
1829                        int ret;
1830                        if (state.isInstallAllowed()) {
1831                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1832                            broadcastPackageVerified(verificationId, originUri,
1833                                    response.code, state.getInstallArgs().getUser());
1834                            try {
1835                                ret = args.copyApk(mContainerService, true);
1836                            } catch (RemoteException e) {
1837                                Slog.e(TAG, "Could not contact the ContainerService");
1838                            }
1839                        } else {
1840                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1841                        }
1842
1843                        Trace.asyncTraceEnd(
1844                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1845
1846                        processPendingInstall(args, ret);
1847                        mHandler.sendEmptyMessage(MCS_UNBIND);
1848                    }
1849
1850                    break;
1851                }
1852                case START_INTENT_FILTER_VERIFICATIONS: {
1853                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1854                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1855                            params.replacing, params.pkg);
1856                    break;
1857                }
1858                case INTENT_FILTER_VERIFIED: {
1859                    final int verificationId = msg.arg1;
1860
1861                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1862                            verificationId);
1863                    if (state == null) {
1864                        Slog.w(TAG, "Invalid IntentFilter verification token "
1865                                + verificationId + " received");
1866                        break;
1867                    }
1868
1869                    final int userId = state.getUserId();
1870
1871                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1872                            "Processing IntentFilter verification with token:"
1873                            + verificationId + " and userId:" + userId);
1874
1875                    final IntentFilterVerificationResponse response =
1876                            (IntentFilterVerificationResponse) msg.obj;
1877
1878                    state.setVerifierResponse(response.callerUid, response.code);
1879
1880                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1881                            "IntentFilter verification with token:" + verificationId
1882                            + " and userId:" + userId
1883                            + " is settings verifier response with response code:"
1884                            + response.code);
1885
1886                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1887                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1888                                + response.getFailedDomainsString());
1889                    }
1890
1891                    if (state.isVerificationComplete()) {
1892                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1893                    } else {
1894                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1895                                "IntentFilter verification with token:" + verificationId
1896                                + " was not said to be complete");
1897                    }
1898
1899                    break;
1900                }
1901                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1902                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1903                            mInstantAppResolverConnection,
1904                            (InstantAppRequest) msg.obj,
1905                            mInstantAppInstallerActivity,
1906                            mHandler);
1907                }
1908            }
1909        }
1910    }
1911
1912    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1913            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1914            boolean launchedForRestore, String installerPackage,
1915            IPackageInstallObserver2 installObserver) {
1916        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1917            // Send the removed broadcasts
1918            if (res.removedInfo != null) {
1919                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1920            }
1921
1922            // Now that we successfully installed the package, grant runtime
1923            // permissions if requested before broadcasting the install. Also
1924            // for legacy apps in permission review mode we clear the permission
1925            // review flag which is used to emulate runtime permissions for
1926            // legacy apps.
1927            if (grantPermissions) {
1928                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1929            }
1930
1931            final boolean update = res.removedInfo != null
1932                    && res.removedInfo.removedPackage != null;
1933            final String installerPackageName =
1934                    res.installerPackageName != null
1935                            ? res.installerPackageName
1936                            : res.removedInfo != null
1937                                    ? res.removedInfo.installerPackageName
1938                                    : null;
1939
1940            // If this is the first time we have child packages for a disabled privileged
1941            // app that had no children, we grant requested runtime permissions to the new
1942            // children if the parent on the system image had them already granted.
1943            if (res.pkg.parentPackage != null) {
1944                synchronized (mPackages) {
1945                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1946                }
1947            }
1948
1949            synchronized (mPackages) {
1950                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1951            }
1952
1953            final String packageName = res.pkg.applicationInfo.packageName;
1954
1955            // Determine the set of users who are adding this package for
1956            // the first time vs. those who are seeing an update.
1957            int[] firstUsers = EMPTY_INT_ARRAY;
1958            int[] updateUsers = EMPTY_INT_ARRAY;
1959            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1960            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1961            for (int newUser : res.newUsers) {
1962                if (ps.getInstantApp(newUser)) {
1963                    continue;
1964                }
1965                if (allNewUsers) {
1966                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1967                    continue;
1968                }
1969                boolean isNew = true;
1970                for (int origUser : res.origUsers) {
1971                    if (origUser == newUser) {
1972                        isNew = false;
1973                        break;
1974                    }
1975                }
1976                if (isNew) {
1977                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1978                } else {
1979                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1980                }
1981            }
1982
1983            // Send installed broadcasts if the package is not a static shared lib.
1984            if (res.pkg.staticSharedLibName == null) {
1985                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1986
1987                // Send added for users that see the package for the first time
1988                // sendPackageAddedForNewUsers also deals with system apps
1989                int appId = UserHandle.getAppId(res.uid);
1990                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1991                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
1992                        virtualPreload /*startReceiver*/, appId, firstUsers);
1993
1994                // Send added for users that don't see the package for the first time
1995                Bundle extras = new Bundle(1);
1996                extras.putInt(Intent.EXTRA_UID, res.uid);
1997                if (update) {
1998                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1999                }
2000                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2001                        extras, 0 /*flags*/,
2002                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
2003                if (installerPackageName != null) {
2004                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2005                            extras, 0 /*flags*/,
2006                            installerPackageName, null /*finishedReceiver*/, updateUsers);
2007                }
2008
2009                // Send replaced for users that don't see the package for the first time
2010                if (update) {
2011                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2012                            packageName, extras, 0 /*flags*/,
2013                            null /*targetPackage*/, null /*finishedReceiver*/,
2014                            updateUsers);
2015                    if (installerPackageName != null) {
2016                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2017                                extras, 0 /*flags*/,
2018                                installerPackageName, null /*finishedReceiver*/, updateUsers);
2019                    }
2020                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2021                            null /*package*/, null /*extras*/, 0 /*flags*/,
2022                            packageName /*targetPackage*/,
2023                            null /*finishedReceiver*/, updateUsers);
2024                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2025                    // First-install and we did a restore, so we're responsible for the
2026                    // first-launch broadcast.
2027                    if (DEBUG_BACKUP) {
2028                        Slog.i(TAG, "Post-restore of " + packageName
2029                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2030                    }
2031                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2032                }
2033
2034                // Send broadcast package appeared if forward locked/external for all users
2035                // treat asec-hosted packages like removable media on upgrade
2036                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2037                    if (DEBUG_INSTALL) {
2038                        Slog.i(TAG, "upgrading pkg " + res.pkg
2039                                + " is ASEC-hosted -> AVAILABLE");
2040                    }
2041                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2042                    ArrayList<String> pkgList = new ArrayList<>(1);
2043                    pkgList.add(packageName);
2044                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2045                }
2046            }
2047
2048            // Work that needs to happen on first install within each user
2049            if (firstUsers != null && firstUsers.length > 0) {
2050                synchronized (mPackages) {
2051                    for (int userId : firstUsers) {
2052                        // If this app is a browser and it's newly-installed for some
2053                        // users, clear any default-browser state in those users. The
2054                        // app's nature doesn't depend on the user, so we can just check
2055                        // its browser nature in any user and generalize.
2056                        if (packageIsBrowser(packageName, userId)) {
2057                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2058                        }
2059
2060                        // We may also need to apply pending (restored) runtime
2061                        // permission grants within these users.
2062                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2063                    }
2064                }
2065            }
2066
2067            // Log current value of "unknown sources" setting
2068            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2069                    getUnknownSourcesSettings());
2070
2071            // Remove the replaced package's older resources safely now
2072            // We delete after a gc for applications  on sdcard.
2073            if (res.removedInfo != null && res.removedInfo.args != null) {
2074                Runtime.getRuntime().gc();
2075                synchronized (mInstallLock) {
2076                    res.removedInfo.args.doPostDeleteLI(true);
2077                }
2078            } else {
2079                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2080                // and not block here.
2081                VMRuntime.getRuntime().requestConcurrentGC();
2082            }
2083
2084            // Notify DexManager that the package was installed for new users.
2085            // The updated users should already be indexed and the package code paths
2086            // should not change.
2087            // Don't notify the manager for ephemeral apps as they are not expected to
2088            // survive long enough to benefit of background optimizations.
2089            for (int userId : firstUsers) {
2090                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2091                // There's a race currently where some install events may interleave with an uninstall.
2092                // This can lead to package info being null (b/36642664).
2093                if (info != null) {
2094                    mDexManager.notifyPackageInstalled(info, userId);
2095                }
2096            }
2097        }
2098
2099        // If someone is watching installs - notify them
2100        if (installObserver != null) {
2101            try {
2102                Bundle extras = extrasForInstallResult(res);
2103                installObserver.onPackageInstalled(res.name, res.returnCode,
2104                        res.returnMsg, extras);
2105            } catch (RemoteException e) {
2106                Slog.i(TAG, "Observer no longer exists.");
2107            }
2108        }
2109    }
2110
2111    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2112            PackageParser.Package pkg) {
2113        if (pkg.parentPackage == null) {
2114            return;
2115        }
2116        if (pkg.requestedPermissions == null) {
2117            return;
2118        }
2119        final PackageSetting disabledSysParentPs = mSettings
2120                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2121        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2122                || !disabledSysParentPs.isPrivileged()
2123                || (disabledSysParentPs.childPackageNames != null
2124                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2125            return;
2126        }
2127        final int[] allUserIds = sUserManager.getUserIds();
2128        final int permCount = pkg.requestedPermissions.size();
2129        for (int i = 0; i < permCount; i++) {
2130            String permission = pkg.requestedPermissions.get(i);
2131            BasePermission bp = mSettings.mPermissions.get(permission);
2132            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2133                continue;
2134            }
2135            for (int userId : allUserIds) {
2136                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2137                        permission, userId)) {
2138                    grantRuntimePermission(pkg.packageName, permission, userId);
2139                }
2140            }
2141        }
2142    }
2143
2144    private StorageEventListener mStorageListener = new StorageEventListener() {
2145        @Override
2146        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2147            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2148                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2149                    final String volumeUuid = vol.getFsUuid();
2150
2151                    // Clean up any users or apps that were removed or recreated
2152                    // while this volume was missing
2153                    sUserManager.reconcileUsers(volumeUuid);
2154                    reconcileApps(volumeUuid);
2155
2156                    // Clean up any install sessions that expired or were
2157                    // cancelled while this volume was missing
2158                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2159
2160                    loadPrivatePackages(vol);
2161
2162                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2163                    unloadPrivatePackages(vol);
2164                }
2165            }
2166
2167            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2168                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2169                    updateExternalMediaStatus(true, false);
2170                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2171                    updateExternalMediaStatus(false, false);
2172                }
2173            }
2174        }
2175
2176        @Override
2177        public void onVolumeForgotten(String fsUuid) {
2178            if (TextUtils.isEmpty(fsUuid)) {
2179                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2180                return;
2181            }
2182
2183            // Remove any apps installed on the forgotten volume
2184            synchronized (mPackages) {
2185                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2186                for (PackageSetting ps : packages) {
2187                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2188                    deletePackageVersioned(new VersionedPackage(ps.name,
2189                            PackageManager.VERSION_CODE_HIGHEST),
2190                            new LegacyPackageDeleteObserver(null).getBinder(),
2191                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2192                    // Try very hard to release any references to this package
2193                    // so we don't risk the system server being killed due to
2194                    // open FDs
2195                    AttributeCache.instance().removePackage(ps.name);
2196                }
2197
2198                mSettings.onVolumeForgotten(fsUuid);
2199                mSettings.writeLPr();
2200            }
2201        }
2202    };
2203
2204    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2205            String[] grantedPermissions) {
2206        for (int userId : userIds) {
2207            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2208        }
2209    }
2210
2211    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2212            String[] grantedPermissions) {
2213        PackageSetting ps = (PackageSetting) pkg.mExtras;
2214        if (ps == null) {
2215            return;
2216        }
2217
2218        PermissionsState permissionsState = ps.getPermissionsState();
2219
2220        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2221                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2222
2223        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2224                >= Build.VERSION_CODES.M;
2225
2226        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2227
2228        for (String permission : pkg.requestedPermissions) {
2229            final BasePermission bp;
2230            synchronized (mPackages) {
2231                bp = mSettings.mPermissions.get(permission);
2232            }
2233            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2234                    && (!instantApp || bp.isInstant())
2235                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2236                    && (grantedPermissions == null
2237                           || ArrayUtils.contains(grantedPermissions, permission))) {
2238                final int flags = permissionsState.getPermissionFlags(permission, userId);
2239                if (supportsRuntimePermissions) {
2240                    // Installer cannot change immutable permissions.
2241                    if ((flags & immutableFlags) == 0) {
2242                        grantRuntimePermission(pkg.packageName, permission, userId);
2243                    }
2244                } else if (mPermissionReviewRequired) {
2245                    // In permission review mode we clear the review flag when we
2246                    // are asked to install the app with all permissions granted.
2247                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2248                        updatePermissionFlags(permission, pkg.packageName,
2249                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2250                    }
2251                }
2252            }
2253        }
2254    }
2255
2256    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2257        Bundle extras = null;
2258        switch (res.returnCode) {
2259            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2260                extras = new Bundle();
2261                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2262                        res.origPermission);
2263                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2264                        res.origPackage);
2265                break;
2266            }
2267            case PackageManager.INSTALL_SUCCEEDED: {
2268                extras = new Bundle();
2269                extras.putBoolean(Intent.EXTRA_REPLACING,
2270                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2271                break;
2272            }
2273        }
2274        return extras;
2275    }
2276
2277    void scheduleWriteSettingsLocked() {
2278        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2279            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2280        }
2281    }
2282
2283    void scheduleWritePackageListLocked(int userId) {
2284        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2285            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2286            msg.arg1 = userId;
2287            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2288        }
2289    }
2290
2291    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2292        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2293        scheduleWritePackageRestrictionsLocked(userId);
2294    }
2295
2296    void scheduleWritePackageRestrictionsLocked(int userId) {
2297        final int[] userIds = (userId == UserHandle.USER_ALL)
2298                ? sUserManager.getUserIds() : new int[]{userId};
2299        for (int nextUserId : userIds) {
2300            if (!sUserManager.exists(nextUserId)) return;
2301            mDirtyUsers.add(nextUserId);
2302            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2303                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2304            }
2305        }
2306    }
2307
2308    public static PackageManagerService main(Context context, Installer installer,
2309            boolean factoryTest, boolean onlyCore) {
2310        // Self-check for initial settings.
2311        PackageManagerServiceCompilerMapping.checkProperties();
2312
2313        PackageManagerService m = new PackageManagerService(context, installer,
2314                factoryTest, onlyCore);
2315        m.enableSystemUserPackages();
2316        ServiceManager.addService("package", m);
2317        final PackageManagerNative pmn = m.new PackageManagerNative();
2318        ServiceManager.addService("package_native", pmn);
2319        return m;
2320    }
2321
2322    private void enableSystemUserPackages() {
2323        if (!UserManager.isSplitSystemUser()) {
2324            return;
2325        }
2326        // For system user, enable apps based on the following conditions:
2327        // - app is whitelisted or belong to one of these groups:
2328        //   -- system app which has no launcher icons
2329        //   -- system app which has INTERACT_ACROSS_USERS permission
2330        //   -- system IME app
2331        // - app is not in the blacklist
2332        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2333        Set<String> enableApps = new ArraySet<>();
2334        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2335                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2336                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2337        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2338        enableApps.addAll(wlApps);
2339        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2340                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2341        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2342        enableApps.removeAll(blApps);
2343        Log.i(TAG, "Applications installed for system user: " + enableApps);
2344        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2345                UserHandle.SYSTEM);
2346        final int allAppsSize = allAps.size();
2347        synchronized (mPackages) {
2348            for (int i = 0; i < allAppsSize; i++) {
2349                String pName = allAps.get(i);
2350                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2351                // Should not happen, but we shouldn't be failing if it does
2352                if (pkgSetting == null) {
2353                    continue;
2354                }
2355                boolean install = enableApps.contains(pName);
2356                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2357                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2358                            + " for system user");
2359                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2360                }
2361            }
2362            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2363        }
2364    }
2365
2366    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2367        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2368                Context.DISPLAY_SERVICE);
2369        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2370    }
2371
2372    /**
2373     * Requests that files preopted on a secondary system partition be copied to the data partition
2374     * if possible.  Note that the actual copying of the files is accomplished by init for security
2375     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2376     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2377     */
2378    private static void requestCopyPreoptedFiles() {
2379        final int WAIT_TIME_MS = 100;
2380        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2381        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2382            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2383            // We will wait for up to 100 seconds.
2384            final long timeStart = SystemClock.uptimeMillis();
2385            final long timeEnd = timeStart + 100 * 1000;
2386            long timeNow = timeStart;
2387            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2388                try {
2389                    Thread.sleep(WAIT_TIME_MS);
2390                } catch (InterruptedException e) {
2391                    // Do nothing
2392                }
2393                timeNow = SystemClock.uptimeMillis();
2394                if (timeNow > timeEnd) {
2395                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2396                    Slog.wtf(TAG, "cppreopt did not finish!");
2397                    break;
2398                }
2399            }
2400
2401            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2402        }
2403    }
2404
2405    public PackageManagerService(Context context, Installer installer,
2406            boolean factoryTest, boolean onlyCore) {
2407        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2408        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2409        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2410                SystemClock.uptimeMillis());
2411
2412        if (mSdkVersion <= 0) {
2413            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2414        }
2415
2416        mContext = context;
2417
2418        mPermissionReviewRequired = context.getResources().getBoolean(
2419                R.bool.config_permissionReviewRequired);
2420
2421        mFactoryTest = factoryTest;
2422        mOnlyCore = onlyCore;
2423        mMetrics = new DisplayMetrics();
2424        mSettings = new Settings(mPackages);
2425        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2426                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2427        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2428                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2429        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2430                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2431        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2432                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2433        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2434                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2435        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2436                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2437
2438        String separateProcesses = SystemProperties.get("debug.separate_processes");
2439        if (separateProcesses != null && separateProcesses.length() > 0) {
2440            if ("*".equals(separateProcesses)) {
2441                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2442                mSeparateProcesses = null;
2443                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2444            } else {
2445                mDefParseFlags = 0;
2446                mSeparateProcesses = separateProcesses.split(",");
2447                Slog.w(TAG, "Running with debug.separate_processes: "
2448                        + separateProcesses);
2449            }
2450        } else {
2451            mDefParseFlags = 0;
2452            mSeparateProcesses = null;
2453        }
2454
2455        mInstaller = installer;
2456        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2457                "*dexopt*");
2458        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2459        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2460
2461        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2462                FgThread.get().getLooper());
2463
2464        getDefaultDisplayMetrics(context, mMetrics);
2465
2466        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2467        SystemConfig systemConfig = SystemConfig.getInstance();
2468        mGlobalGids = systemConfig.getGlobalGids();
2469        mSystemPermissions = systemConfig.getSystemPermissions();
2470        mAvailableFeatures = systemConfig.getAvailableFeatures();
2471        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2472
2473        mProtectedPackages = new ProtectedPackages(mContext);
2474
2475        synchronized (mInstallLock) {
2476        // writer
2477        synchronized (mPackages) {
2478            mHandlerThread = new ServiceThread(TAG,
2479                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2480            mHandlerThread.start();
2481            mHandler = new PackageHandler(mHandlerThread.getLooper());
2482            mProcessLoggingHandler = new ProcessLoggingHandler();
2483            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2484
2485            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2486            mInstantAppRegistry = new InstantAppRegistry(this);
2487
2488            File dataDir = Environment.getDataDirectory();
2489            mAppInstallDir = new File(dataDir, "app");
2490            mAppLib32InstallDir = new File(dataDir, "app-lib");
2491            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2492            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2493            sUserManager = new UserManagerService(context, this,
2494                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2495
2496            // Propagate permission configuration in to package manager.
2497            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2498                    = systemConfig.getPermissions();
2499            for (int i=0; i<permConfig.size(); i++) {
2500                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2501                BasePermission bp = mSettings.mPermissions.get(perm.name);
2502                if (bp == null) {
2503                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2504                    mSettings.mPermissions.put(perm.name, bp);
2505                }
2506                if (perm.gids != null) {
2507                    bp.setGids(perm.gids, perm.perUser);
2508                }
2509            }
2510
2511            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2512            final int builtInLibCount = libConfig.size();
2513            for (int i = 0; i < builtInLibCount; i++) {
2514                String name = libConfig.keyAt(i);
2515                String path = libConfig.valueAt(i);
2516                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2517                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2518            }
2519
2520            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2521
2522            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2523            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2524            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2525
2526            // Clean up orphaned packages for which the code path doesn't exist
2527            // and they are an update to a system app - caused by bug/32321269
2528            final int packageSettingCount = mSettings.mPackages.size();
2529            for (int i = packageSettingCount - 1; i >= 0; i--) {
2530                PackageSetting ps = mSettings.mPackages.valueAt(i);
2531                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2532                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2533                    mSettings.mPackages.removeAt(i);
2534                    mSettings.enableSystemPackageLPw(ps.name);
2535                }
2536            }
2537
2538            if (mFirstBoot) {
2539                requestCopyPreoptedFiles();
2540            }
2541
2542            String customResolverActivity = Resources.getSystem().getString(
2543                    R.string.config_customResolverActivity);
2544            if (TextUtils.isEmpty(customResolverActivity)) {
2545                customResolverActivity = null;
2546            } else {
2547                mCustomResolverComponentName = ComponentName.unflattenFromString(
2548                        customResolverActivity);
2549            }
2550
2551            long startTime = SystemClock.uptimeMillis();
2552
2553            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2554                    startTime);
2555
2556            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2557            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2558
2559            if (bootClassPath == null) {
2560                Slog.w(TAG, "No BOOTCLASSPATH found!");
2561            }
2562
2563            if (systemServerClassPath == null) {
2564                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2565            }
2566
2567            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2568
2569            final VersionInfo ver = mSettings.getInternalVersion();
2570            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2571            if (mIsUpgrade) {
2572                logCriticalInfo(Log.INFO,
2573                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2574            }
2575
2576            // when upgrading from pre-M, promote system app permissions from install to runtime
2577            mPromoteSystemApps =
2578                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2579
2580            // When upgrading from pre-N, we need to handle package extraction like first boot,
2581            // as there is no profiling data available.
2582            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2583
2584            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2585
2586            // save off the names of pre-existing system packages prior to scanning; we don't
2587            // want to automatically grant runtime permissions for new system apps
2588            if (mPromoteSystemApps) {
2589                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2590                while (pkgSettingIter.hasNext()) {
2591                    PackageSetting ps = pkgSettingIter.next();
2592                    if (isSystemApp(ps)) {
2593                        mExistingSystemPackages.add(ps.name);
2594                    }
2595                }
2596            }
2597
2598            mCacheDir = preparePackageParserCache(mIsUpgrade);
2599
2600            // Set flag to monitor and not change apk file paths when
2601            // scanning install directories.
2602            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2603
2604            if (mIsUpgrade || mFirstBoot) {
2605                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2606            }
2607
2608            // Collect vendor overlay packages. (Do this before scanning any apps.)
2609            // For security and version matching reason, only consider
2610            // overlay packages if they reside in the right directory.
2611            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2612                    | PackageParser.PARSE_IS_SYSTEM
2613                    | PackageParser.PARSE_IS_SYSTEM_DIR
2614                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2615
2616            mParallelPackageParserCallback.findStaticOverlayPackages();
2617
2618            // Find base frameworks (resource packages without code).
2619            scanDirTracedLI(frameworkDir, mDefParseFlags
2620                    | PackageParser.PARSE_IS_SYSTEM
2621                    | PackageParser.PARSE_IS_SYSTEM_DIR
2622                    | PackageParser.PARSE_IS_PRIVILEGED,
2623                    scanFlags | SCAN_NO_DEX, 0);
2624
2625            // Collected privileged system packages.
2626            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2627            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2628                    | PackageParser.PARSE_IS_SYSTEM
2629                    | PackageParser.PARSE_IS_SYSTEM_DIR
2630                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2631
2632            // Collect ordinary system packages.
2633            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2634            scanDirTracedLI(systemAppDir, mDefParseFlags
2635                    | PackageParser.PARSE_IS_SYSTEM
2636                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2637
2638            // Collect all vendor packages.
2639            File vendorAppDir = new File("/vendor/app");
2640            try {
2641                vendorAppDir = vendorAppDir.getCanonicalFile();
2642            } catch (IOException e) {
2643                // failed to look up canonical path, continue with original one
2644            }
2645            scanDirTracedLI(vendorAppDir, mDefParseFlags
2646                    | PackageParser.PARSE_IS_SYSTEM
2647                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2648
2649            // Collect all OEM packages.
2650            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2651            scanDirTracedLI(oemAppDir, mDefParseFlags
2652                    | PackageParser.PARSE_IS_SYSTEM
2653                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2654
2655            // Prune any system packages that no longer exist.
2656            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2657            // Stub packages must either be replaced with full versions in the /data
2658            // partition or be disabled.
2659            final List<String> stubSystemApps = new ArrayList<>();
2660            if (!mOnlyCore) {
2661                // do this first before mucking with mPackages for the "expecting better" case
2662                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2663                while (pkgIterator.hasNext()) {
2664                    final PackageParser.Package pkg = pkgIterator.next();
2665                    if (pkg.isStub) {
2666                        stubSystemApps.add(pkg.packageName);
2667                    }
2668                }
2669
2670                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2671                while (psit.hasNext()) {
2672                    PackageSetting ps = psit.next();
2673
2674                    /*
2675                     * If this is not a system app, it can't be a
2676                     * disable system app.
2677                     */
2678                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2679                        continue;
2680                    }
2681
2682                    /*
2683                     * If the package is scanned, it's not erased.
2684                     */
2685                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2686                    if (scannedPkg != null) {
2687                        /*
2688                         * If the system app is both scanned and in the
2689                         * disabled packages list, then it must have been
2690                         * added via OTA. Remove it from the currently
2691                         * scanned package so the previously user-installed
2692                         * application can be scanned.
2693                         */
2694                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2695                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2696                                    + ps.name + "; removing system app.  Last known codePath="
2697                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2698                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2699                                    + scannedPkg.mVersionCode);
2700                            removePackageLI(scannedPkg, true);
2701                            mExpectingBetter.put(ps.name, ps.codePath);
2702                        }
2703
2704                        continue;
2705                    }
2706
2707                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2708                        psit.remove();
2709                        logCriticalInfo(Log.WARN, "System package " + ps.name
2710                                + " no longer exists; it's data will be wiped");
2711                        // Actual deletion of code and data will be handled by later
2712                        // reconciliation step
2713                    } else {
2714                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2715                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2716                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2717                        }
2718                    }
2719                }
2720            }
2721
2722            //look for any incomplete package installations
2723            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2724            for (int i = 0; i < deletePkgsList.size(); i++) {
2725                // Actual deletion of code and data will be handled by later
2726                // reconciliation step
2727                final String packageName = deletePkgsList.get(i).name;
2728                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2729                synchronized (mPackages) {
2730                    mSettings.removePackageLPw(packageName);
2731                }
2732            }
2733
2734            //delete tmp files
2735            deleteTempPackageFiles();
2736
2737            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2738
2739            // Remove any shared userIDs that have no associated packages
2740            mSettings.pruneSharedUsersLPw();
2741            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2742            final int systemPackagesCount = mPackages.size();
2743            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2744                    + " ms, packageCount: " + systemPackagesCount
2745                    + " , timePerPackage: "
2746                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2747                    + " , cached: " + cachedSystemApps);
2748            if (mIsUpgrade && systemPackagesCount > 0) {
2749                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2750                        ((int) systemScanTime) / systemPackagesCount);
2751            }
2752            if (!mOnlyCore) {
2753                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2754                        SystemClock.uptimeMillis());
2755                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2756
2757                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2758                        | PackageParser.PARSE_FORWARD_LOCK,
2759                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2760
2761                // Remove disable package settings for updated system apps that were
2762                // removed via an OTA. If the update is no longer present, remove the
2763                // app completely. Otherwise, revoke their system privileges.
2764                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2765                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2766                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2767
2768                    final String msg;
2769                    if (deletedPkg == null) {
2770                        // should have found an update, but, we didn't; remove everything
2771                        msg = "Updated system package " + deletedAppName
2772                                + " no longer exists; removing its data";
2773                        // Actual deletion of code and data will be handled by later
2774                        // reconciliation step
2775                    } else {
2776                        // found an update; revoke system privileges
2777                        msg = "Updated system package + " + deletedAppName
2778                                + " no longer exists; revoking system privileges";
2779
2780                        // Don't do anything if a stub is removed from the system image. If
2781                        // we were to remove the uncompressed version from the /data partition,
2782                        // this is where it'd be done.
2783
2784                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2785                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2786                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2787                    }
2788                    logCriticalInfo(Log.WARN, msg);
2789                }
2790
2791                /*
2792                 * Make sure all system apps that we expected to appear on
2793                 * the userdata partition actually showed up. If they never
2794                 * appeared, crawl back and revive the system version.
2795                 */
2796                for (int i = 0; i < mExpectingBetter.size(); i++) {
2797                    final String packageName = mExpectingBetter.keyAt(i);
2798                    if (!mPackages.containsKey(packageName)) {
2799                        final File scanFile = mExpectingBetter.valueAt(i);
2800
2801                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2802                                + " but never showed up; reverting to system");
2803
2804                        int reparseFlags = mDefParseFlags;
2805                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2806                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2807                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2808                                    | PackageParser.PARSE_IS_PRIVILEGED;
2809                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2810                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2811                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2812                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2813                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2814                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2815                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2816                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2817                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2818                        } else {
2819                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2820                            continue;
2821                        }
2822
2823                        mSettings.enableSystemPackageLPw(packageName);
2824
2825                        try {
2826                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2827                        } catch (PackageManagerException e) {
2828                            Slog.e(TAG, "Failed to parse original system package: "
2829                                    + e.getMessage());
2830                        }
2831                    }
2832                }
2833
2834                // Uncompress and install any stubbed system applications.
2835                // This must be done last to ensure all stubs are replaced or disabled.
2836                decompressSystemApplications(stubSystemApps, scanFlags);
2837
2838                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2839                                - cachedSystemApps;
2840
2841                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2842                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2843                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2844                        + " ms, packageCount: " + dataPackagesCount
2845                        + " , timePerPackage: "
2846                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2847                        + " , cached: " + cachedNonSystemApps);
2848                if (mIsUpgrade && dataPackagesCount > 0) {
2849                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2850                            ((int) dataScanTime) / dataPackagesCount);
2851                }
2852            }
2853            mExpectingBetter.clear();
2854
2855            // Resolve the storage manager.
2856            mStorageManagerPackage = getStorageManagerPackageName();
2857
2858            // Resolve protected action filters. Only the setup wizard is allowed to
2859            // have a high priority filter for these actions.
2860            mSetupWizardPackage = getSetupWizardPackageName();
2861            if (mProtectedFilters.size() > 0) {
2862                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2863                    Slog.i(TAG, "No setup wizard;"
2864                        + " All protected intents capped to priority 0");
2865                }
2866                for (ActivityIntentInfo filter : mProtectedFilters) {
2867                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2868                        if (DEBUG_FILTERS) {
2869                            Slog.i(TAG, "Found setup wizard;"
2870                                + " allow priority " + filter.getPriority() + ";"
2871                                + " package: " + filter.activity.info.packageName
2872                                + " activity: " + filter.activity.className
2873                                + " priority: " + filter.getPriority());
2874                        }
2875                        // skip setup wizard; allow it to keep the high priority filter
2876                        continue;
2877                    }
2878                    if (DEBUG_FILTERS) {
2879                        Slog.i(TAG, "Protected action; cap priority to 0;"
2880                                + " package: " + filter.activity.info.packageName
2881                                + " activity: " + filter.activity.className
2882                                + " origPrio: " + filter.getPriority());
2883                    }
2884                    filter.setPriority(0);
2885                }
2886            }
2887            mDeferProtectedFilters = false;
2888            mProtectedFilters.clear();
2889
2890            // Now that we know all of the shared libraries, update all clients to have
2891            // the correct library paths.
2892            updateAllSharedLibrariesLPw(null);
2893
2894            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2895                // NOTE: We ignore potential failures here during a system scan (like
2896                // the rest of the commands above) because there's precious little we
2897                // can do about it. A settings error is reported, though.
2898                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2899            }
2900
2901            // Now that we know all the packages we are keeping,
2902            // read and update their last usage times.
2903            mPackageUsage.read(mPackages);
2904            mCompilerStats.read();
2905
2906            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2907                    SystemClock.uptimeMillis());
2908            Slog.i(TAG, "Time to scan packages: "
2909                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2910                    + " seconds");
2911
2912            // If the platform SDK has changed since the last time we booted,
2913            // we need to re-grant app permission to catch any new ones that
2914            // appear.  This is really a hack, and means that apps can in some
2915            // cases get permissions that the user didn't initially explicitly
2916            // allow...  it would be nice to have some better way to handle
2917            // this situation.
2918            int updateFlags = UPDATE_PERMISSIONS_ALL;
2919            if (ver.sdkVersion != mSdkVersion) {
2920                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2921                        + mSdkVersion + "; regranting permissions for internal storage");
2922                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2923            }
2924            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2925            ver.sdkVersion = mSdkVersion;
2926
2927            // If this is the first boot or an update from pre-M, and it is a normal
2928            // boot, then we need to initialize the default preferred apps across
2929            // all defined users.
2930            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2931                for (UserInfo user : sUserManager.getUsers(true)) {
2932                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2933                    applyFactoryDefaultBrowserLPw(user.id);
2934                    primeDomainVerificationsLPw(user.id);
2935                }
2936            }
2937
2938            // Prepare storage for system user really early during boot,
2939            // since core system apps like SettingsProvider and SystemUI
2940            // can't wait for user to start
2941            final int storageFlags;
2942            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2943                storageFlags = StorageManager.FLAG_STORAGE_DE;
2944            } else {
2945                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2946            }
2947            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2948                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2949                    true /* onlyCoreApps */);
2950            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2951                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
2952                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2953                traceLog.traceBegin("AppDataFixup");
2954                try {
2955                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2956                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2957                } catch (InstallerException e) {
2958                    Slog.w(TAG, "Trouble fixing GIDs", e);
2959                }
2960                traceLog.traceEnd();
2961
2962                traceLog.traceBegin("AppDataPrepare");
2963                if (deferPackages == null || deferPackages.isEmpty()) {
2964                    return;
2965                }
2966                int count = 0;
2967                for (String pkgName : deferPackages) {
2968                    PackageParser.Package pkg = null;
2969                    synchronized (mPackages) {
2970                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2971                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2972                            pkg = ps.pkg;
2973                        }
2974                    }
2975                    if (pkg != null) {
2976                        synchronized (mInstallLock) {
2977                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2978                                    true /* maybeMigrateAppData */);
2979                        }
2980                        count++;
2981                    }
2982                }
2983                traceLog.traceEnd();
2984                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2985            }, "prepareAppData");
2986
2987            // If this is first boot after an OTA, and a normal boot, then
2988            // we need to clear code cache directories.
2989            // Note that we do *not* clear the application profiles. These remain valid
2990            // across OTAs and are used to drive profile verification (post OTA) and
2991            // profile compilation (without waiting to collect a fresh set of profiles).
2992            if (mIsUpgrade && !onlyCore) {
2993                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2994                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2995                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2996                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2997                        // No apps are running this early, so no need to freeze
2998                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2999                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
3000                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
3001                    }
3002                }
3003                ver.fingerprint = Build.FINGERPRINT;
3004            }
3005
3006            checkDefaultBrowser();
3007
3008            // clear only after permissions and other defaults have been updated
3009            mExistingSystemPackages.clear();
3010            mPromoteSystemApps = false;
3011
3012            // All the changes are done during package scanning.
3013            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3014
3015            // can downgrade to reader
3016            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3017            mSettings.writeLPr();
3018            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3019            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3020                    SystemClock.uptimeMillis());
3021
3022            if (!mOnlyCore) {
3023                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3024                mRequiredInstallerPackage = getRequiredInstallerLPr();
3025                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3026                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3027                if (mIntentFilterVerifierComponent != null) {
3028                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3029                            mIntentFilterVerifierComponent);
3030                } else {
3031                    mIntentFilterVerifier = null;
3032                }
3033                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3034                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3035                        SharedLibraryInfo.VERSION_UNDEFINED);
3036                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3037                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3038                        SharedLibraryInfo.VERSION_UNDEFINED);
3039            } else {
3040                mRequiredVerifierPackage = null;
3041                mRequiredInstallerPackage = null;
3042                mRequiredUninstallerPackage = null;
3043                mIntentFilterVerifierComponent = null;
3044                mIntentFilterVerifier = null;
3045                mServicesSystemSharedLibraryPackageName = null;
3046                mSharedSystemSharedLibraryPackageName = null;
3047            }
3048
3049            mInstallerService = new PackageInstallerService(context, this);
3050            final Pair<ComponentName, String> instantAppResolverComponent =
3051                    getInstantAppResolverLPr();
3052            if (instantAppResolverComponent != null) {
3053                if (DEBUG_EPHEMERAL) {
3054                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3055                }
3056                mInstantAppResolverConnection = new EphemeralResolverConnection(
3057                        mContext, instantAppResolverComponent.first,
3058                        instantAppResolverComponent.second);
3059                mInstantAppResolverSettingsComponent =
3060                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3061            } else {
3062                mInstantAppResolverConnection = null;
3063                mInstantAppResolverSettingsComponent = null;
3064            }
3065            updateInstantAppInstallerLocked(null);
3066
3067            // Read and update the usage of dex files.
3068            // Do this at the end of PM init so that all the packages have their
3069            // data directory reconciled.
3070            // At this point we know the code paths of the packages, so we can validate
3071            // the disk file and build the internal cache.
3072            // The usage file is expected to be small so loading and verifying it
3073            // should take a fairly small time compare to the other activities (e.g. package
3074            // scanning).
3075            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3076            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3077            for (int userId : currentUserIds) {
3078                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3079            }
3080            mDexManager.load(userPackages);
3081            if (mIsUpgrade) {
3082                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3083                        (int) (SystemClock.uptimeMillis() - startTime));
3084            }
3085        } // synchronized (mPackages)
3086        } // synchronized (mInstallLock)
3087
3088        // Now after opening every single application zip, make sure they
3089        // are all flushed.  Not really needed, but keeps things nice and
3090        // tidy.
3091        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3092        Runtime.getRuntime().gc();
3093        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3094
3095        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3096        FallbackCategoryProvider.loadFallbacks();
3097        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3098
3099        // The initial scanning above does many calls into installd while
3100        // holding the mPackages lock, but we're mostly interested in yelling
3101        // once we have a booted system.
3102        mInstaller.setWarnIfHeld(mPackages);
3103
3104        // Expose private service for system components to use.
3105        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3106        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3107    }
3108
3109    /**
3110     * Uncompress and install stub applications.
3111     * <p>In order to save space on the system partition, some applications are shipped in a
3112     * compressed form. In addition the compressed bits for the full application, the
3113     * system image contains a tiny stub comprised of only the Android manifest.
3114     * <p>During the first boot, attempt to uncompress and install the full application. If
3115     * the application can't be installed for any reason, disable the stub and prevent
3116     * uncompressing the full application during future boots.
3117     * <p>In order to forcefully attempt an installation of a full application, go to app
3118     * settings and enable the application.
3119     */
3120    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3121        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3122            final String pkgName = stubSystemApps.get(i);
3123            // skip if the system package is already disabled
3124            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3125                stubSystemApps.remove(i);
3126                continue;
3127            }
3128            // skip if the package isn't installed (?!); this should never happen
3129            final PackageParser.Package pkg = mPackages.get(pkgName);
3130            if (pkg == null) {
3131                stubSystemApps.remove(i);
3132                continue;
3133            }
3134            // skip if the package has been disabled by the user
3135            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3136            if (ps != null) {
3137                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3138                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3139                    stubSystemApps.remove(i);
3140                    continue;
3141                }
3142            }
3143
3144            if (DEBUG_COMPRESSION) {
3145                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3146            }
3147
3148            // uncompress the binary to its eventual destination on /data
3149            final File scanFile = decompressPackage(pkg);
3150            if (scanFile == null) {
3151                continue;
3152            }
3153
3154            // install the package to replace the stub on /system
3155            try {
3156                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3157                removePackageLI(pkg, true /*chatty*/);
3158                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3159                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3160                        UserHandle.USER_SYSTEM, "android");
3161                stubSystemApps.remove(i);
3162                continue;
3163            } catch (PackageManagerException e) {
3164                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3165            }
3166
3167            // any failed attempt to install the package will be cleaned up later
3168        }
3169
3170        // disable any stub still left; these failed to install the full application
3171        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3172            final String pkgName = stubSystemApps.get(i);
3173            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3174            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3175                    UserHandle.USER_SYSTEM, "android");
3176            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3177        }
3178    }
3179
3180    private int decompressFile(File srcFile, File dstFile) throws ErrnoException {
3181        if (DEBUG_COMPRESSION) {
3182            Slog.i(TAG, "Decompress file"
3183                    + "; src: " + srcFile.getAbsolutePath()
3184                    + ", dst: " + dstFile.getAbsolutePath());
3185        }
3186        try (
3187                InputStream fileIn = new GZIPInputStream(new FileInputStream(srcFile));
3188                OutputStream fileOut = new FileOutputStream(dstFile, false /*append*/);
3189        ) {
3190            Streams.copy(fileIn, fileOut);
3191            Os.chmod(dstFile.getAbsolutePath(), 0644);
3192            return PackageManager.INSTALL_SUCCEEDED;
3193        } catch (IOException e) {
3194            logCriticalInfo(Log.ERROR, "Failed to decompress file"
3195                    + "; src: " + srcFile.getAbsolutePath()
3196                    + ", dst: " + dstFile.getAbsolutePath());
3197        }
3198        return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3199    }
3200
3201    private File[] getCompressedFiles(String codePath) {
3202        final File stubCodePath = new File(codePath);
3203        final String stubName = stubCodePath.getName();
3204
3205        // The layout of a compressed package on a given partition is as follows :
3206        //
3207        // Compressed artifacts:
3208        //
3209        // /partition/ModuleName/foo.gz
3210        // /partation/ModuleName/bar.gz
3211        //
3212        // Stub artifact:
3213        //
3214        // /partition/ModuleName-Stub/ModuleName-Stub.apk
3215        //
3216        // In other words, stub is on the same partition as the compressed artifacts
3217        // and in a directory that's suffixed with "-Stub".
3218        int idx = stubName.lastIndexOf(STUB_SUFFIX);
3219        if (idx < 0 || (stubName.length() != (idx + STUB_SUFFIX.length()))) {
3220            return null;
3221        }
3222
3223        final File stubParentDir = stubCodePath.getParentFile();
3224        if (stubParentDir == null) {
3225            Slog.e(TAG, "Unable to determine stub parent dir for codePath: " + codePath);
3226            return null;
3227        }
3228
3229        final File compressedPath = new File(stubParentDir, stubName.substring(0, idx));
3230        final File[] files = compressedPath.listFiles(new FilenameFilter() {
3231            @Override
3232            public boolean accept(File dir, String name) {
3233                return name.toLowerCase().endsWith(COMPRESSED_EXTENSION);
3234            }
3235        });
3236
3237        if (DEBUG_COMPRESSION && files != null && files.length > 0) {
3238            Slog.i(TAG, "getCompressedFiles[" + codePath + "]: " + Arrays.toString(files));
3239        }
3240
3241        return files;
3242    }
3243
3244    private boolean compressedFileExists(String codePath) {
3245        final File[] compressedFiles = getCompressedFiles(codePath);
3246        return compressedFiles != null && compressedFiles.length > 0;
3247    }
3248
3249    /**
3250     * Decompresses the given package on the system image onto
3251     * the /data partition.
3252     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3253     */
3254    private File decompressPackage(PackageParser.Package pkg) {
3255        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3256        if (compressedFiles == null || compressedFiles.length == 0) {
3257            if (DEBUG_COMPRESSION) {
3258                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3259            }
3260            return null;
3261        }
3262        final File dstCodePath =
3263                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3264        int ret = PackageManager.INSTALL_SUCCEEDED;
3265        try {
3266            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3267            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3268            for (File srcFile : compressedFiles) {
3269                final String srcFileName = srcFile.getName();
3270                final String dstFileName = srcFileName.substring(
3271                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3272                final File dstFile = new File(dstCodePath, dstFileName);
3273                ret = decompressFile(srcFile, dstFile);
3274                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3275                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3276                            + "; pkg: " + pkg.packageName
3277                            + ", file: " + dstFileName);
3278                    break;
3279                }
3280            }
3281        } catch (ErrnoException e) {
3282            logCriticalInfo(Log.ERROR, "Failed to decompress"
3283                    + "; pkg: " + pkg.packageName
3284                    + ", err: " + e.errno);
3285        }
3286        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3287            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3288            NativeLibraryHelper.Handle handle = null;
3289            try {
3290                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3291                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3292                        null /*abiOverride*/);
3293            } catch (IOException e) {
3294                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3295                        + "; pkg: " + pkg.packageName);
3296                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3297            } finally {
3298                IoUtils.closeQuietly(handle);
3299            }
3300        }
3301        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3302            if (dstCodePath == null || !dstCodePath.exists()) {
3303                return null;
3304            }
3305            removeCodePathLI(dstCodePath);
3306            return null;
3307        }
3308        return dstCodePath;
3309    }
3310
3311    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3312        // we're only interested in updating the installer appliction when 1) it's not
3313        // already set or 2) the modified package is the installer
3314        if (mInstantAppInstallerActivity != null
3315                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3316                        .equals(modifiedPackage)) {
3317            return;
3318        }
3319        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3320    }
3321
3322    private static File preparePackageParserCache(boolean isUpgrade) {
3323        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3324            return null;
3325        }
3326
3327        // Disable package parsing on eng builds to allow for faster incremental development.
3328        if (Build.IS_ENG) {
3329            return null;
3330        }
3331
3332        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3333            Slog.i(TAG, "Disabling package parser cache due to system property.");
3334            return null;
3335        }
3336
3337        // The base directory for the package parser cache lives under /data/system/.
3338        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3339                "package_cache");
3340        if (cacheBaseDir == null) {
3341            return null;
3342        }
3343
3344        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3345        // This also serves to "GC" unused entries when the package cache version changes (which
3346        // can only happen during upgrades).
3347        if (isUpgrade) {
3348            FileUtils.deleteContents(cacheBaseDir);
3349        }
3350
3351
3352        // Return the versioned package cache directory. This is something like
3353        // "/data/system/package_cache/1"
3354        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3355
3356        // The following is a workaround to aid development on non-numbered userdebug
3357        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3358        // the system partition is newer.
3359        //
3360        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3361        // that starts with "eng." to signify that this is an engineering build and not
3362        // destined for release.
3363        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3364            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3365
3366            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3367            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3368            // in general and should not be used for production changes. In this specific case,
3369            // we know that they will work.
3370            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3371            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3372                FileUtils.deleteContents(cacheBaseDir);
3373                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3374            }
3375        }
3376
3377        return cacheDir;
3378    }
3379
3380    @Override
3381    public boolean isFirstBoot() {
3382        // allow instant applications
3383        return mFirstBoot;
3384    }
3385
3386    @Override
3387    public boolean isOnlyCoreApps() {
3388        // allow instant applications
3389        return mOnlyCore;
3390    }
3391
3392    @Override
3393    public boolean isUpgrade() {
3394        // allow instant applications
3395        return mIsUpgrade;
3396    }
3397
3398    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3399        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3400
3401        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3402                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3403                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3404        if (matches.size() == 1) {
3405            return matches.get(0).getComponentInfo().packageName;
3406        } else if (matches.size() == 0) {
3407            Log.e(TAG, "There should probably be a verifier, but, none were found");
3408            return null;
3409        }
3410        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3411    }
3412
3413    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3414        synchronized (mPackages) {
3415            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3416            if (libraryEntry == null) {
3417                throw new IllegalStateException("Missing required shared library:" + name);
3418            }
3419            return libraryEntry.apk;
3420        }
3421    }
3422
3423    private @NonNull String getRequiredInstallerLPr() {
3424        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3425        intent.addCategory(Intent.CATEGORY_DEFAULT);
3426        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3427
3428        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3429                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3430                UserHandle.USER_SYSTEM);
3431        if (matches.size() == 1) {
3432            ResolveInfo resolveInfo = matches.get(0);
3433            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3434                throw new RuntimeException("The installer must be a privileged app");
3435            }
3436            return matches.get(0).getComponentInfo().packageName;
3437        } else {
3438            throw new RuntimeException("There must be exactly one installer; found " + matches);
3439        }
3440    }
3441
3442    private @NonNull String getRequiredUninstallerLPr() {
3443        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3444        intent.addCategory(Intent.CATEGORY_DEFAULT);
3445        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3446
3447        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3448                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3449                UserHandle.USER_SYSTEM);
3450        if (resolveInfo == null ||
3451                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3452            throw new RuntimeException("There must be exactly one uninstaller; found "
3453                    + resolveInfo);
3454        }
3455        return resolveInfo.getComponentInfo().packageName;
3456    }
3457
3458    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3459        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3460
3461        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3462                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3463                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3464        ResolveInfo best = null;
3465        final int N = matches.size();
3466        for (int i = 0; i < N; i++) {
3467            final ResolveInfo cur = matches.get(i);
3468            final String packageName = cur.getComponentInfo().packageName;
3469            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3470                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3471                continue;
3472            }
3473
3474            if (best == null || cur.priority > best.priority) {
3475                best = cur;
3476            }
3477        }
3478
3479        if (best != null) {
3480            return best.getComponentInfo().getComponentName();
3481        }
3482        Slog.w(TAG, "Intent filter verifier not found");
3483        return null;
3484    }
3485
3486    @Override
3487    public @Nullable ComponentName getInstantAppResolverComponent() {
3488        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3489            return null;
3490        }
3491        synchronized (mPackages) {
3492            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3493            if (instantAppResolver == null) {
3494                return null;
3495            }
3496            return instantAppResolver.first;
3497        }
3498    }
3499
3500    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3501        final String[] packageArray =
3502                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3503        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3504            if (DEBUG_EPHEMERAL) {
3505                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3506            }
3507            return null;
3508        }
3509
3510        final int callingUid = Binder.getCallingUid();
3511        final int resolveFlags =
3512                MATCH_DIRECT_BOOT_AWARE
3513                | MATCH_DIRECT_BOOT_UNAWARE
3514                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3515        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3516        final Intent resolverIntent = new Intent(actionName);
3517        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3518                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3519        // temporarily look for the old action
3520        if (resolvers.size() == 0) {
3521            if (DEBUG_EPHEMERAL) {
3522                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3523            }
3524            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3525            resolverIntent.setAction(actionName);
3526            resolvers = queryIntentServicesInternal(resolverIntent, null,
3527                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3528        }
3529        final int N = resolvers.size();
3530        if (N == 0) {
3531            if (DEBUG_EPHEMERAL) {
3532                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3533            }
3534            return null;
3535        }
3536
3537        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3538        for (int i = 0; i < N; i++) {
3539            final ResolveInfo info = resolvers.get(i);
3540
3541            if (info.serviceInfo == null) {
3542                continue;
3543            }
3544
3545            final String packageName = info.serviceInfo.packageName;
3546            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3547                if (DEBUG_EPHEMERAL) {
3548                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3549                            + " pkg: " + packageName + ", info:" + info);
3550                }
3551                continue;
3552            }
3553
3554            if (DEBUG_EPHEMERAL) {
3555                Slog.v(TAG, "Ephemeral resolver found;"
3556                        + " pkg: " + packageName + ", info:" + info);
3557            }
3558            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3559        }
3560        if (DEBUG_EPHEMERAL) {
3561            Slog.v(TAG, "Ephemeral resolver NOT found");
3562        }
3563        return null;
3564    }
3565
3566    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3567        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3568        intent.addCategory(Intent.CATEGORY_DEFAULT);
3569        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3570
3571        final int resolveFlags =
3572                MATCH_DIRECT_BOOT_AWARE
3573                | MATCH_DIRECT_BOOT_UNAWARE
3574                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3575        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3576                resolveFlags, UserHandle.USER_SYSTEM);
3577        // temporarily look for the old action
3578        if (matches.isEmpty()) {
3579            if (DEBUG_EPHEMERAL) {
3580                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3581            }
3582            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3583            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3584                    resolveFlags, UserHandle.USER_SYSTEM);
3585        }
3586        Iterator<ResolveInfo> iter = matches.iterator();
3587        while (iter.hasNext()) {
3588            final ResolveInfo rInfo = iter.next();
3589            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3590            if (ps != null) {
3591                final PermissionsState permissionsState = ps.getPermissionsState();
3592                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3593                    continue;
3594                }
3595            }
3596            iter.remove();
3597        }
3598        if (matches.size() == 0) {
3599            return null;
3600        } else if (matches.size() == 1) {
3601            return (ActivityInfo) matches.get(0).getComponentInfo();
3602        } else {
3603            throw new RuntimeException(
3604                    "There must be at most one ephemeral installer; found " + matches);
3605        }
3606    }
3607
3608    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3609            @NonNull ComponentName resolver) {
3610        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3611                .addCategory(Intent.CATEGORY_DEFAULT)
3612                .setPackage(resolver.getPackageName());
3613        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3614        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3615                UserHandle.USER_SYSTEM);
3616        // temporarily look for the old action
3617        if (matches.isEmpty()) {
3618            if (DEBUG_EPHEMERAL) {
3619                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3620            }
3621            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3622            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3623                    UserHandle.USER_SYSTEM);
3624        }
3625        if (matches.isEmpty()) {
3626            return null;
3627        }
3628        return matches.get(0).getComponentInfo().getComponentName();
3629    }
3630
3631    private void primeDomainVerificationsLPw(int userId) {
3632        if (DEBUG_DOMAIN_VERIFICATION) {
3633            Slog.d(TAG, "Priming domain verifications in user " + userId);
3634        }
3635
3636        SystemConfig systemConfig = SystemConfig.getInstance();
3637        ArraySet<String> packages = systemConfig.getLinkedApps();
3638
3639        for (String packageName : packages) {
3640            PackageParser.Package pkg = mPackages.get(packageName);
3641            if (pkg != null) {
3642                if (!pkg.isSystemApp()) {
3643                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3644                    continue;
3645                }
3646
3647                ArraySet<String> domains = null;
3648                for (PackageParser.Activity a : pkg.activities) {
3649                    for (ActivityIntentInfo filter : a.intents) {
3650                        if (hasValidDomains(filter)) {
3651                            if (domains == null) {
3652                                domains = new ArraySet<String>();
3653                            }
3654                            domains.addAll(filter.getHostsList());
3655                        }
3656                    }
3657                }
3658
3659                if (domains != null && domains.size() > 0) {
3660                    if (DEBUG_DOMAIN_VERIFICATION) {
3661                        Slog.v(TAG, "      + " + packageName);
3662                    }
3663                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3664                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3665                    // and then 'always' in the per-user state actually used for intent resolution.
3666                    final IntentFilterVerificationInfo ivi;
3667                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3668                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3669                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3670                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3671                } else {
3672                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3673                            + "' does not handle web links");
3674                }
3675            } else {
3676                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3677            }
3678        }
3679
3680        scheduleWritePackageRestrictionsLocked(userId);
3681        scheduleWriteSettingsLocked();
3682    }
3683
3684    private void applyFactoryDefaultBrowserLPw(int userId) {
3685        // The default browser app's package name is stored in a string resource,
3686        // with a product-specific overlay used for vendor customization.
3687        String browserPkg = mContext.getResources().getString(
3688                com.android.internal.R.string.default_browser);
3689        if (!TextUtils.isEmpty(browserPkg)) {
3690            // non-empty string => required to be a known package
3691            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3692            if (ps == null) {
3693                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3694                browserPkg = null;
3695            } else {
3696                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3697            }
3698        }
3699
3700        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3701        // default.  If there's more than one, just leave everything alone.
3702        if (browserPkg == null) {
3703            calculateDefaultBrowserLPw(userId);
3704        }
3705    }
3706
3707    private void calculateDefaultBrowserLPw(int userId) {
3708        List<String> allBrowsers = resolveAllBrowserApps(userId);
3709        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3710        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3711    }
3712
3713    private List<String> resolveAllBrowserApps(int userId) {
3714        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3715        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3716                PackageManager.MATCH_ALL, userId);
3717
3718        final int count = list.size();
3719        List<String> result = new ArrayList<String>(count);
3720        for (int i=0; i<count; i++) {
3721            ResolveInfo info = list.get(i);
3722            if (info.activityInfo == null
3723                    || !info.handleAllWebDataURI
3724                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3725                    || result.contains(info.activityInfo.packageName)) {
3726                continue;
3727            }
3728            result.add(info.activityInfo.packageName);
3729        }
3730
3731        return result;
3732    }
3733
3734    private boolean packageIsBrowser(String packageName, int userId) {
3735        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3736                PackageManager.MATCH_ALL, userId);
3737        final int N = list.size();
3738        for (int i = 0; i < N; i++) {
3739            ResolveInfo info = list.get(i);
3740            if (packageName.equals(info.activityInfo.packageName)) {
3741                return true;
3742            }
3743        }
3744        return false;
3745    }
3746
3747    private void checkDefaultBrowser() {
3748        final int myUserId = UserHandle.myUserId();
3749        final String packageName = getDefaultBrowserPackageName(myUserId);
3750        if (packageName != null) {
3751            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3752            if (info == null) {
3753                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3754                synchronized (mPackages) {
3755                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3756                }
3757            }
3758        }
3759    }
3760
3761    @Override
3762    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3763            throws RemoteException {
3764        try {
3765            return super.onTransact(code, data, reply, flags);
3766        } catch (RuntimeException e) {
3767            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3768                Slog.wtf(TAG, "Package Manager Crash", e);
3769            }
3770            throw e;
3771        }
3772    }
3773
3774    static int[] appendInts(int[] cur, int[] add) {
3775        if (add == null) return cur;
3776        if (cur == null) return add;
3777        final int N = add.length;
3778        for (int i=0; i<N; i++) {
3779            cur = appendInt(cur, add[i]);
3780        }
3781        return cur;
3782    }
3783
3784    /**
3785     * Returns whether or not a full application can see an instant application.
3786     * <p>
3787     * Currently, there are three cases in which this can occur:
3788     * <ol>
3789     * <li>The calling application is a "special" process. The special
3790     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3791     *     and {@code 0}</li>
3792     * <li>The calling application has the permission
3793     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3794     * <li>The calling application is the default launcher on the
3795     *     system partition.</li>
3796     * </ol>
3797     */
3798    private boolean canViewInstantApps(int callingUid, int userId) {
3799        if (callingUid == Process.SYSTEM_UID
3800                || callingUid == Process.SHELL_UID
3801                || callingUid == Process.ROOT_UID) {
3802            return true;
3803        }
3804        if (mContext.checkCallingOrSelfPermission(
3805                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3806            return true;
3807        }
3808        if (mContext.checkCallingOrSelfPermission(
3809                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3810            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3811            if (homeComponent != null
3812                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3813                return true;
3814            }
3815        }
3816        return false;
3817    }
3818
3819    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3820        if (!sUserManager.exists(userId)) return null;
3821        if (ps == null) {
3822            return null;
3823        }
3824        PackageParser.Package p = ps.pkg;
3825        if (p == null) {
3826            return null;
3827        }
3828        final int callingUid = Binder.getCallingUid();
3829        // Filter out ephemeral app metadata:
3830        //   * The system/shell/root can see metadata for any app
3831        //   * An installed app can see metadata for 1) other installed apps
3832        //     and 2) ephemeral apps that have explicitly interacted with it
3833        //   * Ephemeral apps can only see their own data and exposed installed apps
3834        //   * Holding a signature permission allows seeing instant apps
3835        if (filterAppAccessLPr(ps, callingUid, userId)) {
3836            return null;
3837        }
3838
3839        final PermissionsState permissionsState = ps.getPermissionsState();
3840
3841        // Compute GIDs only if requested
3842        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3843                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3844        // Compute granted permissions only if package has requested permissions
3845        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3846                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3847        final PackageUserState state = ps.readUserState(userId);
3848
3849        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3850                && ps.isSystem()) {
3851            flags |= MATCH_ANY_USER;
3852        }
3853
3854        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3855                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3856
3857        if (packageInfo == null) {
3858            return null;
3859        }
3860
3861        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3862                resolveExternalPackageNameLPr(p);
3863
3864        return packageInfo;
3865    }
3866
3867    @Override
3868    public void checkPackageStartable(String packageName, int userId) {
3869        final int callingUid = Binder.getCallingUid();
3870        if (getInstantAppPackageName(callingUid) != null) {
3871            throw new SecurityException("Instant applications don't have access to this method");
3872        }
3873        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3874        synchronized (mPackages) {
3875            final PackageSetting ps = mSettings.mPackages.get(packageName);
3876            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3877                throw new SecurityException("Package " + packageName + " was not found!");
3878            }
3879
3880            if (!ps.getInstalled(userId)) {
3881                throw new SecurityException(
3882                        "Package " + packageName + " was not installed for user " + userId + "!");
3883            }
3884
3885            if (mSafeMode && !ps.isSystem()) {
3886                throw new SecurityException("Package " + packageName + " not a system app!");
3887            }
3888
3889            if (mFrozenPackages.contains(packageName)) {
3890                throw new SecurityException("Package " + packageName + " is currently frozen!");
3891            }
3892
3893            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3894                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3895            }
3896        }
3897    }
3898
3899    @Override
3900    public boolean isPackageAvailable(String packageName, int userId) {
3901        if (!sUserManager.exists(userId)) return false;
3902        final int callingUid = Binder.getCallingUid();
3903        enforceCrossUserPermission(callingUid, userId,
3904                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3905        synchronized (mPackages) {
3906            PackageParser.Package p = mPackages.get(packageName);
3907            if (p != null) {
3908                final PackageSetting ps = (PackageSetting) p.mExtras;
3909                if (filterAppAccessLPr(ps, callingUid, userId)) {
3910                    return false;
3911                }
3912                if (ps != null) {
3913                    final PackageUserState state = ps.readUserState(userId);
3914                    if (state != null) {
3915                        return PackageParser.isAvailable(state);
3916                    }
3917                }
3918            }
3919        }
3920        return false;
3921    }
3922
3923    @Override
3924    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3925        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3926                flags, Binder.getCallingUid(), userId);
3927    }
3928
3929    @Override
3930    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3931            int flags, int userId) {
3932        return getPackageInfoInternal(versionedPackage.getPackageName(),
3933                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3934    }
3935
3936    /**
3937     * Important: The provided filterCallingUid is used exclusively to filter out packages
3938     * that can be seen based on user state. It's typically the original caller uid prior
3939     * to clearing. Because it can only be provided by trusted code, it's value can be
3940     * trusted and will be used as-is; unlike userId which will be validated by this method.
3941     */
3942    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3943            int flags, int filterCallingUid, int userId) {
3944        if (!sUserManager.exists(userId)) return null;
3945        flags = updateFlagsForPackage(flags, userId, packageName);
3946        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3947                false /* requireFullPermission */, false /* checkShell */, "get package info");
3948
3949        // reader
3950        synchronized (mPackages) {
3951            // Normalize package name to handle renamed packages and static libs
3952            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3953
3954            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3955            if (matchFactoryOnly) {
3956                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3957                if (ps != null) {
3958                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3959                        return null;
3960                    }
3961                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3962                        return null;
3963                    }
3964                    return generatePackageInfo(ps, flags, userId);
3965                }
3966            }
3967
3968            PackageParser.Package p = mPackages.get(packageName);
3969            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3970                return null;
3971            }
3972            if (DEBUG_PACKAGE_INFO)
3973                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3974            if (p != null) {
3975                final PackageSetting ps = (PackageSetting) p.mExtras;
3976                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3977                    return null;
3978                }
3979                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3980                    return null;
3981                }
3982                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3983            }
3984            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3985                final PackageSetting ps = mSettings.mPackages.get(packageName);
3986                if (ps == null) return null;
3987                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3988                    return null;
3989                }
3990                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3991                    return null;
3992                }
3993                return generatePackageInfo(ps, flags, userId);
3994            }
3995        }
3996        return null;
3997    }
3998
3999    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
4000        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
4001            return true;
4002        }
4003        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
4004            return true;
4005        }
4006        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
4007            return true;
4008        }
4009        return false;
4010    }
4011
4012    private boolean isComponentVisibleToInstantApp(
4013            @Nullable ComponentName component, @ComponentType int type) {
4014        if (type == TYPE_ACTIVITY) {
4015            final PackageParser.Activity activity = mActivities.mActivities.get(component);
4016            return activity != null
4017                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4018                    : false;
4019        } else if (type == TYPE_RECEIVER) {
4020            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
4021            return activity != null
4022                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4023                    : false;
4024        } else if (type == TYPE_SERVICE) {
4025            final PackageParser.Service service = mServices.mServices.get(component);
4026            return service != null
4027                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4028                    : false;
4029        } else if (type == TYPE_PROVIDER) {
4030            final PackageParser.Provider provider = mProviders.mProviders.get(component);
4031            return provider != null
4032                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4033                    : false;
4034        } else if (type == TYPE_UNKNOWN) {
4035            return isComponentVisibleToInstantApp(component);
4036        }
4037        return false;
4038    }
4039
4040    /**
4041     * Returns whether or not access to the application should be filtered.
4042     * <p>
4043     * Access may be limited based upon whether the calling or target applications
4044     * are instant applications.
4045     *
4046     * @see #canAccessInstantApps(int)
4047     */
4048    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4049            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4050        // if we're in an isolated process, get the real calling UID
4051        if (Process.isIsolated(callingUid)) {
4052            callingUid = mIsolatedOwners.get(callingUid);
4053        }
4054        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4055        final boolean callerIsInstantApp = instantAppPkgName != null;
4056        if (ps == null) {
4057            if (callerIsInstantApp) {
4058                // pretend the application exists, but, needs to be filtered
4059                return true;
4060            }
4061            return false;
4062        }
4063        // if the target and caller are the same application, don't filter
4064        if (isCallerSameApp(ps.name, callingUid)) {
4065            return false;
4066        }
4067        if (callerIsInstantApp) {
4068            // request for a specific component; if it hasn't been explicitly exposed, filter
4069            if (component != null) {
4070                return !isComponentVisibleToInstantApp(component, componentType);
4071            }
4072            // request for application; if no components have been explicitly exposed, filter
4073            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
4074        }
4075        if (ps.getInstantApp(userId)) {
4076            // caller can see all components of all instant applications, don't filter
4077            if (canViewInstantApps(callingUid, userId)) {
4078                return false;
4079            }
4080            // request for a specific instant application component, filter
4081            if (component != null) {
4082                return true;
4083            }
4084            // request for an instant application; if the caller hasn't been granted access, filter
4085            return !mInstantAppRegistry.isInstantAccessGranted(
4086                    userId, UserHandle.getAppId(callingUid), ps.appId);
4087        }
4088        return false;
4089    }
4090
4091    /**
4092     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4093     */
4094    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4095        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4096    }
4097
4098    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4099            int flags) {
4100        // Callers can access only the libs they depend on, otherwise they need to explicitly
4101        // ask for the shared libraries given the caller is allowed to access all static libs.
4102        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4103            // System/shell/root get to see all static libs
4104            final int appId = UserHandle.getAppId(uid);
4105            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4106                    || appId == Process.ROOT_UID) {
4107                return false;
4108            }
4109        }
4110
4111        // No package means no static lib as it is always on internal storage
4112        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4113            return false;
4114        }
4115
4116        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4117                ps.pkg.staticSharedLibVersion);
4118        if (libEntry == null) {
4119            return false;
4120        }
4121
4122        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4123        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4124        if (uidPackageNames == null) {
4125            return true;
4126        }
4127
4128        for (String uidPackageName : uidPackageNames) {
4129            if (ps.name.equals(uidPackageName)) {
4130                return false;
4131            }
4132            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4133            if (uidPs != null) {
4134                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4135                        libEntry.info.getName());
4136                if (index < 0) {
4137                    continue;
4138                }
4139                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
4140                    return false;
4141                }
4142            }
4143        }
4144        return true;
4145    }
4146
4147    @Override
4148    public String[] currentToCanonicalPackageNames(String[] names) {
4149        final int callingUid = Binder.getCallingUid();
4150        if (getInstantAppPackageName(callingUid) != null) {
4151            return names;
4152        }
4153        final String[] out = new String[names.length];
4154        // reader
4155        synchronized (mPackages) {
4156            final int callingUserId = UserHandle.getUserId(callingUid);
4157            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4158            for (int i=names.length-1; i>=0; i--) {
4159                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4160                boolean translateName = false;
4161                if (ps != null && ps.realName != null) {
4162                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4163                    translateName = !targetIsInstantApp
4164                            || canViewInstantApps
4165                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4166                                    UserHandle.getAppId(callingUid), ps.appId);
4167                }
4168                out[i] = translateName ? ps.realName : names[i];
4169            }
4170        }
4171        return out;
4172    }
4173
4174    @Override
4175    public String[] canonicalToCurrentPackageNames(String[] names) {
4176        final int callingUid = Binder.getCallingUid();
4177        if (getInstantAppPackageName(callingUid) != null) {
4178            return names;
4179        }
4180        final String[] out = new String[names.length];
4181        // reader
4182        synchronized (mPackages) {
4183            final int callingUserId = UserHandle.getUserId(callingUid);
4184            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4185            for (int i=names.length-1; i>=0; i--) {
4186                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4187                boolean translateName = false;
4188                if (cur != null) {
4189                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4190                    final boolean targetIsInstantApp =
4191                            ps != null && ps.getInstantApp(callingUserId);
4192                    translateName = !targetIsInstantApp
4193                            || canViewInstantApps
4194                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4195                                    UserHandle.getAppId(callingUid), ps.appId);
4196                }
4197                out[i] = translateName ? cur : names[i];
4198            }
4199        }
4200        return out;
4201    }
4202
4203    @Override
4204    public int getPackageUid(String packageName, int flags, int userId) {
4205        if (!sUserManager.exists(userId)) return -1;
4206        final int callingUid = Binder.getCallingUid();
4207        flags = updateFlagsForPackage(flags, userId, packageName);
4208        enforceCrossUserPermission(callingUid, userId,
4209                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4210
4211        // reader
4212        synchronized (mPackages) {
4213            final PackageParser.Package p = mPackages.get(packageName);
4214            if (p != null && p.isMatch(flags)) {
4215                PackageSetting ps = (PackageSetting) p.mExtras;
4216                if (filterAppAccessLPr(ps, callingUid, userId)) {
4217                    return -1;
4218                }
4219                return UserHandle.getUid(userId, p.applicationInfo.uid);
4220            }
4221            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4222                final PackageSetting ps = mSettings.mPackages.get(packageName);
4223                if (ps != null && ps.isMatch(flags)
4224                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4225                    return UserHandle.getUid(userId, ps.appId);
4226                }
4227            }
4228        }
4229
4230        return -1;
4231    }
4232
4233    @Override
4234    public int[] getPackageGids(String packageName, int flags, int userId) {
4235        if (!sUserManager.exists(userId)) return null;
4236        final int callingUid = Binder.getCallingUid();
4237        flags = updateFlagsForPackage(flags, userId, packageName);
4238        enforceCrossUserPermission(callingUid, userId,
4239                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4240
4241        // reader
4242        synchronized (mPackages) {
4243            final PackageParser.Package p = mPackages.get(packageName);
4244            if (p != null && p.isMatch(flags)) {
4245                PackageSetting ps = (PackageSetting) p.mExtras;
4246                if (filterAppAccessLPr(ps, callingUid, userId)) {
4247                    return null;
4248                }
4249                // TODO: Shouldn't this be checking for package installed state for userId and
4250                // return null?
4251                return ps.getPermissionsState().computeGids(userId);
4252            }
4253            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4254                final PackageSetting ps = mSettings.mPackages.get(packageName);
4255                if (ps != null && ps.isMatch(flags)
4256                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4257                    return ps.getPermissionsState().computeGids(userId);
4258                }
4259            }
4260        }
4261
4262        return null;
4263    }
4264
4265    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
4266        if (bp.perm != null) {
4267            return PackageParser.generatePermissionInfo(bp.perm, flags);
4268        }
4269        PermissionInfo pi = new PermissionInfo();
4270        pi.name = bp.name;
4271        pi.packageName = bp.sourcePackage;
4272        pi.nonLocalizedLabel = bp.name;
4273        pi.protectionLevel = bp.protectionLevel;
4274        return pi;
4275    }
4276
4277    @Override
4278    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4279        final int callingUid = Binder.getCallingUid();
4280        if (getInstantAppPackageName(callingUid) != null) {
4281            return null;
4282        }
4283        // reader
4284        synchronized (mPackages) {
4285            final BasePermission p = mSettings.mPermissions.get(name);
4286            if (p == null) {
4287                return null;
4288            }
4289            // If the caller is an app that targets pre 26 SDK drop protection flags.
4290            PermissionInfo permissionInfo = generatePermissionInfo(p, flags);
4291            if (permissionInfo != null) {
4292                final int protectionLevel = adjustPermissionProtectionFlagsLPr(
4293                        permissionInfo.protectionLevel, packageName, callingUid);
4294                if (permissionInfo.protectionLevel != protectionLevel) {
4295                    // If we return different protection level, don't use the cached info
4296                    if (p.perm != null && p.perm.info == permissionInfo) {
4297                        permissionInfo = new PermissionInfo(permissionInfo);
4298                    }
4299                    permissionInfo.protectionLevel = protectionLevel;
4300                }
4301            }
4302            return permissionInfo;
4303        }
4304    }
4305
4306    private int adjustPermissionProtectionFlagsLPr(int protectionLevel,
4307            String packageName, int uid) {
4308        // Signature permission flags area always reported
4309        final int protectionLevelMasked = protectionLevel
4310                & (PermissionInfo.PROTECTION_NORMAL
4311                | PermissionInfo.PROTECTION_DANGEROUS
4312                | PermissionInfo.PROTECTION_SIGNATURE);
4313        if (protectionLevelMasked == PermissionInfo.PROTECTION_SIGNATURE) {
4314            return protectionLevel;
4315        }
4316
4317        // System sees all flags.
4318        final int appId = UserHandle.getAppId(uid);
4319        if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID
4320                || appId == Process.SHELL_UID) {
4321            return protectionLevel;
4322        }
4323
4324        // Normalize package name to handle renamed packages and static libs
4325        packageName = resolveInternalPackageNameLPr(packageName,
4326                PackageManager.VERSION_CODE_HIGHEST);
4327
4328        // Apps that target O see flags for all protection levels.
4329        final PackageSetting ps = mSettings.mPackages.get(packageName);
4330        if (ps == null) {
4331            return protectionLevel;
4332        }
4333        if (ps.appId != appId) {
4334            return protectionLevel;
4335        }
4336
4337        final PackageParser.Package pkg = mPackages.get(packageName);
4338        if (pkg == null) {
4339            return protectionLevel;
4340        }
4341        if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
4342            return protectionLevelMasked;
4343        }
4344
4345        return protectionLevel;
4346    }
4347
4348    @Override
4349    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
4350            int flags) {
4351        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4352            return null;
4353        }
4354        // reader
4355        synchronized (mPackages) {
4356            if (group != null && !mPermissionGroups.containsKey(group)) {
4357                // This is thrown as NameNotFoundException
4358                return null;
4359            }
4360
4361            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4362            for (BasePermission p : mSettings.mPermissions.values()) {
4363                if (group == null) {
4364                    if (p.perm == null || p.perm.info.group == null) {
4365                        out.add(generatePermissionInfo(p, flags));
4366                    }
4367                } else {
4368                    if (p.perm != null && group.equals(p.perm.info.group)) {
4369                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
4370                    }
4371                }
4372            }
4373            return new ParceledListSlice<>(out);
4374        }
4375    }
4376
4377    @Override
4378    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4379        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4380            return null;
4381        }
4382        // reader
4383        synchronized (mPackages) {
4384            return PackageParser.generatePermissionGroupInfo(
4385                    mPermissionGroups.get(name), flags);
4386        }
4387    }
4388
4389    @Override
4390    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4391        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4392            return ParceledListSlice.emptyList();
4393        }
4394        // reader
4395        synchronized (mPackages) {
4396            final int N = mPermissionGroups.size();
4397            ArrayList<PermissionGroupInfo> out
4398                    = new ArrayList<PermissionGroupInfo>(N);
4399            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4400                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4401            }
4402            return new ParceledListSlice<>(out);
4403        }
4404    }
4405
4406    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4407            int filterCallingUid, int userId) {
4408        if (!sUserManager.exists(userId)) return null;
4409        PackageSetting ps = mSettings.mPackages.get(packageName);
4410        if (ps != null) {
4411            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4412                return null;
4413            }
4414            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4415                return null;
4416            }
4417            if (ps.pkg == null) {
4418                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4419                if (pInfo != null) {
4420                    return pInfo.applicationInfo;
4421                }
4422                return null;
4423            }
4424            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4425                    ps.readUserState(userId), userId);
4426            if (ai != null) {
4427                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4428            }
4429            return ai;
4430        }
4431        return null;
4432    }
4433
4434    @Override
4435    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4436        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4437    }
4438
4439    /**
4440     * Important: The provided filterCallingUid is used exclusively to filter out applications
4441     * that can be seen based on user state. It's typically the original caller uid prior
4442     * to clearing. Because it can only be provided by trusted code, it's value can be
4443     * trusted and will be used as-is; unlike userId which will be validated by this method.
4444     */
4445    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4446            int filterCallingUid, int userId) {
4447        if (!sUserManager.exists(userId)) return null;
4448        flags = updateFlagsForApplication(flags, userId, packageName);
4449        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4450                false /* requireFullPermission */, false /* checkShell */, "get application info");
4451
4452        // writer
4453        synchronized (mPackages) {
4454            // Normalize package name to handle renamed packages and static libs
4455            packageName = resolveInternalPackageNameLPr(packageName,
4456                    PackageManager.VERSION_CODE_HIGHEST);
4457
4458            PackageParser.Package p = mPackages.get(packageName);
4459            if (DEBUG_PACKAGE_INFO) Log.v(
4460                    TAG, "getApplicationInfo " + packageName
4461                    + ": " + p);
4462            if (p != null) {
4463                PackageSetting ps = mSettings.mPackages.get(packageName);
4464                if (ps == null) return null;
4465                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4466                    return null;
4467                }
4468                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4469                    return null;
4470                }
4471                // Note: isEnabledLP() does not apply here - always return info
4472                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4473                        p, flags, ps.readUserState(userId), userId);
4474                if (ai != null) {
4475                    ai.packageName = resolveExternalPackageNameLPr(p);
4476                }
4477                return ai;
4478            }
4479            if ("android".equals(packageName)||"system".equals(packageName)) {
4480                return mAndroidApplication;
4481            }
4482            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4483                // Already generates the external package name
4484                return generateApplicationInfoFromSettingsLPw(packageName,
4485                        flags, filterCallingUid, userId);
4486            }
4487        }
4488        return null;
4489    }
4490
4491    private String normalizePackageNameLPr(String packageName) {
4492        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4493        return normalizedPackageName != null ? normalizedPackageName : packageName;
4494    }
4495
4496    @Override
4497    public void deletePreloadsFileCache() {
4498        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4499            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4500        }
4501        File dir = Environment.getDataPreloadsFileCacheDirectory();
4502        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4503        FileUtils.deleteContents(dir);
4504    }
4505
4506    @Override
4507    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4508            final int storageFlags, final IPackageDataObserver observer) {
4509        mContext.enforceCallingOrSelfPermission(
4510                android.Manifest.permission.CLEAR_APP_CACHE, null);
4511        mHandler.post(() -> {
4512            boolean success = false;
4513            try {
4514                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4515                success = true;
4516            } catch (IOException e) {
4517                Slog.w(TAG, e);
4518            }
4519            if (observer != null) {
4520                try {
4521                    observer.onRemoveCompleted(null, success);
4522                } catch (RemoteException e) {
4523                    Slog.w(TAG, e);
4524                }
4525            }
4526        });
4527    }
4528
4529    @Override
4530    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4531            final int storageFlags, final IntentSender pi) {
4532        mContext.enforceCallingOrSelfPermission(
4533                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4534        mHandler.post(() -> {
4535            boolean success = false;
4536            try {
4537                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4538                success = true;
4539            } catch (IOException e) {
4540                Slog.w(TAG, e);
4541            }
4542            if (pi != null) {
4543                try {
4544                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4545                } catch (SendIntentException e) {
4546                    Slog.w(TAG, e);
4547                }
4548            }
4549        });
4550    }
4551
4552    /**
4553     * Blocking call to clear various types of cached data across the system
4554     * until the requested bytes are available.
4555     */
4556    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4557        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4558        final File file = storage.findPathForUuid(volumeUuid);
4559        if (file.getUsableSpace() >= bytes) return;
4560
4561        if (ENABLE_FREE_CACHE_V2) {
4562            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4563                    volumeUuid);
4564            final boolean aggressive = (storageFlags
4565                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4566            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4567
4568            // 1. Pre-flight to determine if we have any chance to succeed
4569            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4570            if (internalVolume && (aggressive || SystemProperties
4571                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4572                deletePreloadsFileCache();
4573                if (file.getUsableSpace() >= bytes) return;
4574            }
4575
4576            // 3. Consider parsed APK data (aggressive only)
4577            if (internalVolume && aggressive) {
4578                FileUtils.deleteContents(mCacheDir);
4579                if (file.getUsableSpace() >= bytes) return;
4580            }
4581
4582            // 4. Consider cached app data (above quotas)
4583            try {
4584                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4585                        Installer.FLAG_FREE_CACHE_V2);
4586            } catch (InstallerException ignored) {
4587            }
4588            if (file.getUsableSpace() >= bytes) return;
4589
4590            // 5. Consider shared libraries with refcount=0 and age>min cache period
4591            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4592                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4593                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4594                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4595                return;
4596            }
4597
4598            // 6. Consider dexopt output (aggressive only)
4599            // TODO: Implement
4600
4601            // 7. Consider installed instant apps unused longer than min cache period
4602            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4603                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4604                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4605                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4606                return;
4607            }
4608
4609            // 8. Consider cached app data (below quotas)
4610            try {
4611                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4612                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4613            } catch (InstallerException ignored) {
4614            }
4615            if (file.getUsableSpace() >= bytes) return;
4616
4617            // 9. Consider DropBox entries
4618            // TODO: Implement
4619
4620            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4621            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4622                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4623                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4624                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4625                return;
4626            }
4627        } else {
4628            try {
4629                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4630            } catch (InstallerException ignored) {
4631            }
4632            if (file.getUsableSpace() >= bytes) return;
4633        }
4634
4635        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4636    }
4637
4638    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4639            throws IOException {
4640        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4641        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4642
4643        List<VersionedPackage> packagesToDelete = null;
4644        final long now = System.currentTimeMillis();
4645
4646        synchronized (mPackages) {
4647            final int[] allUsers = sUserManager.getUserIds();
4648            final int libCount = mSharedLibraries.size();
4649            for (int i = 0; i < libCount; i++) {
4650                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4651                if (versionedLib == null) {
4652                    continue;
4653                }
4654                final int versionCount = versionedLib.size();
4655                for (int j = 0; j < versionCount; j++) {
4656                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4657                    // Skip packages that are not static shared libs.
4658                    if (!libInfo.isStatic()) {
4659                        break;
4660                    }
4661                    // Important: We skip static shared libs used for some user since
4662                    // in such a case we need to keep the APK on the device. The check for
4663                    // a lib being used for any user is performed by the uninstall call.
4664                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4665                    // Resolve the package name - we use synthetic package names internally
4666                    final String internalPackageName = resolveInternalPackageNameLPr(
4667                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4668                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4669                    // Skip unused static shared libs cached less than the min period
4670                    // to prevent pruning a lib needed by a subsequently installed package.
4671                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4672                        continue;
4673                    }
4674                    if (packagesToDelete == null) {
4675                        packagesToDelete = new ArrayList<>();
4676                    }
4677                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4678                            declaringPackage.getVersionCode()));
4679                }
4680            }
4681        }
4682
4683        if (packagesToDelete != null) {
4684            final int packageCount = packagesToDelete.size();
4685            for (int i = 0; i < packageCount; i++) {
4686                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4687                // Delete the package synchronously (will fail of the lib used for any user).
4688                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4689                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4690                                == PackageManager.DELETE_SUCCEEDED) {
4691                    if (volume.getUsableSpace() >= neededSpace) {
4692                        return true;
4693                    }
4694                }
4695            }
4696        }
4697
4698        return false;
4699    }
4700
4701    /**
4702     * Update given flags based on encryption status of current user.
4703     */
4704    private int updateFlags(int flags, int userId) {
4705        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4706                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4707            // Caller expressed an explicit opinion about what encryption
4708            // aware/unaware components they want to see, so fall through and
4709            // give them what they want
4710        } else {
4711            // Caller expressed no opinion, so match based on user state
4712            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4713                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4714            } else {
4715                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4716            }
4717        }
4718        return flags;
4719    }
4720
4721    private UserManagerInternal getUserManagerInternal() {
4722        if (mUserManagerInternal == null) {
4723            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4724        }
4725        return mUserManagerInternal;
4726    }
4727
4728    private DeviceIdleController.LocalService getDeviceIdleController() {
4729        if (mDeviceIdleController == null) {
4730            mDeviceIdleController =
4731                    LocalServices.getService(DeviceIdleController.LocalService.class);
4732        }
4733        return mDeviceIdleController;
4734    }
4735
4736    /**
4737     * Update given flags when being used to request {@link PackageInfo}.
4738     */
4739    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4740        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4741        boolean triaged = true;
4742        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4743                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4744            // Caller is asking for component details, so they'd better be
4745            // asking for specific encryption matching behavior, or be triaged
4746            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4747                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4748                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4749                triaged = false;
4750            }
4751        }
4752        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4753                | PackageManager.MATCH_SYSTEM_ONLY
4754                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4755            triaged = false;
4756        }
4757        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4758            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4759                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4760                    + Debug.getCallers(5));
4761        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4762                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4763            // If the caller wants all packages and has a restricted profile associated with it,
4764            // then match all users. This is to make sure that launchers that need to access work
4765            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4766            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4767            flags |= PackageManager.MATCH_ANY_USER;
4768        }
4769        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4770            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4771                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4772        }
4773        return updateFlags(flags, userId);
4774    }
4775
4776    /**
4777     * Update given flags when being used to request {@link ApplicationInfo}.
4778     */
4779    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4780        return updateFlagsForPackage(flags, userId, cookie);
4781    }
4782
4783    /**
4784     * Update given flags when being used to request {@link ComponentInfo}.
4785     */
4786    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4787        if (cookie instanceof Intent) {
4788            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4789                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4790            }
4791        }
4792
4793        boolean triaged = true;
4794        // Caller is asking for component details, so they'd better be
4795        // asking for specific encryption matching behavior, or be triaged
4796        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4797                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4798                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4799            triaged = false;
4800        }
4801        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4802            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4803                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4804        }
4805
4806        return updateFlags(flags, userId);
4807    }
4808
4809    /**
4810     * Update given intent when being used to request {@link ResolveInfo}.
4811     */
4812    private Intent updateIntentForResolve(Intent intent) {
4813        if (intent.getSelector() != null) {
4814            intent = intent.getSelector();
4815        }
4816        if (DEBUG_PREFERRED) {
4817            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4818        }
4819        return intent;
4820    }
4821
4822    /**
4823     * Update given flags when being used to request {@link ResolveInfo}.
4824     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4825     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4826     * flag set. However, this flag is only honoured in three circumstances:
4827     * <ul>
4828     * <li>when called from a system process</li>
4829     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4830     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4831     * action and a {@code android.intent.category.BROWSABLE} category</li>
4832     * </ul>
4833     */
4834    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4835        return updateFlagsForResolve(flags, userId, intent, callingUid,
4836                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4837    }
4838    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4839            boolean wantInstantApps) {
4840        return updateFlagsForResolve(flags, userId, intent, callingUid,
4841                wantInstantApps, false /*onlyExposedExplicitly*/);
4842    }
4843    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4844            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4845        // Safe mode means we shouldn't match any third-party components
4846        if (mSafeMode) {
4847            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4848        }
4849        if (getInstantAppPackageName(callingUid) != null) {
4850            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4851            if (onlyExposedExplicitly) {
4852                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4853            }
4854            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4855            flags |= PackageManager.MATCH_INSTANT;
4856        } else {
4857            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4858            final boolean allowMatchInstant =
4859                    (wantInstantApps
4860                            && Intent.ACTION_VIEW.equals(intent.getAction())
4861                            && hasWebURI(intent))
4862                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4863            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4864                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4865            if (!allowMatchInstant) {
4866                flags &= ~PackageManager.MATCH_INSTANT;
4867            }
4868        }
4869        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4870    }
4871
4872    @Override
4873    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4874        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4875    }
4876
4877    /**
4878     * Important: The provided filterCallingUid is used exclusively to filter out activities
4879     * that can be seen based on user state. It's typically the original caller uid prior
4880     * to clearing. Because it can only be provided by trusted code, it's value can be
4881     * trusted and will be used as-is; unlike userId which will be validated by this method.
4882     */
4883    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4884            int filterCallingUid, int userId) {
4885        if (!sUserManager.exists(userId)) return null;
4886        flags = updateFlagsForComponent(flags, userId, component);
4887        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4888                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4889        synchronized (mPackages) {
4890            PackageParser.Activity a = mActivities.mActivities.get(component);
4891
4892            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4893            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4894                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4895                if (ps == null) return null;
4896                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4897                    return null;
4898                }
4899                return PackageParser.generateActivityInfo(
4900                        a, flags, ps.readUserState(userId), userId);
4901            }
4902            if (mResolveComponentName.equals(component)) {
4903                return PackageParser.generateActivityInfo(
4904                        mResolveActivity, flags, new PackageUserState(), userId);
4905            }
4906        }
4907        return null;
4908    }
4909
4910    @Override
4911    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4912            String resolvedType) {
4913        synchronized (mPackages) {
4914            if (component.equals(mResolveComponentName)) {
4915                // The resolver supports EVERYTHING!
4916                return true;
4917            }
4918            final int callingUid = Binder.getCallingUid();
4919            final int callingUserId = UserHandle.getUserId(callingUid);
4920            PackageParser.Activity a = mActivities.mActivities.get(component);
4921            if (a == null) {
4922                return false;
4923            }
4924            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4925            if (ps == null) {
4926                return false;
4927            }
4928            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4929                return false;
4930            }
4931            for (int i=0; i<a.intents.size(); i++) {
4932                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4933                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4934                    return true;
4935                }
4936            }
4937            return false;
4938        }
4939    }
4940
4941    @Override
4942    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4943        if (!sUserManager.exists(userId)) return null;
4944        final int callingUid = Binder.getCallingUid();
4945        flags = updateFlagsForComponent(flags, userId, component);
4946        enforceCrossUserPermission(callingUid, userId,
4947                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4948        synchronized (mPackages) {
4949            PackageParser.Activity a = mReceivers.mActivities.get(component);
4950            if (DEBUG_PACKAGE_INFO) Log.v(
4951                TAG, "getReceiverInfo " + component + ": " + a);
4952            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4953                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4954                if (ps == null) return null;
4955                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4956                    return null;
4957                }
4958                return PackageParser.generateActivityInfo(
4959                        a, flags, ps.readUserState(userId), userId);
4960            }
4961        }
4962        return null;
4963    }
4964
4965    @Override
4966    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4967            int flags, int userId) {
4968        if (!sUserManager.exists(userId)) return null;
4969        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4970        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4971            return null;
4972        }
4973
4974        flags = updateFlagsForPackage(flags, userId, null);
4975
4976        final boolean canSeeStaticLibraries =
4977                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4978                        == PERMISSION_GRANTED
4979                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4980                        == PERMISSION_GRANTED
4981                || canRequestPackageInstallsInternal(packageName,
4982                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4983                        false  /* throwIfPermNotDeclared*/)
4984                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4985                        == PERMISSION_GRANTED;
4986
4987        synchronized (mPackages) {
4988            List<SharedLibraryInfo> result = null;
4989
4990            final int libCount = mSharedLibraries.size();
4991            for (int i = 0; i < libCount; i++) {
4992                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4993                if (versionedLib == null) {
4994                    continue;
4995                }
4996
4997                final int versionCount = versionedLib.size();
4998                for (int j = 0; j < versionCount; j++) {
4999                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
5000                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
5001                        break;
5002                    }
5003                    final long identity = Binder.clearCallingIdentity();
5004                    try {
5005                        PackageInfo packageInfo = getPackageInfoVersioned(
5006                                libInfo.getDeclaringPackage(), flags
5007                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
5008                        if (packageInfo == null) {
5009                            continue;
5010                        }
5011                    } finally {
5012                        Binder.restoreCallingIdentity(identity);
5013                    }
5014
5015                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
5016                            libInfo.getVersion(), libInfo.getType(),
5017                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
5018                            flags, userId));
5019
5020                    if (result == null) {
5021                        result = new ArrayList<>();
5022                    }
5023                    result.add(resLibInfo);
5024                }
5025            }
5026
5027            return result != null ? new ParceledListSlice<>(result) : null;
5028        }
5029    }
5030
5031    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
5032            SharedLibraryInfo libInfo, int flags, int userId) {
5033        List<VersionedPackage> versionedPackages = null;
5034        final int packageCount = mSettings.mPackages.size();
5035        for (int i = 0; i < packageCount; i++) {
5036            PackageSetting ps = mSettings.mPackages.valueAt(i);
5037
5038            if (ps == null) {
5039                continue;
5040            }
5041
5042            if (!ps.getUserState().get(userId).isAvailable(flags)) {
5043                continue;
5044            }
5045
5046            final String libName = libInfo.getName();
5047            if (libInfo.isStatic()) {
5048                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
5049                if (libIdx < 0) {
5050                    continue;
5051                }
5052                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
5053                    continue;
5054                }
5055                if (versionedPackages == null) {
5056                    versionedPackages = new ArrayList<>();
5057                }
5058                // If the dependent is a static shared lib, use the public package name
5059                String dependentPackageName = ps.name;
5060                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
5061                    dependentPackageName = ps.pkg.manifestPackageName;
5062                }
5063                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
5064            } else if (ps.pkg != null) {
5065                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5066                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5067                    if (versionedPackages == null) {
5068                        versionedPackages = new ArrayList<>();
5069                    }
5070                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5071                }
5072            }
5073        }
5074
5075        return versionedPackages;
5076    }
5077
5078    @Override
5079    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5080        if (!sUserManager.exists(userId)) return null;
5081        final int callingUid = Binder.getCallingUid();
5082        flags = updateFlagsForComponent(flags, userId, component);
5083        enforceCrossUserPermission(callingUid, userId,
5084                false /* requireFullPermission */, false /* checkShell */, "get service info");
5085        synchronized (mPackages) {
5086            PackageParser.Service s = mServices.mServices.get(component);
5087            if (DEBUG_PACKAGE_INFO) Log.v(
5088                TAG, "getServiceInfo " + component + ": " + s);
5089            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5090                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5091                if (ps == null) return null;
5092                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5093                    return null;
5094                }
5095                return PackageParser.generateServiceInfo(
5096                        s, flags, ps.readUserState(userId), userId);
5097            }
5098        }
5099        return null;
5100    }
5101
5102    @Override
5103    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5104        if (!sUserManager.exists(userId)) return null;
5105        final int callingUid = Binder.getCallingUid();
5106        flags = updateFlagsForComponent(flags, userId, component);
5107        enforceCrossUserPermission(callingUid, userId,
5108                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5109        synchronized (mPackages) {
5110            PackageParser.Provider p = mProviders.mProviders.get(component);
5111            if (DEBUG_PACKAGE_INFO) Log.v(
5112                TAG, "getProviderInfo " + component + ": " + p);
5113            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5114                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5115                if (ps == null) return null;
5116                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5117                    return null;
5118                }
5119                return PackageParser.generateProviderInfo(
5120                        p, flags, ps.readUserState(userId), userId);
5121            }
5122        }
5123        return null;
5124    }
5125
5126    @Override
5127    public String[] getSystemSharedLibraryNames() {
5128        // allow instant applications
5129        synchronized (mPackages) {
5130            Set<String> libs = null;
5131            final int libCount = mSharedLibraries.size();
5132            for (int i = 0; i < libCount; i++) {
5133                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5134                if (versionedLib == null) {
5135                    continue;
5136                }
5137                final int versionCount = versionedLib.size();
5138                for (int j = 0; j < versionCount; j++) {
5139                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5140                    if (!libEntry.info.isStatic()) {
5141                        if (libs == null) {
5142                            libs = new ArraySet<>();
5143                        }
5144                        libs.add(libEntry.info.getName());
5145                        break;
5146                    }
5147                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5148                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5149                            UserHandle.getUserId(Binder.getCallingUid()),
5150                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5151                        if (libs == null) {
5152                            libs = new ArraySet<>();
5153                        }
5154                        libs.add(libEntry.info.getName());
5155                        break;
5156                    }
5157                }
5158            }
5159
5160            if (libs != null) {
5161                String[] libsArray = new String[libs.size()];
5162                libs.toArray(libsArray);
5163                return libsArray;
5164            }
5165
5166            return null;
5167        }
5168    }
5169
5170    @Override
5171    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5172        // allow instant applications
5173        synchronized (mPackages) {
5174            return mServicesSystemSharedLibraryPackageName;
5175        }
5176    }
5177
5178    @Override
5179    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5180        // allow instant applications
5181        synchronized (mPackages) {
5182            return mSharedSystemSharedLibraryPackageName;
5183        }
5184    }
5185
5186    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5187        for (int i = userList.length - 1; i >= 0; --i) {
5188            final int userId = userList[i];
5189            // don't add instant app to the list of updates
5190            if (pkgSetting.getInstantApp(userId)) {
5191                continue;
5192            }
5193            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5194            if (changedPackages == null) {
5195                changedPackages = new SparseArray<>();
5196                mChangedPackages.put(userId, changedPackages);
5197            }
5198            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5199            if (sequenceNumbers == null) {
5200                sequenceNumbers = new HashMap<>();
5201                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5202            }
5203            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5204            if (sequenceNumber != null) {
5205                changedPackages.remove(sequenceNumber);
5206            }
5207            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5208            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5209        }
5210        mChangedPackagesSequenceNumber++;
5211    }
5212
5213    @Override
5214    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5215        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5216            return null;
5217        }
5218        synchronized (mPackages) {
5219            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5220                return null;
5221            }
5222            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5223            if (changedPackages == null) {
5224                return null;
5225            }
5226            final List<String> packageNames =
5227                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5228            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5229                final String packageName = changedPackages.get(i);
5230                if (packageName != null) {
5231                    packageNames.add(packageName);
5232                }
5233            }
5234            return packageNames.isEmpty()
5235                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5236        }
5237    }
5238
5239    @Override
5240    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5241        // allow instant applications
5242        ArrayList<FeatureInfo> res;
5243        synchronized (mAvailableFeatures) {
5244            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5245            res.addAll(mAvailableFeatures.values());
5246        }
5247        final FeatureInfo fi = new FeatureInfo();
5248        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5249                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5250        res.add(fi);
5251
5252        return new ParceledListSlice<>(res);
5253    }
5254
5255    @Override
5256    public boolean hasSystemFeature(String name, int version) {
5257        // allow instant applications
5258        synchronized (mAvailableFeatures) {
5259            final FeatureInfo feat = mAvailableFeatures.get(name);
5260            if (feat == null) {
5261                return false;
5262            } else {
5263                return feat.version >= version;
5264            }
5265        }
5266    }
5267
5268    @Override
5269    public int checkPermission(String permName, String pkgName, int userId) {
5270        if (!sUserManager.exists(userId)) {
5271            return PackageManager.PERMISSION_DENIED;
5272        }
5273        final int callingUid = Binder.getCallingUid();
5274
5275        synchronized (mPackages) {
5276            final PackageParser.Package p = mPackages.get(pkgName);
5277            if (p != null && p.mExtras != null) {
5278                final PackageSetting ps = (PackageSetting) p.mExtras;
5279                if (filterAppAccessLPr(ps, callingUid, userId)) {
5280                    return PackageManager.PERMISSION_DENIED;
5281                }
5282                final boolean instantApp = ps.getInstantApp(userId);
5283                final PermissionsState permissionsState = ps.getPermissionsState();
5284                if (permissionsState.hasPermission(permName, userId)) {
5285                    if (instantApp) {
5286                        BasePermission bp = mSettings.mPermissions.get(permName);
5287                        if (bp != null && bp.isInstant()) {
5288                            return PackageManager.PERMISSION_GRANTED;
5289                        }
5290                    } else {
5291                        return PackageManager.PERMISSION_GRANTED;
5292                    }
5293                }
5294                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5295                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5296                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5297                    return PackageManager.PERMISSION_GRANTED;
5298                }
5299            }
5300        }
5301
5302        return PackageManager.PERMISSION_DENIED;
5303    }
5304
5305    @Override
5306    public int checkUidPermission(String permName, int uid) {
5307        final int callingUid = Binder.getCallingUid();
5308        final int callingUserId = UserHandle.getUserId(callingUid);
5309        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5310        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
5311        final int userId = UserHandle.getUserId(uid);
5312        if (!sUserManager.exists(userId)) {
5313            return PackageManager.PERMISSION_DENIED;
5314        }
5315
5316        synchronized (mPackages) {
5317            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5318            if (obj != null) {
5319                if (obj instanceof SharedUserSetting) {
5320                    if (isCallerInstantApp) {
5321                        return PackageManager.PERMISSION_DENIED;
5322                    }
5323                } else if (obj instanceof PackageSetting) {
5324                    final PackageSetting ps = (PackageSetting) obj;
5325                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5326                        return PackageManager.PERMISSION_DENIED;
5327                    }
5328                }
5329                final SettingBase settingBase = (SettingBase) obj;
5330                final PermissionsState permissionsState = settingBase.getPermissionsState();
5331                if (permissionsState.hasPermission(permName, userId)) {
5332                    if (isUidInstantApp) {
5333                        BasePermission bp = mSettings.mPermissions.get(permName);
5334                        if (bp != null && bp.isInstant()) {
5335                            return PackageManager.PERMISSION_GRANTED;
5336                        }
5337                    } else {
5338                        return PackageManager.PERMISSION_GRANTED;
5339                    }
5340                }
5341                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5342                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5343                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5344                    return PackageManager.PERMISSION_GRANTED;
5345                }
5346            } else {
5347                ArraySet<String> perms = mSystemPermissions.get(uid);
5348                if (perms != null) {
5349                    if (perms.contains(permName)) {
5350                        return PackageManager.PERMISSION_GRANTED;
5351                    }
5352                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5353                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5354                        return PackageManager.PERMISSION_GRANTED;
5355                    }
5356                }
5357            }
5358        }
5359
5360        return PackageManager.PERMISSION_DENIED;
5361    }
5362
5363    @Override
5364    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5365        if (UserHandle.getCallingUserId() != userId) {
5366            mContext.enforceCallingPermission(
5367                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5368                    "isPermissionRevokedByPolicy for user " + userId);
5369        }
5370
5371        if (checkPermission(permission, packageName, userId)
5372                == PackageManager.PERMISSION_GRANTED) {
5373            return false;
5374        }
5375
5376        final int callingUid = Binder.getCallingUid();
5377        if (getInstantAppPackageName(callingUid) != null) {
5378            if (!isCallerSameApp(packageName, callingUid)) {
5379                return false;
5380            }
5381        } else {
5382            if (isInstantApp(packageName, userId)) {
5383                return false;
5384            }
5385        }
5386
5387        final long identity = Binder.clearCallingIdentity();
5388        try {
5389            final int flags = getPermissionFlags(permission, packageName, userId);
5390            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5391        } finally {
5392            Binder.restoreCallingIdentity(identity);
5393        }
5394    }
5395
5396    @Override
5397    public String getPermissionControllerPackageName() {
5398        synchronized (mPackages) {
5399            return mRequiredInstallerPackage;
5400        }
5401    }
5402
5403    /**
5404     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
5405     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
5406     * @param checkShell whether to prevent shell from access if there's a debugging restriction
5407     * @param message the message to log on security exception
5408     */
5409    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
5410            boolean checkShell, String message) {
5411        if (userId < 0) {
5412            throw new IllegalArgumentException("Invalid userId " + userId);
5413        }
5414        if (checkShell) {
5415            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
5416        }
5417        if (userId == UserHandle.getUserId(callingUid)) return;
5418        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5419            if (requireFullPermission) {
5420                mContext.enforceCallingOrSelfPermission(
5421                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5422            } else {
5423                try {
5424                    mContext.enforceCallingOrSelfPermission(
5425                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5426                } catch (SecurityException se) {
5427                    mContext.enforceCallingOrSelfPermission(
5428                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5429                }
5430            }
5431        }
5432    }
5433
5434    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5435        if (callingUid == Process.SHELL_UID) {
5436            if (userHandle >= 0
5437                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
5438                throw new SecurityException("Shell does not have permission to access user "
5439                        + userHandle);
5440            } else if (userHandle < 0) {
5441                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5442                        + Debug.getCallers(3));
5443            }
5444        }
5445    }
5446
5447    private BasePermission findPermissionTreeLP(String permName) {
5448        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
5449            if (permName.startsWith(bp.name) &&
5450                    permName.length() > bp.name.length() &&
5451                    permName.charAt(bp.name.length()) == '.') {
5452                return bp;
5453            }
5454        }
5455        return null;
5456    }
5457
5458    private BasePermission checkPermissionTreeLP(String permName) {
5459        if (permName != null) {
5460            BasePermission bp = findPermissionTreeLP(permName);
5461            if (bp != null) {
5462                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
5463                    return bp;
5464                }
5465                throw new SecurityException("Calling uid "
5466                        + Binder.getCallingUid()
5467                        + " is not allowed to add to permission tree "
5468                        + bp.name + " owned by uid " + bp.uid);
5469            }
5470        }
5471        throw new SecurityException("No permission tree found for " + permName);
5472    }
5473
5474    static boolean compareStrings(CharSequence s1, CharSequence s2) {
5475        if (s1 == null) {
5476            return s2 == null;
5477        }
5478        if (s2 == null) {
5479            return false;
5480        }
5481        if (s1.getClass() != s2.getClass()) {
5482            return false;
5483        }
5484        return s1.equals(s2);
5485    }
5486
5487    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5488        if (pi1.icon != pi2.icon) return false;
5489        if (pi1.logo != pi2.logo) return false;
5490        if (pi1.protectionLevel != pi2.protectionLevel) return false;
5491        if (!compareStrings(pi1.name, pi2.name)) return false;
5492        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5493        // We'll take care of setting this one.
5494        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5495        // These are not currently stored in settings.
5496        //if (!compareStrings(pi1.group, pi2.group)) return false;
5497        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5498        //if (pi1.labelRes != pi2.labelRes) return false;
5499        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5500        return true;
5501    }
5502
5503    int permissionInfoFootprint(PermissionInfo info) {
5504        int size = info.name.length();
5505        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5506        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5507        return size;
5508    }
5509
5510    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5511        int size = 0;
5512        for (BasePermission perm : mSettings.mPermissions.values()) {
5513            if (perm.uid == tree.uid) {
5514                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5515            }
5516        }
5517        return size;
5518    }
5519
5520    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5521        // We calculate the max size of permissions defined by this uid and throw
5522        // if that plus the size of 'info' would exceed our stated maximum.
5523        if (tree.uid != Process.SYSTEM_UID) {
5524            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5525            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5526                throw new SecurityException("Permission tree size cap exceeded");
5527            }
5528        }
5529    }
5530
5531    boolean addPermissionLocked(PermissionInfo info, boolean async) {
5532        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5533            throw new SecurityException("Instant apps can't add permissions");
5534        }
5535        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5536            throw new SecurityException("Label must be specified in permission");
5537        }
5538        BasePermission tree = checkPermissionTreeLP(info.name);
5539        BasePermission bp = mSettings.mPermissions.get(info.name);
5540        boolean added = bp == null;
5541        boolean changed = true;
5542        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5543        if (added) {
5544            enforcePermissionCapLocked(info, tree);
5545            bp = new BasePermission(info.name, tree.sourcePackage,
5546                    BasePermission.TYPE_DYNAMIC);
5547        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5548            throw new SecurityException(
5549                    "Not allowed to modify non-dynamic permission "
5550                    + info.name);
5551        } else {
5552            if (bp.protectionLevel == fixedLevel
5553                    && bp.perm.owner.equals(tree.perm.owner)
5554                    && bp.uid == tree.uid
5555                    && comparePermissionInfos(bp.perm.info, info)) {
5556                changed = false;
5557            }
5558        }
5559        bp.protectionLevel = fixedLevel;
5560        info = new PermissionInfo(info);
5561        info.protectionLevel = fixedLevel;
5562        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5563        bp.perm.info.packageName = tree.perm.info.packageName;
5564        bp.uid = tree.uid;
5565        if (added) {
5566            mSettings.mPermissions.put(info.name, bp);
5567        }
5568        if (changed) {
5569            if (!async) {
5570                mSettings.writeLPr();
5571            } else {
5572                scheduleWriteSettingsLocked();
5573            }
5574        }
5575        return added;
5576    }
5577
5578    @Override
5579    public boolean addPermission(PermissionInfo info) {
5580        synchronized (mPackages) {
5581            return addPermissionLocked(info, false);
5582        }
5583    }
5584
5585    @Override
5586    public boolean addPermissionAsync(PermissionInfo info) {
5587        synchronized (mPackages) {
5588            return addPermissionLocked(info, true);
5589        }
5590    }
5591
5592    @Override
5593    public void removePermission(String name) {
5594        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5595            throw new SecurityException("Instant applications don't have access to this method");
5596        }
5597        synchronized (mPackages) {
5598            checkPermissionTreeLP(name);
5599            BasePermission bp = mSettings.mPermissions.get(name);
5600            if (bp != null) {
5601                if (bp.type != BasePermission.TYPE_DYNAMIC) {
5602                    throw new SecurityException(
5603                            "Not allowed to modify non-dynamic permission "
5604                            + name);
5605                }
5606                mSettings.mPermissions.remove(name);
5607                mSettings.writeLPr();
5608            }
5609        }
5610    }
5611
5612    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5613            PackageParser.Package pkg, BasePermission bp) {
5614        int index = pkg.requestedPermissions.indexOf(bp.name);
5615        if (index == -1) {
5616            throw new SecurityException("Package " + pkg.packageName
5617                    + " has not requested permission " + bp.name);
5618        }
5619        if (!bp.isRuntime() && !bp.isDevelopment()) {
5620            throw new SecurityException("Permission " + bp.name
5621                    + " is not a changeable permission type");
5622        }
5623    }
5624
5625    @Override
5626    public void grantRuntimePermission(String packageName, String name, final int userId) {
5627        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5628    }
5629
5630    private void grantRuntimePermission(String packageName, String name, final int userId,
5631            boolean overridePolicy) {
5632        if (!sUserManager.exists(userId)) {
5633            Log.e(TAG, "No such user:" + userId);
5634            return;
5635        }
5636        final int callingUid = Binder.getCallingUid();
5637
5638        mContext.enforceCallingOrSelfPermission(
5639                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5640                "grantRuntimePermission");
5641
5642        enforceCrossUserPermission(callingUid, userId,
5643                true /* requireFullPermission */, true /* checkShell */,
5644                "grantRuntimePermission");
5645
5646        final int uid;
5647        final PackageSetting ps;
5648
5649        synchronized (mPackages) {
5650            final PackageParser.Package pkg = mPackages.get(packageName);
5651            if (pkg == null) {
5652                throw new IllegalArgumentException("Unknown package: " + packageName);
5653            }
5654            final BasePermission bp = mSettings.mPermissions.get(name);
5655            if (bp == null) {
5656                throw new IllegalArgumentException("Unknown permission: " + name);
5657            }
5658            ps = (PackageSetting) pkg.mExtras;
5659            if (ps == null
5660                    || filterAppAccessLPr(ps, callingUid, userId)) {
5661                throw new IllegalArgumentException("Unknown package: " + packageName);
5662            }
5663
5664            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5665
5666            // If a permission review is required for legacy apps we represent
5667            // their permissions as always granted runtime ones since we need
5668            // to keep the review required permission flag per user while an
5669            // install permission's state is shared across all users.
5670            if (mPermissionReviewRequired
5671                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5672                    && bp.isRuntime()) {
5673                return;
5674            }
5675
5676            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5677
5678            final PermissionsState permissionsState = ps.getPermissionsState();
5679
5680            final int flags = permissionsState.getPermissionFlags(name, userId);
5681            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5682                throw new SecurityException("Cannot grant system fixed permission "
5683                        + name + " for package " + packageName);
5684            }
5685            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5686                throw new SecurityException("Cannot grant policy fixed permission "
5687                        + name + " for package " + packageName);
5688            }
5689
5690            if (bp.isDevelopment()) {
5691                // Development permissions must be handled specially, since they are not
5692                // normal runtime permissions.  For now they apply to all users.
5693                if (permissionsState.grantInstallPermission(bp) !=
5694                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5695                    scheduleWriteSettingsLocked();
5696                }
5697                return;
5698            }
5699
5700            if (ps.getInstantApp(userId) && !bp.isInstant()) {
5701                throw new SecurityException("Cannot grant non-ephemeral permission"
5702                        + name + " for package " + packageName);
5703            }
5704
5705            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5706                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5707                return;
5708            }
5709
5710            final int result = permissionsState.grantRuntimePermission(bp, userId);
5711            switch (result) {
5712                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5713                    return;
5714                }
5715
5716                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5717                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5718                    mHandler.post(new Runnable() {
5719                        @Override
5720                        public void run() {
5721                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5722                        }
5723                    });
5724                }
5725                break;
5726            }
5727
5728            if (bp.isRuntime()) {
5729                logPermissionGranted(mContext, name, packageName);
5730            }
5731
5732            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5733
5734            // Not critical if that is lost - app has to request again.
5735            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5736        }
5737
5738        // Only need to do this if user is initialized. Otherwise it's a new user
5739        // and there are no processes running as the user yet and there's no need
5740        // to make an expensive call to remount processes for the changed permissions.
5741        if (READ_EXTERNAL_STORAGE.equals(name)
5742                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5743            final long token = Binder.clearCallingIdentity();
5744            try {
5745                if (sUserManager.isInitialized(userId)) {
5746                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5747                            StorageManagerInternal.class);
5748                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5749                }
5750            } finally {
5751                Binder.restoreCallingIdentity(token);
5752            }
5753        }
5754    }
5755
5756    @Override
5757    public void revokeRuntimePermission(String packageName, String name, int userId) {
5758        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5759    }
5760
5761    private void revokeRuntimePermission(String packageName, String name, int userId,
5762            boolean overridePolicy) {
5763        if (!sUserManager.exists(userId)) {
5764            Log.e(TAG, "No such user:" + userId);
5765            return;
5766        }
5767
5768        mContext.enforceCallingOrSelfPermission(
5769                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5770                "revokeRuntimePermission");
5771
5772        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5773                true /* requireFullPermission */, true /* checkShell */,
5774                "revokeRuntimePermission");
5775
5776        final int appId;
5777
5778        synchronized (mPackages) {
5779            final PackageParser.Package pkg = mPackages.get(packageName);
5780            if (pkg == null) {
5781                throw new IllegalArgumentException("Unknown package: " + packageName);
5782            }
5783            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5784            if (ps == null
5785                    || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
5786                throw new IllegalArgumentException("Unknown package: " + packageName);
5787            }
5788            final BasePermission bp = mSettings.mPermissions.get(name);
5789            if (bp == null) {
5790                throw new IllegalArgumentException("Unknown permission: " + name);
5791            }
5792
5793            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5794
5795            // If a permission review is required for legacy apps we represent
5796            // their permissions as always granted runtime ones since we need
5797            // to keep the review required permission flag per user while an
5798            // install permission's state is shared across all users.
5799            if (mPermissionReviewRequired
5800                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5801                    && bp.isRuntime()) {
5802                return;
5803            }
5804
5805            final PermissionsState permissionsState = ps.getPermissionsState();
5806
5807            final int flags = permissionsState.getPermissionFlags(name, userId);
5808            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5809                throw new SecurityException("Cannot revoke system fixed permission "
5810                        + name + " for package " + packageName);
5811            }
5812            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5813                throw new SecurityException("Cannot revoke policy fixed permission "
5814                        + name + " for package " + packageName);
5815            }
5816
5817            if (bp.isDevelopment()) {
5818                // Development permissions must be handled specially, since they are not
5819                // normal runtime permissions.  For now they apply to all users.
5820                if (permissionsState.revokeInstallPermission(bp) !=
5821                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5822                    scheduleWriteSettingsLocked();
5823                }
5824                return;
5825            }
5826
5827            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5828                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5829                return;
5830            }
5831
5832            if (bp.isRuntime()) {
5833                logPermissionRevoked(mContext, name, packageName);
5834            }
5835
5836            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5837
5838            // Critical, after this call app should never have the permission.
5839            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5840
5841            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5842        }
5843
5844        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5845    }
5846
5847    /**
5848     * Get the first event id for the permission.
5849     *
5850     * <p>There are four events for each permission: <ul>
5851     *     <li>Request permission: first id + 0</li>
5852     *     <li>Grant permission: first id + 1</li>
5853     *     <li>Request for permission denied: first id + 2</li>
5854     *     <li>Revoke permission: first id + 3</li>
5855     * </ul></p>
5856     *
5857     * @param name name of the permission
5858     *
5859     * @return The first event id for the permission
5860     */
5861    private static int getBaseEventId(@NonNull String name) {
5862        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5863
5864        if (eventIdIndex == -1) {
5865            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5866                    || Build.IS_USER) {
5867                Log.i(TAG, "Unknown permission " + name);
5868
5869                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5870            } else {
5871                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5872                //
5873                // Also update
5874                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5875                // - metrics_constants.proto
5876                throw new IllegalStateException("Unknown permission " + name);
5877            }
5878        }
5879
5880        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5881    }
5882
5883    /**
5884     * Log that a permission was revoked.
5885     *
5886     * @param context Context of the caller
5887     * @param name name of the permission
5888     * @param packageName package permission if for
5889     */
5890    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5891            @NonNull String packageName) {
5892        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5893    }
5894
5895    /**
5896     * Log that a permission request was granted.
5897     *
5898     * @param context Context of the caller
5899     * @param name name of the permission
5900     * @param packageName package permission if for
5901     */
5902    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5903            @NonNull String packageName) {
5904        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5905    }
5906
5907    @Override
5908    public void resetRuntimePermissions() {
5909        mContext.enforceCallingOrSelfPermission(
5910                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5911                "revokeRuntimePermission");
5912
5913        int callingUid = Binder.getCallingUid();
5914        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5915            mContext.enforceCallingOrSelfPermission(
5916                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5917                    "resetRuntimePermissions");
5918        }
5919
5920        synchronized (mPackages) {
5921            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5922            for (int userId : UserManagerService.getInstance().getUserIds()) {
5923                final int packageCount = mPackages.size();
5924                for (int i = 0; i < packageCount; i++) {
5925                    PackageParser.Package pkg = mPackages.valueAt(i);
5926                    if (!(pkg.mExtras instanceof PackageSetting)) {
5927                        continue;
5928                    }
5929                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5930                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5931                }
5932            }
5933        }
5934    }
5935
5936    @Override
5937    public int getPermissionFlags(String name, String packageName, int userId) {
5938        if (!sUserManager.exists(userId)) {
5939            return 0;
5940        }
5941
5942        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5943
5944        final int callingUid = Binder.getCallingUid();
5945        enforceCrossUserPermission(callingUid, userId,
5946                true /* requireFullPermission */, false /* checkShell */,
5947                "getPermissionFlags");
5948
5949        synchronized (mPackages) {
5950            final PackageParser.Package pkg = mPackages.get(packageName);
5951            if (pkg == null) {
5952                return 0;
5953            }
5954            final BasePermission bp = mSettings.mPermissions.get(name);
5955            if (bp == null) {
5956                return 0;
5957            }
5958            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5959            if (ps == null
5960                    || filterAppAccessLPr(ps, callingUid, userId)) {
5961                return 0;
5962            }
5963            PermissionsState permissionsState = ps.getPermissionsState();
5964            return permissionsState.getPermissionFlags(name, userId);
5965        }
5966    }
5967
5968    @Override
5969    public void updatePermissionFlags(String name, String packageName, int flagMask,
5970            int flagValues, int userId) {
5971        if (!sUserManager.exists(userId)) {
5972            return;
5973        }
5974
5975        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5976
5977        final int callingUid = Binder.getCallingUid();
5978        enforceCrossUserPermission(callingUid, userId,
5979                true /* requireFullPermission */, true /* checkShell */,
5980                "updatePermissionFlags");
5981
5982        // Only the system can change these flags and nothing else.
5983        if (getCallingUid() != Process.SYSTEM_UID) {
5984            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5985            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5986            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5987            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5988            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5989        }
5990
5991        synchronized (mPackages) {
5992            final PackageParser.Package pkg = mPackages.get(packageName);
5993            if (pkg == null) {
5994                throw new IllegalArgumentException("Unknown package: " + packageName);
5995            }
5996            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5997            if (ps == null
5998                    || filterAppAccessLPr(ps, callingUid, userId)) {
5999                throw new IllegalArgumentException("Unknown package: " + packageName);
6000            }
6001
6002            final BasePermission bp = mSettings.mPermissions.get(name);
6003            if (bp == null) {
6004                throw new IllegalArgumentException("Unknown permission: " + name);
6005            }
6006
6007            PermissionsState permissionsState = ps.getPermissionsState();
6008
6009            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
6010
6011            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
6012                // Install and runtime permissions are stored in different places,
6013                // so figure out what permission changed and persist the change.
6014                if (permissionsState.getInstallPermissionState(name) != null) {
6015                    scheduleWriteSettingsLocked();
6016                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
6017                        || hadState) {
6018                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
6019                }
6020            }
6021        }
6022    }
6023
6024    /**
6025     * Update the permission flags for all packages and runtime permissions of a user in order
6026     * to allow device or profile owner to remove POLICY_FIXED.
6027     */
6028    @Override
6029    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
6030        if (!sUserManager.exists(userId)) {
6031            return;
6032        }
6033
6034        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
6035
6036        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6037                true /* requireFullPermission */, true /* checkShell */,
6038                "updatePermissionFlagsForAllApps");
6039
6040        // Only the system can change system fixed flags.
6041        if (getCallingUid() != Process.SYSTEM_UID) {
6042            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
6043            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
6044        }
6045
6046        synchronized (mPackages) {
6047            boolean changed = false;
6048            final int packageCount = mPackages.size();
6049            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
6050                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
6051                final PackageSetting ps = (PackageSetting) pkg.mExtras;
6052                if (ps == null) {
6053                    continue;
6054                }
6055                PermissionsState permissionsState = ps.getPermissionsState();
6056                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
6057                        userId, flagMask, flagValues);
6058            }
6059            if (changed) {
6060                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
6061            }
6062        }
6063    }
6064
6065    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
6066        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
6067                != PackageManager.PERMISSION_GRANTED
6068            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
6069                != PackageManager.PERMISSION_GRANTED) {
6070            throw new SecurityException(message + " requires "
6071                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
6072                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
6073        }
6074    }
6075
6076    @Override
6077    public boolean shouldShowRequestPermissionRationale(String permissionName,
6078            String packageName, int userId) {
6079        if (UserHandle.getCallingUserId() != userId) {
6080            mContext.enforceCallingPermission(
6081                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
6082                    "canShowRequestPermissionRationale for user " + userId);
6083        }
6084
6085        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
6086        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
6087            return false;
6088        }
6089
6090        if (checkPermission(permissionName, packageName, userId)
6091                == PackageManager.PERMISSION_GRANTED) {
6092            return false;
6093        }
6094
6095        final int flags;
6096
6097        final long identity = Binder.clearCallingIdentity();
6098        try {
6099            flags = getPermissionFlags(permissionName,
6100                    packageName, userId);
6101        } finally {
6102            Binder.restoreCallingIdentity(identity);
6103        }
6104
6105        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
6106                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
6107                | PackageManager.FLAG_PERMISSION_USER_FIXED;
6108
6109        if ((flags & fixedFlags) != 0) {
6110            return false;
6111        }
6112
6113        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
6114    }
6115
6116    @Override
6117    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6118        mContext.enforceCallingOrSelfPermission(
6119                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
6120                "addOnPermissionsChangeListener");
6121
6122        synchronized (mPackages) {
6123            mOnPermissionChangeListeners.addListenerLocked(listener);
6124        }
6125    }
6126
6127    @Override
6128    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6129        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6130            throw new SecurityException("Instant applications don't have access to this method");
6131        }
6132        synchronized (mPackages) {
6133            mOnPermissionChangeListeners.removeListenerLocked(listener);
6134        }
6135    }
6136
6137    @Override
6138    public boolean isProtectedBroadcast(String actionName) {
6139        // allow instant applications
6140        synchronized (mProtectedBroadcasts) {
6141            if (mProtectedBroadcasts.contains(actionName)) {
6142                return true;
6143            } else if (actionName != null) {
6144                // TODO: remove these terrible hacks
6145                if (actionName.startsWith("android.net.netmon.lingerExpired")
6146                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
6147                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
6148                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
6149                    return true;
6150                }
6151            }
6152        }
6153        return false;
6154    }
6155
6156    @Override
6157    public int checkSignatures(String pkg1, String pkg2) {
6158        synchronized (mPackages) {
6159            final PackageParser.Package p1 = mPackages.get(pkg1);
6160            final PackageParser.Package p2 = mPackages.get(pkg2);
6161            if (p1 == null || p1.mExtras == null
6162                    || p2 == null || p2.mExtras == null) {
6163                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6164            }
6165            final int callingUid = Binder.getCallingUid();
6166            final int callingUserId = UserHandle.getUserId(callingUid);
6167            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
6168            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
6169            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
6170                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
6171                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6172            }
6173            return compareSignatures(p1.mSignatures, p2.mSignatures);
6174        }
6175    }
6176
6177    @Override
6178    public int checkUidSignatures(int uid1, int uid2) {
6179        final int callingUid = Binder.getCallingUid();
6180        final int callingUserId = UserHandle.getUserId(callingUid);
6181        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6182        // Map to base uids.
6183        uid1 = UserHandle.getAppId(uid1);
6184        uid2 = UserHandle.getAppId(uid2);
6185        // reader
6186        synchronized (mPackages) {
6187            Signature[] s1;
6188            Signature[] s2;
6189            Object obj = mSettings.getUserIdLPr(uid1);
6190            if (obj != null) {
6191                if (obj instanceof SharedUserSetting) {
6192                    if (isCallerInstantApp) {
6193                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6194                    }
6195                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
6196                } else if (obj instanceof PackageSetting) {
6197                    final PackageSetting ps = (PackageSetting) obj;
6198                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6199                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6200                    }
6201                    s1 = ps.signatures.mSignatures;
6202                } else {
6203                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6204                }
6205            } else {
6206                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6207            }
6208            obj = mSettings.getUserIdLPr(uid2);
6209            if (obj != null) {
6210                if (obj instanceof SharedUserSetting) {
6211                    if (isCallerInstantApp) {
6212                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6213                    }
6214                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
6215                } else if (obj instanceof PackageSetting) {
6216                    final PackageSetting ps = (PackageSetting) obj;
6217                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6218                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6219                    }
6220                    s2 = ps.signatures.mSignatures;
6221                } else {
6222                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6223                }
6224            } else {
6225                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6226            }
6227            return compareSignatures(s1, s2);
6228        }
6229    }
6230
6231    /**
6232     * This method should typically only be used when granting or revoking
6233     * permissions, since the app may immediately restart after this call.
6234     * <p>
6235     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
6236     * guard your work against the app being relaunched.
6237     */
6238    private void killUid(int appId, int userId, String reason) {
6239        final long identity = Binder.clearCallingIdentity();
6240        try {
6241            IActivityManager am = ActivityManager.getService();
6242            if (am != null) {
6243                try {
6244                    am.killUid(appId, userId, reason);
6245                } catch (RemoteException e) {
6246                    /* ignore - same process */
6247                }
6248            }
6249        } finally {
6250            Binder.restoreCallingIdentity(identity);
6251        }
6252    }
6253
6254    /**
6255     * Compares two sets of signatures. Returns:
6256     * <br />
6257     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
6258     * <br />
6259     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
6260     * <br />
6261     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
6262     * <br />
6263     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
6264     * <br />
6265     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
6266     */
6267    static int compareSignatures(Signature[] s1, Signature[] s2) {
6268        if (s1 == null) {
6269            return s2 == null
6270                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
6271                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
6272        }
6273
6274        if (s2 == null) {
6275            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
6276        }
6277
6278        if (s1.length != s2.length) {
6279            return PackageManager.SIGNATURE_NO_MATCH;
6280        }
6281
6282        // Since both signature sets are of size 1, we can compare without HashSets.
6283        if (s1.length == 1) {
6284            return s1[0].equals(s2[0]) ?
6285                    PackageManager.SIGNATURE_MATCH :
6286                    PackageManager.SIGNATURE_NO_MATCH;
6287        }
6288
6289        ArraySet<Signature> set1 = new ArraySet<Signature>();
6290        for (Signature sig : s1) {
6291            set1.add(sig);
6292        }
6293        ArraySet<Signature> set2 = new ArraySet<Signature>();
6294        for (Signature sig : s2) {
6295            set2.add(sig);
6296        }
6297        // Make sure s2 contains all signatures in s1.
6298        if (set1.equals(set2)) {
6299            return PackageManager.SIGNATURE_MATCH;
6300        }
6301        return PackageManager.SIGNATURE_NO_MATCH;
6302    }
6303
6304    /**
6305     * If the database version for this type of package (internal storage or
6306     * external storage) is less than the version where package signatures
6307     * were updated, return true.
6308     */
6309    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6310        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6311        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
6312    }
6313
6314    /**
6315     * Used for backward compatibility to make sure any packages with
6316     * certificate chains get upgraded to the new style. {@code existingSigs}
6317     * will be in the old format (since they were stored on disk from before the
6318     * system upgrade) and {@code scannedSigs} will be in the newer format.
6319     */
6320    private int compareSignaturesCompat(PackageSignatures existingSigs,
6321            PackageParser.Package scannedPkg) {
6322        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
6323            return PackageManager.SIGNATURE_NO_MATCH;
6324        }
6325
6326        ArraySet<Signature> existingSet = new ArraySet<Signature>();
6327        for (Signature sig : existingSigs.mSignatures) {
6328            existingSet.add(sig);
6329        }
6330        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
6331        for (Signature sig : scannedPkg.mSignatures) {
6332            try {
6333                Signature[] chainSignatures = sig.getChainSignatures();
6334                for (Signature chainSig : chainSignatures) {
6335                    scannedCompatSet.add(chainSig);
6336                }
6337            } catch (CertificateEncodingException e) {
6338                scannedCompatSet.add(sig);
6339            }
6340        }
6341        /*
6342         * Make sure the expanded scanned set contains all signatures in the
6343         * existing one.
6344         */
6345        if (scannedCompatSet.equals(existingSet)) {
6346            // Migrate the old signatures to the new scheme.
6347            existingSigs.assignSignatures(scannedPkg.mSignatures);
6348            // The new KeySets will be re-added later in the scanning process.
6349            synchronized (mPackages) {
6350                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
6351            }
6352            return PackageManager.SIGNATURE_MATCH;
6353        }
6354        return PackageManager.SIGNATURE_NO_MATCH;
6355    }
6356
6357    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6358        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6359        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6360    }
6361
6362    private int compareSignaturesRecover(PackageSignatures existingSigs,
6363            PackageParser.Package scannedPkg) {
6364        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
6365            return PackageManager.SIGNATURE_NO_MATCH;
6366        }
6367
6368        String msg = null;
6369        try {
6370            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
6371                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
6372                        + scannedPkg.packageName);
6373                return PackageManager.SIGNATURE_MATCH;
6374            }
6375        } catch (CertificateException e) {
6376            msg = e.getMessage();
6377        }
6378
6379        logCriticalInfo(Log.INFO,
6380                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
6381        return PackageManager.SIGNATURE_NO_MATCH;
6382    }
6383
6384    @Override
6385    public List<String> getAllPackages() {
6386        final int callingUid = Binder.getCallingUid();
6387        final int callingUserId = UserHandle.getUserId(callingUid);
6388        synchronized (mPackages) {
6389            if (canViewInstantApps(callingUid, callingUserId)) {
6390                return new ArrayList<String>(mPackages.keySet());
6391            }
6392            final String instantAppPkgName = getInstantAppPackageName(callingUid);
6393            final List<String> result = new ArrayList<>();
6394            if (instantAppPkgName != null) {
6395                // caller is an instant application; filter unexposed applications
6396                for (PackageParser.Package pkg : mPackages.values()) {
6397                    if (!pkg.visibleToInstantApps) {
6398                        continue;
6399                    }
6400                    result.add(pkg.packageName);
6401                }
6402            } else {
6403                // caller is a normal application; filter instant applications
6404                for (PackageParser.Package pkg : mPackages.values()) {
6405                    final PackageSetting ps =
6406                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6407                    if (ps != null
6408                            && ps.getInstantApp(callingUserId)
6409                            && !mInstantAppRegistry.isInstantAccessGranted(
6410                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6411                        continue;
6412                    }
6413                    result.add(pkg.packageName);
6414                }
6415            }
6416            return result;
6417        }
6418    }
6419
6420    @Override
6421    public String[] getPackagesForUid(int uid) {
6422        final int callingUid = Binder.getCallingUid();
6423        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6424        final int userId = UserHandle.getUserId(uid);
6425        uid = UserHandle.getAppId(uid);
6426        // reader
6427        synchronized (mPackages) {
6428            Object obj = mSettings.getUserIdLPr(uid);
6429            if (obj instanceof SharedUserSetting) {
6430                if (isCallerInstantApp) {
6431                    return null;
6432                }
6433                final SharedUserSetting sus = (SharedUserSetting) obj;
6434                final int N = sus.packages.size();
6435                String[] res = new String[N];
6436                final Iterator<PackageSetting> it = sus.packages.iterator();
6437                int i = 0;
6438                while (it.hasNext()) {
6439                    PackageSetting ps = it.next();
6440                    if (ps.getInstalled(userId)) {
6441                        res[i++] = ps.name;
6442                    } else {
6443                        res = ArrayUtils.removeElement(String.class, res, res[i]);
6444                    }
6445                }
6446                return res;
6447            } else if (obj instanceof PackageSetting) {
6448                final PackageSetting ps = (PackageSetting) obj;
6449                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6450                    return new String[]{ps.name};
6451                }
6452            }
6453        }
6454        return null;
6455    }
6456
6457    @Override
6458    public String getNameForUid(int uid) {
6459        final int callingUid = Binder.getCallingUid();
6460        if (getInstantAppPackageName(callingUid) != null) {
6461            return null;
6462        }
6463        synchronized (mPackages) {
6464            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6465            if (obj instanceof SharedUserSetting) {
6466                final SharedUserSetting sus = (SharedUserSetting) obj;
6467                return sus.name + ":" + sus.userId;
6468            } else if (obj instanceof PackageSetting) {
6469                final PackageSetting ps = (PackageSetting) obj;
6470                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6471                    return null;
6472                }
6473                return ps.name;
6474            }
6475            return null;
6476        }
6477    }
6478
6479    @Override
6480    public String[] getNamesForUids(int[] uids) {
6481        if (uids == null || uids.length == 0) {
6482            return null;
6483        }
6484        final int callingUid = Binder.getCallingUid();
6485        if (getInstantAppPackageName(callingUid) != null) {
6486            return null;
6487        }
6488        final String[] names = new String[uids.length];
6489        synchronized (mPackages) {
6490            for (int i = uids.length - 1; i >= 0; i--) {
6491                final int uid = uids[i];
6492                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6493                if (obj instanceof SharedUserSetting) {
6494                    final SharedUserSetting sus = (SharedUserSetting) obj;
6495                    names[i] = "shared:" + sus.name;
6496                } else if (obj instanceof PackageSetting) {
6497                    final PackageSetting ps = (PackageSetting) obj;
6498                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6499                        names[i] = null;
6500                    } else {
6501                        names[i] = ps.name;
6502                    }
6503                } else {
6504                    names[i] = null;
6505                }
6506            }
6507        }
6508        return names;
6509    }
6510
6511    @Override
6512    public int getUidForSharedUser(String sharedUserName) {
6513        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6514            return -1;
6515        }
6516        if (sharedUserName == null) {
6517            return -1;
6518        }
6519        // reader
6520        synchronized (mPackages) {
6521            SharedUserSetting suid;
6522            try {
6523                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6524                if (suid != null) {
6525                    return suid.userId;
6526                }
6527            } catch (PackageManagerException ignore) {
6528                // can't happen, but, still need to catch it
6529            }
6530            return -1;
6531        }
6532    }
6533
6534    @Override
6535    public int getFlagsForUid(int uid) {
6536        final int callingUid = Binder.getCallingUid();
6537        if (getInstantAppPackageName(callingUid) != null) {
6538            return 0;
6539        }
6540        synchronized (mPackages) {
6541            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6542            if (obj instanceof SharedUserSetting) {
6543                final SharedUserSetting sus = (SharedUserSetting) obj;
6544                return sus.pkgFlags;
6545            } else if (obj instanceof PackageSetting) {
6546                final PackageSetting ps = (PackageSetting) obj;
6547                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6548                    return 0;
6549                }
6550                return ps.pkgFlags;
6551            }
6552        }
6553        return 0;
6554    }
6555
6556    @Override
6557    public int getPrivateFlagsForUid(int uid) {
6558        final int callingUid = Binder.getCallingUid();
6559        if (getInstantAppPackageName(callingUid) != null) {
6560            return 0;
6561        }
6562        synchronized (mPackages) {
6563            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6564            if (obj instanceof SharedUserSetting) {
6565                final SharedUserSetting sus = (SharedUserSetting) obj;
6566                return sus.pkgPrivateFlags;
6567            } else if (obj instanceof PackageSetting) {
6568                final PackageSetting ps = (PackageSetting) obj;
6569                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6570                    return 0;
6571                }
6572                return ps.pkgPrivateFlags;
6573            }
6574        }
6575        return 0;
6576    }
6577
6578    @Override
6579    public boolean isUidPrivileged(int uid) {
6580        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6581            return false;
6582        }
6583        uid = UserHandle.getAppId(uid);
6584        // reader
6585        synchronized (mPackages) {
6586            Object obj = mSettings.getUserIdLPr(uid);
6587            if (obj instanceof SharedUserSetting) {
6588                final SharedUserSetting sus = (SharedUserSetting) obj;
6589                final Iterator<PackageSetting> it = sus.packages.iterator();
6590                while (it.hasNext()) {
6591                    if (it.next().isPrivileged()) {
6592                        return true;
6593                    }
6594                }
6595            } else if (obj instanceof PackageSetting) {
6596                final PackageSetting ps = (PackageSetting) obj;
6597                return ps.isPrivileged();
6598            }
6599        }
6600        return false;
6601    }
6602
6603    @Override
6604    public String[] getAppOpPermissionPackages(String permissionName) {
6605        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6606            return null;
6607        }
6608        synchronized (mPackages) {
6609            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6610            if (pkgs == null) {
6611                return null;
6612            }
6613            return pkgs.toArray(new String[pkgs.size()]);
6614        }
6615    }
6616
6617    @Override
6618    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6619            int flags, int userId) {
6620        return resolveIntentInternal(
6621                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6622    }
6623
6624    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6625            int flags, int userId, boolean resolveForStart) {
6626        try {
6627            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6628
6629            if (!sUserManager.exists(userId)) return null;
6630            final int callingUid = Binder.getCallingUid();
6631            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6632            enforceCrossUserPermission(callingUid, userId,
6633                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6634
6635            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6636            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6637                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
6638            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6639
6640            final ResolveInfo bestChoice =
6641                    chooseBestActivity(intent, resolvedType, flags, query, userId);
6642            return bestChoice;
6643        } finally {
6644            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6645        }
6646    }
6647
6648    @Override
6649    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6650        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6651            throw new SecurityException(
6652                    "findPersistentPreferredActivity can only be run by the system");
6653        }
6654        if (!sUserManager.exists(userId)) {
6655            return null;
6656        }
6657        final int callingUid = Binder.getCallingUid();
6658        intent = updateIntentForResolve(intent);
6659        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6660        final int flags = updateFlagsForResolve(
6661                0, userId, intent, callingUid, false /*includeInstantApps*/);
6662        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6663                userId);
6664        synchronized (mPackages) {
6665            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6666                    userId);
6667        }
6668    }
6669
6670    @Override
6671    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6672            IntentFilter filter, int match, ComponentName activity) {
6673        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6674            return;
6675        }
6676        final int userId = UserHandle.getCallingUserId();
6677        if (DEBUG_PREFERRED) {
6678            Log.v(TAG, "setLastChosenActivity intent=" + intent
6679                + " resolvedType=" + resolvedType
6680                + " flags=" + flags
6681                + " filter=" + filter
6682                + " match=" + match
6683                + " activity=" + activity);
6684            filter.dump(new PrintStreamPrinter(System.out), "    ");
6685        }
6686        intent.setComponent(null);
6687        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6688                userId);
6689        // Find any earlier preferred or last chosen entries and nuke them
6690        findPreferredActivity(intent, resolvedType,
6691                flags, query, 0, false, true, false, userId);
6692        // Add the new activity as the last chosen for this filter
6693        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6694                "Setting last chosen");
6695    }
6696
6697    @Override
6698    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6699        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6700            return null;
6701        }
6702        final int userId = UserHandle.getCallingUserId();
6703        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6704        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6705                userId);
6706        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6707                false, false, false, userId);
6708    }
6709
6710    /**
6711     * Returns whether or not instant apps have been disabled remotely.
6712     */
6713    private boolean isEphemeralDisabled() {
6714        return mEphemeralAppsDisabled;
6715    }
6716
6717    private boolean isInstantAppAllowed(
6718            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6719            boolean skipPackageCheck) {
6720        if (mInstantAppResolverConnection == null) {
6721            return false;
6722        }
6723        if (mInstantAppInstallerActivity == null) {
6724            return false;
6725        }
6726        if (intent.getComponent() != null) {
6727            return false;
6728        }
6729        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6730            return false;
6731        }
6732        if (!skipPackageCheck && intent.getPackage() != null) {
6733            return false;
6734        }
6735        final boolean isWebUri = hasWebURI(intent);
6736        if (!isWebUri || intent.getData().getHost() == null) {
6737            return false;
6738        }
6739        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6740        // Or if there's already an ephemeral app installed that handles the action
6741        synchronized (mPackages) {
6742            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6743            for (int n = 0; n < count; n++) {
6744                final ResolveInfo info = resolvedActivities.get(n);
6745                final String packageName = info.activityInfo.packageName;
6746                final PackageSetting ps = mSettings.mPackages.get(packageName);
6747                if (ps != null) {
6748                    // only check domain verification status if the app is not a browser
6749                    if (!info.handleAllWebDataURI) {
6750                        // Try to get the status from User settings first
6751                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6752                        final int status = (int) (packedStatus >> 32);
6753                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6754                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6755                            if (DEBUG_EPHEMERAL) {
6756                                Slog.v(TAG, "DENY instant app;"
6757                                    + " pkg: " + packageName + ", status: " + status);
6758                            }
6759                            return false;
6760                        }
6761                    }
6762                    if (ps.getInstantApp(userId)) {
6763                        if (DEBUG_EPHEMERAL) {
6764                            Slog.v(TAG, "DENY instant app installed;"
6765                                    + " pkg: " + packageName);
6766                        }
6767                        return false;
6768                    }
6769                }
6770            }
6771        }
6772        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6773        return true;
6774    }
6775
6776    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6777            Intent origIntent, String resolvedType, String callingPackage,
6778            Bundle verificationBundle, int userId) {
6779        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6780                new InstantAppRequest(responseObj, origIntent, resolvedType,
6781                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
6782        mHandler.sendMessage(msg);
6783    }
6784
6785    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6786            int flags, List<ResolveInfo> query, int userId) {
6787        if (query != null) {
6788            final int N = query.size();
6789            if (N == 1) {
6790                return query.get(0);
6791            } else if (N > 1) {
6792                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6793                // If there is more than one activity with the same priority,
6794                // then let the user decide between them.
6795                ResolveInfo r0 = query.get(0);
6796                ResolveInfo r1 = query.get(1);
6797                if (DEBUG_INTENT_MATCHING || debug) {
6798                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6799                            + r1.activityInfo.name + "=" + r1.priority);
6800                }
6801                // If the first activity has a higher priority, or a different
6802                // default, then it is always desirable to pick it.
6803                if (r0.priority != r1.priority
6804                        || r0.preferredOrder != r1.preferredOrder
6805                        || r0.isDefault != r1.isDefault) {
6806                    return query.get(0);
6807                }
6808                // If we have saved a preference for a preferred activity for
6809                // this Intent, use that.
6810                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6811                        flags, query, r0.priority, true, false, debug, userId);
6812                if (ri != null) {
6813                    return ri;
6814                }
6815                // If we have an ephemeral app, use it
6816                for (int i = 0; i < N; i++) {
6817                    ri = query.get(i);
6818                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6819                        final String packageName = ri.activityInfo.packageName;
6820                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6821                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6822                        final int status = (int)(packedStatus >> 32);
6823                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6824                            return ri;
6825                        }
6826                    }
6827                }
6828                ri = new ResolveInfo(mResolveInfo);
6829                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6830                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6831                // If all of the options come from the same package, show the application's
6832                // label and icon instead of the generic resolver's.
6833                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6834                // and then throw away the ResolveInfo itself, meaning that the caller loses
6835                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6836                // a fallback for this case; we only set the target package's resources on
6837                // the ResolveInfo, not the ActivityInfo.
6838                final String intentPackage = intent.getPackage();
6839                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6840                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6841                    ri.resolvePackageName = intentPackage;
6842                    if (userNeedsBadging(userId)) {
6843                        ri.noResourceId = true;
6844                    } else {
6845                        ri.icon = appi.icon;
6846                    }
6847                    ri.iconResourceId = appi.icon;
6848                    ri.labelRes = appi.labelRes;
6849                }
6850                ri.activityInfo.applicationInfo = new ApplicationInfo(
6851                        ri.activityInfo.applicationInfo);
6852                if (userId != 0) {
6853                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6854                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6855                }
6856                // Make sure that the resolver is displayable in car mode
6857                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6858                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6859                return ri;
6860            }
6861        }
6862        return null;
6863    }
6864
6865    /**
6866     * Return true if the given list is not empty and all of its contents have
6867     * an activityInfo with the given package name.
6868     */
6869    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6870        if (ArrayUtils.isEmpty(list)) {
6871            return false;
6872        }
6873        for (int i = 0, N = list.size(); i < N; i++) {
6874            final ResolveInfo ri = list.get(i);
6875            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6876            if (ai == null || !packageName.equals(ai.packageName)) {
6877                return false;
6878            }
6879        }
6880        return true;
6881    }
6882
6883    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6884            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6885        final int N = query.size();
6886        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6887                .get(userId);
6888        // Get the list of persistent preferred activities that handle the intent
6889        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6890        List<PersistentPreferredActivity> pprefs = ppir != null
6891                ? ppir.queryIntent(intent, resolvedType,
6892                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6893                        userId)
6894                : null;
6895        if (pprefs != null && pprefs.size() > 0) {
6896            final int M = pprefs.size();
6897            for (int i=0; i<M; i++) {
6898                final PersistentPreferredActivity ppa = pprefs.get(i);
6899                if (DEBUG_PREFERRED || debug) {
6900                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6901                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6902                            + "\n  component=" + ppa.mComponent);
6903                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6904                }
6905                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6906                        flags | MATCH_DISABLED_COMPONENTS, userId);
6907                if (DEBUG_PREFERRED || debug) {
6908                    Slog.v(TAG, "Found persistent preferred activity:");
6909                    if (ai != null) {
6910                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6911                    } else {
6912                        Slog.v(TAG, "  null");
6913                    }
6914                }
6915                if (ai == null) {
6916                    // This previously registered persistent preferred activity
6917                    // component is no longer known. Ignore it and do NOT remove it.
6918                    continue;
6919                }
6920                for (int j=0; j<N; j++) {
6921                    final ResolveInfo ri = query.get(j);
6922                    if (!ri.activityInfo.applicationInfo.packageName
6923                            .equals(ai.applicationInfo.packageName)) {
6924                        continue;
6925                    }
6926                    if (!ri.activityInfo.name.equals(ai.name)) {
6927                        continue;
6928                    }
6929                    //  Found a persistent preference that can handle the intent.
6930                    if (DEBUG_PREFERRED || debug) {
6931                        Slog.v(TAG, "Returning persistent preferred activity: " +
6932                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6933                    }
6934                    return ri;
6935                }
6936            }
6937        }
6938        return null;
6939    }
6940
6941    // TODO: handle preferred activities missing while user has amnesia
6942    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6943            List<ResolveInfo> query, int priority, boolean always,
6944            boolean removeMatches, boolean debug, int userId) {
6945        if (!sUserManager.exists(userId)) return null;
6946        final int callingUid = Binder.getCallingUid();
6947        flags = updateFlagsForResolve(
6948                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6949        intent = updateIntentForResolve(intent);
6950        // writer
6951        synchronized (mPackages) {
6952            // Try to find a matching persistent preferred activity.
6953            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6954                    debug, userId);
6955
6956            // If a persistent preferred activity matched, use it.
6957            if (pri != null) {
6958                return pri;
6959            }
6960
6961            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6962            // Get the list of preferred activities that handle the intent
6963            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6964            List<PreferredActivity> prefs = pir != null
6965                    ? pir.queryIntent(intent, resolvedType,
6966                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6967                            userId)
6968                    : null;
6969            if (prefs != null && prefs.size() > 0) {
6970                boolean changed = false;
6971                try {
6972                    // First figure out how good the original match set is.
6973                    // We will only allow preferred activities that came
6974                    // from the same match quality.
6975                    int match = 0;
6976
6977                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6978
6979                    final int N = query.size();
6980                    for (int j=0; j<N; j++) {
6981                        final ResolveInfo ri = query.get(j);
6982                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6983                                + ": 0x" + Integer.toHexString(match));
6984                        if (ri.match > match) {
6985                            match = ri.match;
6986                        }
6987                    }
6988
6989                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6990                            + Integer.toHexString(match));
6991
6992                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6993                    final int M = prefs.size();
6994                    for (int i=0; i<M; i++) {
6995                        final PreferredActivity pa = prefs.get(i);
6996                        if (DEBUG_PREFERRED || debug) {
6997                            Slog.v(TAG, "Checking PreferredActivity ds="
6998                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6999                                    + "\n  component=" + pa.mPref.mComponent);
7000                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
7001                        }
7002                        if (pa.mPref.mMatch != match) {
7003                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
7004                                    + Integer.toHexString(pa.mPref.mMatch));
7005                            continue;
7006                        }
7007                        // If it's not an "always" type preferred activity and that's what we're
7008                        // looking for, skip it.
7009                        if (always && !pa.mPref.mAlways) {
7010                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
7011                            continue;
7012                        }
7013                        final ActivityInfo ai = getActivityInfo(
7014                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
7015                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
7016                                userId);
7017                        if (DEBUG_PREFERRED || debug) {
7018                            Slog.v(TAG, "Found preferred activity:");
7019                            if (ai != null) {
7020                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
7021                            } else {
7022                                Slog.v(TAG, "  null");
7023                            }
7024                        }
7025                        if (ai == null) {
7026                            // This previously registered preferred activity
7027                            // component is no longer known.  Most likely an update
7028                            // to the app was installed and in the new version this
7029                            // component no longer exists.  Clean it up by removing
7030                            // it from the preferred activities list, and skip it.
7031                            Slog.w(TAG, "Removing dangling preferred activity: "
7032                                    + pa.mPref.mComponent);
7033                            pir.removeFilter(pa);
7034                            changed = true;
7035                            continue;
7036                        }
7037                        for (int j=0; j<N; j++) {
7038                            final ResolveInfo ri = query.get(j);
7039                            if (!ri.activityInfo.applicationInfo.packageName
7040                                    .equals(ai.applicationInfo.packageName)) {
7041                                continue;
7042                            }
7043                            if (!ri.activityInfo.name.equals(ai.name)) {
7044                                continue;
7045                            }
7046
7047                            if (removeMatches) {
7048                                pir.removeFilter(pa);
7049                                changed = true;
7050                                if (DEBUG_PREFERRED) {
7051                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
7052                                }
7053                                break;
7054                            }
7055
7056                            // Okay we found a previously set preferred or last chosen app.
7057                            // If the result set is different from when this
7058                            // was created, and is not a subset of the preferred set, we need to
7059                            // clear it and re-ask the user their preference, if we're looking for
7060                            // an "always" type entry.
7061                            if (always && !pa.mPref.sameSet(query)) {
7062                                if (pa.mPref.isSuperset(query)) {
7063                                    // some components of the set are no longer present in
7064                                    // the query, but the preferred activity can still be reused
7065                                    if (DEBUG_PREFERRED) {
7066                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
7067                                                + " still valid as only non-preferred components"
7068                                                + " were removed for " + intent + " type "
7069                                                + resolvedType);
7070                                    }
7071                                    // remove obsolete components and re-add the up-to-date filter
7072                                    PreferredActivity freshPa = new PreferredActivity(pa,
7073                                            pa.mPref.mMatch,
7074                                            pa.mPref.discardObsoleteComponents(query),
7075                                            pa.mPref.mComponent,
7076                                            pa.mPref.mAlways);
7077                                    pir.removeFilter(pa);
7078                                    pir.addFilter(freshPa);
7079                                    changed = true;
7080                                } else {
7081                                    Slog.i(TAG,
7082                                            "Result set changed, dropping preferred activity for "
7083                                                    + intent + " type " + resolvedType);
7084                                    if (DEBUG_PREFERRED) {
7085                                        Slog.v(TAG, "Removing preferred activity since set changed "
7086                                                + pa.mPref.mComponent);
7087                                    }
7088                                    pir.removeFilter(pa);
7089                                    // Re-add the filter as a "last chosen" entry (!always)
7090                                    PreferredActivity lastChosen = new PreferredActivity(
7091                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
7092                                    pir.addFilter(lastChosen);
7093                                    changed = true;
7094                                    return null;
7095                                }
7096                            }
7097
7098                            // Yay! Either the set matched or we're looking for the last chosen
7099                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
7100                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
7101                            return ri;
7102                        }
7103                    }
7104                } finally {
7105                    if (changed) {
7106                        if (DEBUG_PREFERRED) {
7107                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
7108                        }
7109                        scheduleWritePackageRestrictionsLocked(userId);
7110                    }
7111                }
7112            }
7113        }
7114        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
7115        return null;
7116    }
7117
7118    /*
7119     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
7120     */
7121    @Override
7122    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
7123            int targetUserId) {
7124        mContext.enforceCallingOrSelfPermission(
7125                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
7126        List<CrossProfileIntentFilter> matches =
7127                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
7128        if (matches != null) {
7129            int size = matches.size();
7130            for (int i = 0; i < size; i++) {
7131                if (matches.get(i).getTargetUserId() == targetUserId) return true;
7132            }
7133        }
7134        if (hasWebURI(intent)) {
7135            // cross-profile app linking works only towards the parent.
7136            final int callingUid = Binder.getCallingUid();
7137            final UserInfo parent = getProfileParent(sourceUserId);
7138            synchronized(mPackages) {
7139                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
7140                        false /*includeInstantApps*/);
7141                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
7142                        intent, resolvedType, flags, sourceUserId, parent.id);
7143                return xpDomainInfo != null;
7144            }
7145        }
7146        return false;
7147    }
7148
7149    private UserInfo getProfileParent(int userId) {
7150        final long identity = Binder.clearCallingIdentity();
7151        try {
7152            return sUserManager.getProfileParent(userId);
7153        } finally {
7154            Binder.restoreCallingIdentity(identity);
7155        }
7156    }
7157
7158    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
7159            String resolvedType, int userId) {
7160        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
7161        if (resolver != null) {
7162            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
7163        }
7164        return null;
7165    }
7166
7167    @Override
7168    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
7169            String resolvedType, int flags, int userId) {
7170        try {
7171            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
7172
7173            return new ParceledListSlice<>(
7174                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
7175        } finally {
7176            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7177        }
7178    }
7179
7180    /**
7181     * Returns the package name of the calling Uid if it's an instant app. If it isn't
7182     * instant, returns {@code null}.
7183     */
7184    private String getInstantAppPackageName(int callingUid) {
7185        synchronized (mPackages) {
7186            // If the caller is an isolated app use the owner's uid for the lookup.
7187            if (Process.isIsolated(callingUid)) {
7188                callingUid = mIsolatedOwners.get(callingUid);
7189            }
7190            final int appId = UserHandle.getAppId(callingUid);
7191            final Object obj = mSettings.getUserIdLPr(appId);
7192            if (obj instanceof PackageSetting) {
7193                final PackageSetting ps = (PackageSetting) obj;
7194                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
7195                return isInstantApp ? ps.pkg.packageName : null;
7196            }
7197        }
7198        return null;
7199    }
7200
7201    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7202            String resolvedType, int flags, int userId) {
7203        return queryIntentActivitiesInternal(
7204                intent, resolvedType, flags, Binder.getCallingUid(), userId,
7205                false /*resolveForStart*/, true /*allowDynamicSplits*/);
7206    }
7207
7208    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7209            String resolvedType, int flags, int filterCallingUid, int userId,
7210            boolean resolveForStart, boolean allowDynamicSplits) {
7211        if (!sUserManager.exists(userId)) return Collections.emptyList();
7212        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
7213        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7214                false /* requireFullPermission */, false /* checkShell */,
7215                "query intent activities");
7216        final String pkgName = intent.getPackage();
7217        ComponentName comp = intent.getComponent();
7218        if (comp == null) {
7219            if (intent.getSelector() != null) {
7220                intent = intent.getSelector();
7221                comp = intent.getComponent();
7222            }
7223        }
7224
7225        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
7226                comp != null || pkgName != null /*onlyExposedExplicitly*/);
7227        if (comp != null) {
7228            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7229            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
7230            if (ai != null) {
7231                // When specifying an explicit component, we prevent the activity from being
7232                // used when either 1) the calling package is normal and the activity is within
7233                // an ephemeral application or 2) the calling package is ephemeral and the
7234                // activity is not visible to ephemeral applications.
7235                final boolean matchInstantApp =
7236                        (flags & PackageManager.MATCH_INSTANT) != 0;
7237                final boolean matchVisibleToInstantAppOnly =
7238                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7239                final boolean matchExplicitlyVisibleOnly =
7240                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7241                final boolean isCallerInstantApp =
7242                        instantAppPkgName != null;
7243                final boolean isTargetSameInstantApp =
7244                        comp.getPackageName().equals(instantAppPkgName);
7245                final boolean isTargetInstantApp =
7246                        (ai.applicationInfo.privateFlags
7247                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7248                final boolean isTargetVisibleToInstantApp =
7249                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7250                final boolean isTargetExplicitlyVisibleToInstantApp =
7251                        isTargetVisibleToInstantApp
7252                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7253                final boolean isTargetHiddenFromInstantApp =
7254                        !isTargetVisibleToInstantApp
7255                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7256                final boolean blockResolution =
7257                        !isTargetSameInstantApp
7258                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7259                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7260                                        && isTargetHiddenFromInstantApp));
7261                if (!blockResolution) {
7262                    final ResolveInfo ri = new ResolveInfo();
7263                    ri.activityInfo = ai;
7264                    list.add(ri);
7265                }
7266            }
7267            return applyPostResolutionFilter(
7268                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
7269        }
7270
7271        // reader
7272        boolean sortResult = false;
7273        boolean addEphemeral = false;
7274        List<ResolveInfo> result;
7275        final boolean ephemeralDisabled = isEphemeralDisabled();
7276        synchronized (mPackages) {
7277            if (pkgName == null) {
7278                List<CrossProfileIntentFilter> matchingFilters =
7279                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
7280                // Check for results that need to skip the current profile.
7281                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
7282                        resolvedType, flags, userId);
7283                if (xpResolveInfo != null) {
7284                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
7285                    xpResult.add(xpResolveInfo);
7286                    return applyPostResolutionFilter(
7287                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
7288                            allowDynamicSplits, filterCallingUid, userId);
7289                }
7290
7291                // Check for results in the current profile.
7292                result = filterIfNotSystemUser(mActivities.queryIntent(
7293                        intent, resolvedType, flags, userId), userId);
7294                addEphemeral = !ephemeralDisabled
7295                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
7296                // Check for cross profile results.
7297                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
7298                xpResolveInfo = queryCrossProfileIntents(
7299                        matchingFilters, intent, resolvedType, flags, userId,
7300                        hasNonNegativePriorityResult);
7301                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
7302                    boolean isVisibleToUser = filterIfNotSystemUser(
7303                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
7304                    if (isVisibleToUser) {
7305                        result.add(xpResolveInfo);
7306                        sortResult = true;
7307                    }
7308                }
7309                if (hasWebURI(intent)) {
7310                    CrossProfileDomainInfo xpDomainInfo = null;
7311                    final UserInfo parent = getProfileParent(userId);
7312                    if (parent != null) {
7313                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
7314                                flags, userId, parent.id);
7315                    }
7316                    if (xpDomainInfo != null) {
7317                        if (xpResolveInfo != null) {
7318                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
7319                            // in the result.
7320                            result.remove(xpResolveInfo);
7321                        }
7322                        if (result.size() == 0 && !addEphemeral) {
7323                            // No result in current profile, but found candidate in parent user.
7324                            // And we are not going to add emphemeral app, so we can return the
7325                            // result straight away.
7326                            result.add(xpDomainInfo.resolveInfo);
7327                            return applyPostResolutionFilter(result, instantAppPkgName,
7328                                    allowDynamicSplits, filterCallingUid, userId);
7329                        }
7330                    } else if (result.size() <= 1 && !addEphemeral) {
7331                        // No result in parent user and <= 1 result in current profile, and we
7332                        // are not going to add emphemeral app, so we can return the result without
7333                        // further processing.
7334                        return applyPostResolutionFilter(result, instantAppPkgName,
7335                                allowDynamicSplits, filterCallingUid, userId);
7336                    }
7337                    // We have more than one candidate (combining results from current and parent
7338                    // profile), so we need filtering and sorting.
7339                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
7340                            intent, flags, result, xpDomainInfo, userId);
7341                    sortResult = true;
7342                }
7343            } else {
7344                final PackageParser.Package pkg = mPackages.get(pkgName);
7345                result = null;
7346                if (pkg != null) {
7347                    result = filterIfNotSystemUser(
7348                            mActivities.queryIntentForPackage(
7349                                    intent, resolvedType, flags, pkg.activities, userId),
7350                            userId);
7351                }
7352                if (result == null || result.size() == 0) {
7353                    // the caller wants to resolve for a particular package; however, there
7354                    // were no installed results, so, try to find an ephemeral result
7355                    addEphemeral = !ephemeralDisabled
7356                            && isInstantAppAllowed(
7357                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
7358                    if (result == null) {
7359                        result = new ArrayList<>();
7360                    }
7361                }
7362            }
7363        }
7364        if (addEphemeral) {
7365            result = maybeAddInstantAppInstaller(
7366                    result, intent, resolvedType, flags, userId, resolveForStart);
7367        }
7368        if (sortResult) {
7369            Collections.sort(result, mResolvePrioritySorter);
7370        }
7371        return applyPostResolutionFilter(
7372                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
7373    }
7374
7375    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
7376            String resolvedType, int flags, int userId, boolean resolveForStart) {
7377        // first, check to see if we've got an instant app already installed
7378        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
7379        ResolveInfo localInstantApp = null;
7380        boolean blockResolution = false;
7381        if (!alreadyResolvedLocally) {
7382            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
7383                    flags
7384                        | PackageManager.GET_RESOLVED_FILTER
7385                        | PackageManager.MATCH_INSTANT
7386                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
7387                    userId);
7388            for (int i = instantApps.size() - 1; i >= 0; --i) {
7389                final ResolveInfo info = instantApps.get(i);
7390                final String packageName = info.activityInfo.packageName;
7391                final PackageSetting ps = mSettings.mPackages.get(packageName);
7392                if (ps.getInstantApp(userId)) {
7393                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7394                    final int status = (int)(packedStatus >> 32);
7395                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7396                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7397                        // there's a local instant application installed, but, the user has
7398                        // chosen to never use it; skip resolution and don't acknowledge
7399                        // an instant application is even available
7400                        if (DEBUG_EPHEMERAL) {
7401                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7402                        }
7403                        blockResolution = true;
7404                        break;
7405                    } else {
7406                        // we have a locally installed instant application; skip resolution
7407                        // but acknowledge there's an instant application available
7408                        if (DEBUG_EPHEMERAL) {
7409                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7410                        }
7411                        localInstantApp = info;
7412                        break;
7413                    }
7414                }
7415            }
7416        }
7417        // no app installed, let's see if one's available
7418        AuxiliaryResolveInfo auxiliaryResponse = null;
7419        if (!blockResolution) {
7420            if (localInstantApp == null) {
7421                // we don't have an instant app locally, resolve externally
7422                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7423                final InstantAppRequest requestObject = new InstantAppRequest(
7424                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
7425                        null /*callingPackage*/, userId, null /*verificationBundle*/,
7426                        resolveForStart);
7427                auxiliaryResponse =
7428                        InstantAppResolver.doInstantAppResolutionPhaseOne(
7429                                mContext, mInstantAppResolverConnection, requestObject);
7430                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7431            } else {
7432                // we have an instant application locally, but, we can't admit that since
7433                // callers shouldn't be able to determine prior browsing. create a dummy
7434                // auxiliary response so the downstream code behaves as if there's an
7435                // instant application available externally. when it comes time to start
7436                // the instant application, we'll do the right thing.
7437                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7438                auxiliaryResponse = new AuxiliaryResolveInfo(
7439                        ai.packageName, null /*splitName*/, null /*failureActivity*/,
7440                        ai.versionCode, null /*failureIntent*/);
7441            }
7442        }
7443        if (auxiliaryResponse != null) {
7444            if (DEBUG_EPHEMERAL) {
7445                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7446            }
7447            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7448            final PackageSetting ps =
7449                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7450            if (ps != null) {
7451                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7452                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7453                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
7454                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7455                // make sure this resolver is the default
7456                ephemeralInstaller.isDefault = true;
7457                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7458                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7459                // add a non-generic filter
7460                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
7461                ephemeralInstaller.filter.addDataPath(
7462                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7463                ephemeralInstaller.isInstantAppAvailable = true;
7464                result.add(ephemeralInstaller);
7465            }
7466        }
7467        return result;
7468    }
7469
7470    private static class CrossProfileDomainInfo {
7471        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7472        ResolveInfo resolveInfo;
7473        /* Best domain verification status of the activities found in the other profile */
7474        int bestDomainVerificationStatus;
7475    }
7476
7477    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7478            String resolvedType, int flags, int sourceUserId, int parentUserId) {
7479        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7480                sourceUserId)) {
7481            return null;
7482        }
7483        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7484                resolvedType, flags, parentUserId);
7485
7486        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7487            return null;
7488        }
7489        CrossProfileDomainInfo result = null;
7490        int size = resultTargetUser.size();
7491        for (int i = 0; i < size; i++) {
7492            ResolveInfo riTargetUser = resultTargetUser.get(i);
7493            // Intent filter verification is only for filters that specify a host. So don't return
7494            // those that handle all web uris.
7495            if (riTargetUser.handleAllWebDataURI) {
7496                continue;
7497            }
7498            String packageName = riTargetUser.activityInfo.packageName;
7499            PackageSetting ps = mSettings.mPackages.get(packageName);
7500            if (ps == null) {
7501                continue;
7502            }
7503            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7504            int status = (int)(verificationState >> 32);
7505            if (result == null) {
7506                result = new CrossProfileDomainInfo();
7507                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7508                        sourceUserId, parentUserId);
7509                result.bestDomainVerificationStatus = status;
7510            } else {
7511                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7512                        result.bestDomainVerificationStatus);
7513            }
7514        }
7515        // Don't consider matches with status NEVER across profiles.
7516        if (result != null && result.bestDomainVerificationStatus
7517                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7518            return null;
7519        }
7520        return result;
7521    }
7522
7523    /**
7524     * Verification statuses are ordered from the worse to the best, except for
7525     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7526     */
7527    private int bestDomainVerificationStatus(int status1, int status2) {
7528        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7529            return status2;
7530        }
7531        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7532            return status1;
7533        }
7534        return (int) MathUtils.max(status1, status2);
7535    }
7536
7537    private boolean isUserEnabled(int userId) {
7538        long callingId = Binder.clearCallingIdentity();
7539        try {
7540            UserInfo userInfo = sUserManager.getUserInfo(userId);
7541            return userInfo != null && userInfo.isEnabled();
7542        } finally {
7543            Binder.restoreCallingIdentity(callingId);
7544        }
7545    }
7546
7547    /**
7548     * Filter out activities with systemUserOnly flag set, when current user is not System.
7549     *
7550     * @return filtered list
7551     */
7552    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7553        if (userId == UserHandle.USER_SYSTEM) {
7554            return resolveInfos;
7555        }
7556        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7557            ResolveInfo info = resolveInfos.get(i);
7558            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7559                resolveInfos.remove(i);
7560            }
7561        }
7562        return resolveInfos;
7563    }
7564
7565    /**
7566     * Filters out ephemeral activities.
7567     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7568     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7569     *
7570     * @param resolveInfos The pre-filtered list of resolved activities
7571     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7572     *          is performed.
7573     * @return A filtered list of resolved activities.
7574     */
7575    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7576            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) {
7577        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7578            final ResolveInfo info = resolveInfos.get(i);
7579            // allow activities that are defined in the provided package
7580            if (allowDynamicSplits
7581                    && info.activityInfo.splitName != null
7582                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7583                            info.activityInfo.splitName)) {
7584                // requested activity is defined in a split that hasn't been installed yet.
7585                // add the installer to the resolve list
7586                if (DEBUG_INSTALL) {
7587                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
7588                }
7589                final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7590                final ComponentName installFailureActivity = findInstallFailureActivity(
7591                        info.activityInfo.packageName,  filterCallingUid, userId);
7592                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7593                        info.activityInfo.packageName, info.activityInfo.splitName,
7594                        installFailureActivity,
7595                        info.activityInfo.applicationInfo.versionCode,
7596                        null /*failureIntent*/);
7597                // make sure this resolver is the default
7598                installerInfo.isDefault = true;
7599                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7600                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7601                // add a non-generic filter
7602                installerInfo.filter = new IntentFilter();
7603                // load resources from the correct package
7604                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7605                resolveInfos.set(i, installerInfo);
7606                continue;
7607            }
7608            // caller is a full app, don't need to apply any other filtering
7609            if (ephemeralPkgName == null) {
7610                continue;
7611            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
7612                // caller is same app; don't need to apply any other filtering
7613                continue;
7614            }
7615            // allow activities that have been explicitly exposed to ephemeral apps
7616            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7617            if (!isEphemeralApp
7618                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7619                continue;
7620            }
7621            resolveInfos.remove(i);
7622        }
7623        return resolveInfos;
7624    }
7625
7626    /**
7627     * Returns the activity component that can handle install failures.
7628     * <p>By default, the instant application installer handles failures. However, an
7629     * application may want to handle failures on its own. Applications do this by
7630     * creating an activity with an intent filter that handles the action
7631     * {@link Intent#ACTION_INSTALL_FAILURE}.
7632     */
7633    private @Nullable ComponentName findInstallFailureActivity(
7634            String packageName, int filterCallingUid, int userId) {
7635        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
7636        failureActivityIntent.setPackage(packageName);
7637        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
7638        final List<ResolveInfo> result = queryIntentActivitiesInternal(
7639                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
7640                false /*resolveForStart*/, false /*allowDynamicSplits*/);
7641        final int NR = result.size();
7642        if (NR > 0) {
7643            for (int i = 0; i < NR; i++) {
7644                final ResolveInfo info = result.get(i);
7645                if (info.activityInfo.splitName != null) {
7646                    continue;
7647                }
7648                return new ComponentName(packageName, info.activityInfo.name);
7649            }
7650        }
7651        return null;
7652    }
7653
7654    /**
7655     * @param resolveInfos list of resolve infos in descending priority order
7656     * @return if the list contains a resolve info with non-negative priority
7657     */
7658    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7659        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7660    }
7661
7662    private static boolean hasWebURI(Intent intent) {
7663        if (intent.getData() == null) {
7664            return false;
7665        }
7666        final String scheme = intent.getScheme();
7667        if (TextUtils.isEmpty(scheme)) {
7668            return false;
7669        }
7670        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7671    }
7672
7673    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7674            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7675            int userId) {
7676        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7677
7678        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7679            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7680                    candidates.size());
7681        }
7682
7683        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7684        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7685        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7686        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7687        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7688        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7689
7690        synchronized (mPackages) {
7691            final int count = candidates.size();
7692            // First, try to use linked apps. Partition the candidates into four lists:
7693            // one for the final results, one for the "do not use ever", one for "undefined status"
7694            // and finally one for "browser app type".
7695            for (int n=0; n<count; n++) {
7696                ResolveInfo info = candidates.get(n);
7697                String packageName = info.activityInfo.packageName;
7698                PackageSetting ps = mSettings.mPackages.get(packageName);
7699                if (ps != null) {
7700                    // Add to the special match all list (Browser use case)
7701                    if (info.handleAllWebDataURI) {
7702                        matchAllList.add(info);
7703                        continue;
7704                    }
7705                    // Try to get the status from User settings first
7706                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7707                    int status = (int)(packedStatus >> 32);
7708                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7709                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7710                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7711                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7712                                    + " : linkgen=" + linkGeneration);
7713                        }
7714                        // Use link-enabled generation as preferredOrder, i.e.
7715                        // prefer newly-enabled over earlier-enabled.
7716                        info.preferredOrder = linkGeneration;
7717                        alwaysList.add(info);
7718                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7719                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7720                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7721                        }
7722                        neverList.add(info);
7723                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7724                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7725                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7726                        }
7727                        alwaysAskList.add(info);
7728                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7729                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7730                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7731                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7732                        }
7733                        undefinedList.add(info);
7734                    }
7735                }
7736            }
7737
7738            // We'll want to include browser possibilities in a few cases
7739            boolean includeBrowser = false;
7740
7741            // First try to add the "always" resolution(s) for the current user, if any
7742            if (alwaysList.size() > 0) {
7743                result.addAll(alwaysList);
7744            } else {
7745                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7746                result.addAll(undefinedList);
7747                // Maybe add one for the other profile.
7748                if (xpDomainInfo != null && (
7749                        xpDomainInfo.bestDomainVerificationStatus
7750                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7751                    result.add(xpDomainInfo.resolveInfo);
7752                }
7753                includeBrowser = true;
7754            }
7755
7756            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7757            // If there were 'always' entries their preferred order has been set, so we also
7758            // back that off to make the alternatives equivalent
7759            if (alwaysAskList.size() > 0) {
7760                for (ResolveInfo i : result) {
7761                    i.preferredOrder = 0;
7762                }
7763                result.addAll(alwaysAskList);
7764                includeBrowser = true;
7765            }
7766
7767            if (includeBrowser) {
7768                // Also add browsers (all of them or only the default one)
7769                if (DEBUG_DOMAIN_VERIFICATION) {
7770                    Slog.v(TAG, "   ...including browsers in candidate set");
7771                }
7772                if ((matchFlags & MATCH_ALL) != 0) {
7773                    result.addAll(matchAllList);
7774                } else {
7775                    // Browser/generic handling case.  If there's a default browser, go straight
7776                    // to that (but only if there is no other higher-priority match).
7777                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7778                    int maxMatchPrio = 0;
7779                    ResolveInfo defaultBrowserMatch = null;
7780                    final int numCandidates = matchAllList.size();
7781                    for (int n = 0; n < numCandidates; n++) {
7782                        ResolveInfo info = matchAllList.get(n);
7783                        // track the highest overall match priority...
7784                        if (info.priority > maxMatchPrio) {
7785                            maxMatchPrio = info.priority;
7786                        }
7787                        // ...and the highest-priority default browser match
7788                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7789                            if (defaultBrowserMatch == null
7790                                    || (defaultBrowserMatch.priority < info.priority)) {
7791                                if (debug) {
7792                                    Slog.v(TAG, "Considering default browser match " + info);
7793                                }
7794                                defaultBrowserMatch = info;
7795                            }
7796                        }
7797                    }
7798                    if (defaultBrowserMatch != null
7799                            && defaultBrowserMatch.priority >= maxMatchPrio
7800                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7801                    {
7802                        if (debug) {
7803                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7804                        }
7805                        result.add(defaultBrowserMatch);
7806                    } else {
7807                        result.addAll(matchAllList);
7808                    }
7809                }
7810
7811                // If there is nothing selected, add all candidates and remove the ones that the user
7812                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7813                if (result.size() == 0) {
7814                    result.addAll(candidates);
7815                    result.removeAll(neverList);
7816                }
7817            }
7818        }
7819        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7820            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7821                    result.size());
7822            for (ResolveInfo info : result) {
7823                Slog.v(TAG, "  + " + info.activityInfo);
7824            }
7825        }
7826        return result;
7827    }
7828
7829    // Returns a packed value as a long:
7830    //
7831    // high 'int'-sized word: link status: undefined/ask/never/always.
7832    // low 'int'-sized word: relative priority among 'always' results.
7833    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7834        long result = ps.getDomainVerificationStatusForUser(userId);
7835        // if none available, get the master status
7836        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7837            if (ps.getIntentFilterVerificationInfo() != null) {
7838                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7839            }
7840        }
7841        return result;
7842    }
7843
7844    private ResolveInfo querySkipCurrentProfileIntents(
7845            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7846            int flags, int sourceUserId) {
7847        if (matchingFilters != null) {
7848            int size = matchingFilters.size();
7849            for (int i = 0; i < size; i ++) {
7850                CrossProfileIntentFilter filter = matchingFilters.get(i);
7851                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7852                    // Checking if there are activities in the target user that can handle the
7853                    // intent.
7854                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7855                            resolvedType, flags, sourceUserId);
7856                    if (resolveInfo != null) {
7857                        return resolveInfo;
7858                    }
7859                }
7860            }
7861        }
7862        return null;
7863    }
7864
7865    // Return matching ResolveInfo in target user if any.
7866    private ResolveInfo queryCrossProfileIntents(
7867            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7868            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7869        if (matchingFilters != null) {
7870            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7871            // match the same intent. For performance reasons, it is better not to
7872            // run queryIntent twice for the same userId
7873            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7874            int size = matchingFilters.size();
7875            for (int i = 0; i < size; i++) {
7876                CrossProfileIntentFilter filter = matchingFilters.get(i);
7877                int targetUserId = filter.getTargetUserId();
7878                boolean skipCurrentProfile =
7879                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7880                boolean skipCurrentProfileIfNoMatchFound =
7881                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7882                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7883                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7884                    // Checking if there are activities in the target user that can handle the
7885                    // intent.
7886                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7887                            resolvedType, flags, sourceUserId);
7888                    if (resolveInfo != null) return resolveInfo;
7889                    alreadyTriedUserIds.put(targetUserId, true);
7890                }
7891            }
7892        }
7893        return null;
7894    }
7895
7896    /**
7897     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7898     * will forward the intent to the filter's target user.
7899     * Otherwise, returns null.
7900     */
7901    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7902            String resolvedType, int flags, int sourceUserId) {
7903        int targetUserId = filter.getTargetUserId();
7904        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7905                resolvedType, flags, targetUserId);
7906        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7907            // If all the matches in the target profile are suspended, return null.
7908            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7909                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7910                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7911                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7912                            targetUserId);
7913                }
7914            }
7915        }
7916        return null;
7917    }
7918
7919    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7920            int sourceUserId, int targetUserId) {
7921        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7922        long ident = Binder.clearCallingIdentity();
7923        boolean targetIsProfile;
7924        try {
7925            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7926        } finally {
7927            Binder.restoreCallingIdentity(ident);
7928        }
7929        String className;
7930        if (targetIsProfile) {
7931            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7932        } else {
7933            className = FORWARD_INTENT_TO_PARENT;
7934        }
7935        ComponentName forwardingActivityComponentName = new ComponentName(
7936                mAndroidApplication.packageName, className);
7937        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7938                sourceUserId);
7939        if (!targetIsProfile) {
7940            forwardingActivityInfo.showUserIcon = targetUserId;
7941            forwardingResolveInfo.noResourceId = true;
7942        }
7943        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7944        forwardingResolveInfo.priority = 0;
7945        forwardingResolveInfo.preferredOrder = 0;
7946        forwardingResolveInfo.match = 0;
7947        forwardingResolveInfo.isDefault = true;
7948        forwardingResolveInfo.filter = filter;
7949        forwardingResolveInfo.targetUserId = targetUserId;
7950        return forwardingResolveInfo;
7951    }
7952
7953    @Override
7954    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7955            Intent[] specifics, String[] specificTypes, Intent intent,
7956            String resolvedType, int flags, int userId) {
7957        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7958                specificTypes, intent, resolvedType, flags, userId));
7959    }
7960
7961    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7962            Intent[] specifics, String[] specificTypes, Intent intent,
7963            String resolvedType, int flags, int userId) {
7964        if (!sUserManager.exists(userId)) return Collections.emptyList();
7965        final int callingUid = Binder.getCallingUid();
7966        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7967                false /*includeInstantApps*/);
7968        enforceCrossUserPermission(callingUid, userId,
7969                false /*requireFullPermission*/, false /*checkShell*/,
7970                "query intent activity options");
7971        final String resultsAction = intent.getAction();
7972
7973        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7974                | PackageManager.GET_RESOLVED_FILTER, userId);
7975
7976        if (DEBUG_INTENT_MATCHING) {
7977            Log.v(TAG, "Query " + intent + ": " + results);
7978        }
7979
7980        int specificsPos = 0;
7981        int N;
7982
7983        // todo: note that the algorithm used here is O(N^2).  This
7984        // isn't a problem in our current environment, but if we start running
7985        // into situations where we have more than 5 or 10 matches then this
7986        // should probably be changed to something smarter...
7987
7988        // First we go through and resolve each of the specific items
7989        // that were supplied, taking care of removing any corresponding
7990        // duplicate items in the generic resolve list.
7991        if (specifics != null) {
7992            for (int i=0; i<specifics.length; i++) {
7993                final Intent sintent = specifics[i];
7994                if (sintent == null) {
7995                    continue;
7996                }
7997
7998                if (DEBUG_INTENT_MATCHING) {
7999                    Log.v(TAG, "Specific #" + i + ": " + sintent);
8000                }
8001
8002                String action = sintent.getAction();
8003                if (resultsAction != null && resultsAction.equals(action)) {
8004                    // If this action was explicitly requested, then don't
8005                    // remove things that have it.
8006                    action = null;
8007                }
8008
8009                ResolveInfo ri = null;
8010                ActivityInfo ai = null;
8011
8012                ComponentName comp = sintent.getComponent();
8013                if (comp == null) {
8014                    ri = resolveIntent(
8015                        sintent,
8016                        specificTypes != null ? specificTypes[i] : null,
8017                            flags, userId);
8018                    if (ri == null) {
8019                        continue;
8020                    }
8021                    if (ri == mResolveInfo) {
8022                        // ACK!  Must do something better with this.
8023                    }
8024                    ai = ri.activityInfo;
8025                    comp = new ComponentName(ai.applicationInfo.packageName,
8026                            ai.name);
8027                } else {
8028                    ai = getActivityInfo(comp, flags, userId);
8029                    if (ai == null) {
8030                        continue;
8031                    }
8032                }
8033
8034                // Look for any generic query activities that are duplicates
8035                // of this specific one, and remove them from the results.
8036                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
8037                N = results.size();
8038                int j;
8039                for (j=specificsPos; j<N; j++) {
8040                    ResolveInfo sri = results.get(j);
8041                    if ((sri.activityInfo.name.equals(comp.getClassName())
8042                            && sri.activityInfo.applicationInfo.packageName.equals(
8043                                    comp.getPackageName()))
8044                        || (action != null && sri.filter.matchAction(action))) {
8045                        results.remove(j);
8046                        if (DEBUG_INTENT_MATCHING) Log.v(
8047                            TAG, "Removing duplicate item from " + j
8048                            + " due to specific " + specificsPos);
8049                        if (ri == null) {
8050                            ri = sri;
8051                        }
8052                        j--;
8053                        N--;
8054                    }
8055                }
8056
8057                // Add this specific item to its proper place.
8058                if (ri == null) {
8059                    ri = new ResolveInfo();
8060                    ri.activityInfo = ai;
8061                }
8062                results.add(specificsPos, ri);
8063                ri.specificIndex = i;
8064                specificsPos++;
8065            }
8066        }
8067
8068        // Now we go through the remaining generic results and remove any
8069        // duplicate actions that are found here.
8070        N = results.size();
8071        for (int i=specificsPos; i<N-1; i++) {
8072            final ResolveInfo rii = results.get(i);
8073            if (rii.filter == null) {
8074                continue;
8075            }
8076
8077            // Iterate over all of the actions of this result's intent
8078            // filter...  typically this should be just one.
8079            final Iterator<String> it = rii.filter.actionsIterator();
8080            if (it == null) {
8081                continue;
8082            }
8083            while (it.hasNext()) {
8084                final String action = it.next();
8085                if (resultsAction != null && resultsAction.equals(action)) {
8086                    // If this action was explicitly requested, then don't
8087                    // remove things that have it.
8088                    continue;
8089                }
8090                for (int j=i+1; j<N; j++) {
8091                    final ResolveInfo rij = results.get(j);
8092                    if (rij.filter != null && rij.filter.hasAction(action)) {
8093                        results.remove(j);
8094                        if (DEBUG_INTENT_MATCHING) Log.v(
8095                            TAG, "Removing duplicate item from " + j
8096                            + " due to action " + action + " at " + i);
8097                        j--;
8098                        N--;
8099                    }
8100                }
8101            }
8102
8103            // If the caller didn't request filter information, drop it now
8104            // so we don't have to marshall/unmarshall it.
8105            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
8106                rii.filter = null;
8107            }
8108        }
8109
8110        // Filter out the caller activity if so requested.
8111        if (caller != null) {
8112            N = results.size();
8113            for (int i=0; i<N; i++) {
8114                ActivityInfo ainfo = results.get(i).activityInfo;
8115                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
8116                        && caller.getClassName().equals(ainfo.name)) {
8117                    results.remove(i);
8118                    break;
8119                }
8120            }
8121        }
8122
8123        // If the caller didn't request filter information,
8124        // drop them now so we don't have to
8125        // marshall/unmarshall it.
8126        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
8127            N = results.size();
8128            for (int i=0; i<N; i++) {
8129                results.get(i).filter = null;
8130            }
8131        }
8132
8133        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
8134        return results;
8135    }
8136
8137    @Override
8138    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
8139            String resolvedType, int flags, int userId) {
8140        return new ParceledListSlice<>(
8141                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
8142                        false /*allowDynamicSplits*/));
8143    }
8144
8145    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
8146            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
8147        if (!sUserManager.exists(userId)) return Collections.emptyList();
8148        final int callingUid = Binder.getCallingUid();
8149        enforceCrossUserPermission(callingUid, userId,
8150                false /*requireFullPermission*/, false /*checkShell*/,
8151                "query intent receivers");
8152        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8153        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8154                false /*includeInstantApps*/);
8155        ComponentName comp = intent.getComponent();
8156        if (comp == null) {
8157            if (intent.getSelector() != null) {
8158                intent = intent.getSelector();
8159                comp = intent.getComponent();
8160            }
8161        }
8162        if (comp != null) {
8163            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8164            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
8165            if (ai != null) {
8166                // When specifying an explicit component, we prevent the activity from being
8167                // used when either 1) the calling package is normal and the activity is within
8168                // an instant application or 2) the calling package is ephemeral and the
8169                // activity is not visible to instant applications.
8170                final boolean matchInstantApp =
8171                        (flags & PackageManager.MATCH_INSTANT) != 0;
8172                final boolean matchVisibleToInstantAppOnly =
8173                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8174                final boolean matchExplicitlyVisibleOnly =
8175                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
8176                final boolean isCallerInstantApp =
8177                        instantAppPkgName != null;
8178                final boolean isTargetSameInstantApp =
8179                        comp.getPackageName().equals(instantAppPkgName);
8180                final boolean isTargetInstantApp =
8181                        (ai.applicationInfo.privateFlags
8182                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8183                final boolean isTargetVisibleToInstantApp =
8184                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
8185                final boolean isTargetExplicitlyVisibleToInstantApp =
8186                        isTargetVisibleToInstantApp
8187                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
8188                final boolean isTargetHiddenFromInstantApp =
8189                        !isTargetVisibleToInstantApp
8190                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
8191                final boolean blockResolution =
8192                        !isTargetSameInstantApp
8193                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8194                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8195                                        && isTargetHiddenFromInstantApp));
8196                if (!blockResolution) {
8197                    ResolveInfo ri = new ResolveInfo();
8198                    ri.activityInfo = ai;
8199                    list.add(ri);
8200                }
8201            }
8202            return applyPostResolutionFilter(
8203                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8204        }
8205
8206        // reader
8207        synchronized (mPackages) {
8208            String pkgName = intent.getPackage();
8209            if (pkgName == null) {
8210                final List<ResolveInfo> result =
8211                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
8212                return applyPostResolutionFilter(
8213                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8214            }
8215            final PackageParser.Package pkg = mPackages.get(pkgName);
8216            if (pkg != null) {
8217                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
8218                        intent, resolvedType, flags, pkg.receivers, userId);
8219                return applyPostResolutionFilter(
8220                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8221            }
8222            return Collections.emptyList();
8223        }
8224    }
8225
8226    @Override
8227    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
8228        final int callingUid = Binder.getCallingUid();
8229        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
8230    }
8231
8232    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
8233            int userId, int callingUid) {
8234        if (!sUserManager.exists(userId)) return null;
8235        flags = updateFlagsForResolve(
8236                flags, userId, intent, callingUid, false /*includeInstantApps*/);
8237        List<ResolveInfo> query = queryIntentServicesInternal(
8238                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
8239        if (query != null) {
8240            if (query.size() >= 1) {
8241                // If there is more than one service with the same priority,
8242                // just arbitrarily pick the first one.
8243                return query.get(0);
8244            }
8245        }
8246        return null;
8247    }
8248
8249    @Override
8250    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
8251            String resolvedType, int flags, int userId) {
8252        final int callingUid = Binder.getCallingUid();
8253        return new ParceledListSlice<>(queryIntentServicesInternal(
8254                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
8255    }
8256
8257    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
8258            String resolvedType, int flags, int userId, int callingUid,
8259            boolean includeInstantApps) {
8260        if (!sUserManager.exists(userId)) return Collections.emptyList();
8261        enforceCrossUserPermission(callingUid, userId,
8262                false /*requireFullPermission*/, false /*checkShell*/,
8263                "query intent receivers");
8264        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8265        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
8266        ComponentName comp = intent.getComponent();
8267        if (comp == null) {
8268            if (intent.getSelector() != null) {
8269                intent = intent.getSelector();
8270                comp = intent.getComponent();
8271            }
8272        }
8273        if (comp != null) {
8274            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8275            final ServiceInfo si = getServiceInfo(comp, flags, userId);
8276            if (si != null) {
8277                // When specifying an explicit component, we prevent the service from being
8278                // used when either 1) the service is in an instant application and the
8279                // caller is not the same instant application or 2) the calling package is
8280                // ephemeral and the activity is not visible to ephemeral applications.
8281                final boolean matchInstantApp =
8282                        (flags & PackageManager.MATCH_INSTANT) != 0;
8283                final boolean matchVisibleToInstantAppOnly =
8284                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8285                final boolean isCallerInstantApp =
8286                        instantAppPkgName != null;
8287                final boolean isTargetSameInstantApp =
8288                        comp.getPackageName().equals(instantAppPkgName);
8289                final boolean isTargetInstantApp =
8290                        (si.applicationInfo.privateFlags
8291                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8292                final boolean isTargetHiddenFromInstantApp =
8293                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8294                final boolean blockResolution =
8295                        !isTargetSameInstantApp
8296                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8297                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8298                                        && isTargetHiddenFromInstantApp));
8299                if (!blockResolution) {
8300                    final ResolveInfo ri = new ResolveInfo();
8301                    ri.serviceInfo = si;
8302                    list.add(ri);
8303                }
8304            }
8305            return list;
8306        }
8307
8308        // reader
8309        synchronized (mPackages) {
8310            String pkgName = intent.getPackage();
8311            if (pkgName == null) {
8312                return applyPostServiceResolutionFilter(
8313                        mServices.queryIntent(intent, resolvedType, flags, userId),
8314                        instantAppPkgName);
8315            }
8316            final PackageParser.Package pkg = mPackages.get(pkgName);
8317            if (pkg != null) {
8318                return applyPostServiceResolutionFilter(
8319                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
8320                                userId),
8321                        instantAppPkgName);
8322            }
8323            return Collections.emptyList();
8324        }
8325    }
8326
8327    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
8328            String instantAppPkgName) {
8329        if (instantAppPkgName == null) {
8330            return resolveInfos;
8331        }
8332        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8333            final ResolveInfo info = resolveInfos.get(i);
8334            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
8335            // allow services that are defined in the provided package
8336            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
8337                if (info.serviceInfo.splitName != null
8338                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
8339                                info.serviceInfo.splitName)) {
8340                    // requested service is defined in a split that hasn't been installed yet.
8341                    // add the installer to the resolve list
8342                    if (DEBUG_EPHEMERAL) {
8343                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8344                    }
8345                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8346                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8347                            info.serviceInfo.packageName, info.serviceInfo.splitName,
8348                            null /*failureActivity*/, info.serviceInfo.applicationInfo.versionCode,
8349                            null /*failureIntent*/);
8350                    // make sure this resolver is the default
8351                    installerInfo.isDefault = true;
8352                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8353                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8354                    // add a non-generic filter
8355                    installerInfo.filter = new IntentFilter();
8356                    // load resources from the correct package
8357                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8358                    resolveInfos.set(i, installerInfo);
8359                }
8360                continue;
8361            }
8362            // allow services that have been explicitly exposed to ephemeral apps
8363            if (!isEphemeralApp
8364                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8365                continue;
8366            }
8367            resolveInfos.remove(i);
8368        }
8369        return resolveInfos;
8370    }
8371
8372    @Override
8373    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
8374            String resolvedType, int flags, int userId) {
8375        return new ParceledListSlice<>(
8376                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
8377    }
8378
8379    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
8380            Intent intent, String resolvedType, int flags, int userId) {
8381        if (!sUserManager.exists(userId)) return Collections.emptyList();
8382        final int callingUid = Binder.getCallingUid();
8383        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8384        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8385                false /*includeInstantApps*/);
8386        ComponentName comp = intent.getComponent();
8387        if (comp == null) {
8388            if (intent.getSelector() != null) {
8389                intent = intent.getSelector();
8390                comp = intent.getComponent();
8391            }
8392        }
8393        if (comp != null) {
8394            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8395            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
8396            if (pi != null) {
8397                // When specifying an explicit component, we prevent the provider from being
8398                // used when either 1) the provider is in an instant application and the
8399                // caller is not the same instant application or 2) the calling package is an
8400                // instant application and the provider is not visible to instant applications.
8401                final boolean matchInstantApp =
8402                        (flags & PackageManager.MATCH_INSTANT) != 0;
8403                final boolean matchVisibleToInstantAppOnly =
8404                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8405                final boolean isCallerInstantApp =
8406                        instantAppPkgName != null;
8407                final boolean isTargetSameInstantApp =
8408                        comp.getPackageName().equals(instantAppPkgName);
8409                final boolean isTargetInstantApp =
8410                        (pi.applicationInfo.privateFlags
8411                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8412                final boolean isTargetHiddenFromInstantApp =
8413                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8414                final boolean blockResolution =
8415                        !isTargetSameInstantApp
8416                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8417                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8418                                        && isTargetHiddenFromInstantApp));
8419                if (!blockResolution) {
8420                    final ResolveInfo ri = new ResolveInfo();
8421                    ri.providerInfo = pi;
8422                    list.add(ri);
8423                }
8424            }
8425            return list;
8426        }
8427
8428        // reader
8429        synchronized (mPackages) {
8430            String pkgName = intent.getPackage();
8431            if (pkgName == null) {
8432                return applyPostContentProviderResolutionFilter(
8433                        mProviders.queryIntent(intent, resolvedType, flags, userId),
8434                        instantAppPkgName);
8435            }
8436            final PackageParser.Package pkg = mPackages.get(pkgName);
8437            if (pkg != null) {
8438                return applyPostContentProviderResolutionFilter(
8439                        mProviders.queryIntentForPackage(
8440                        intent, resolvedType, flags, pkg.providers, userId),
8441                        instantAppPkgName);
8442            }
8443            return Collections.emptyList();
8444        }
8445    }
8446
8447    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8448            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8449        if (instantAppPkgName == null) {
8450            return resolveInfos;
8451        }
8452        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8453            final ResolveInfo info = resolveInfos.get(i);
8454            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8455            // allow providers that are defined in the provided package
8456            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8457                if (info.providerInfo.splitName != null
8458                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8459                                info.providerInfo.splitName)) {
8460                    // requested provider is defined in a split that hasn't been installed yet.
8461                    // add the installer to the resolve list
8462                    if (DEBUG_EPHEMERAL) {
8463                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8464                    }
8465                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8466                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8467                            info.providerInfo.packageName, info.providerInfo.splitName,
8468                            null /*failureActivity*/, info.providerInfo.applicationInfo.versionCode,
8469                            null /*failureIntent*/);
8470                    // make sure this resolver is the default
8471                    installerInfo.isDefault = true;
8472                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8473                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8474                    // add a non-generic filter
8475                    installerInfo.filter = new IntentFilter();
8476                    // load resources from the correct package
8477                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8478                    resolveInfos.set(i, installerInfo);
8479                }
8480                continue;
8481            }
8482            // allow providers that have been explicitly exposed to instant applications
8483            if (!isEphemeralApp
8484                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8485                continue;
8486            }
8487            resolveInfos.remove(i);
8488        }
8489        return resolveInfos;
8490    }
8491
8492    @Override
8493    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8494        final int callingUid = Binder.getCallingUid();
8495        if (getInstantAppPackageName(callingUid) != null) {
8496            return ParceledListSlice.emptyList();
8497        }
8498        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8499        flags = updateFlagsForPackage(flags, userId, null);
8500        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8501        enforceCrossUserPermission(callingUid, userId,
8502                true /* requireFullPermission */, false /* checkShell */,
8503                "get installed packages");
8504
8505        // writer
8506        synchronized (mPackages) {
8507            ArrayList<PackageInfo> list;
8508            if (listUninstalled) {
8509                list = new ArrayList<>(mSettings.mPackages.size());
8510                for (PackageSetting ps : mSettings.mPackages.values()) {
8511                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8512                        continue;
8513                    }
8514                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8515                        return null;
8516                    }
8517                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8518                    if (pi != null) {
8519                        list.add(pi);
8520                    }
8521                }
8522            } else {
8523                list = new ArrayList<>(mPackages.size());
8524                for (PackageParser.Package p : mPackages.values()) {
8525                    final PackageSetting ps = (PackageSetting) p.mExtras;
8526                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8527                        continue;
8528                    }
8529                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8530                        return null;
8531                    }
8532                    final PackageInfo pi = generatePackageInfo((PackageSetting)
8533                            p.mExtras, flags, userId);
8534                    if (pi != null) {
8535                        list.add(pi);
8536                    }
8537                }
8538            }
8539
8540            return new ParceledListSlice<>(list);
8541        }
8542    }
8543
8544    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8545            String[] permissions, boolean[] tmp, int flags, int userId) {
8546        int numMatch = 0;
8547        final PermissionsState permissionsState = ps.getPermissionsState();
8548        for (int i=0; i<permissions.length; i++) {
8549            final String permission = permissions[i];
8550            if (permissionsState.hasPermission(permission, userId)) {
8551                tmp[i] = true;
8552                numMatch++;
8553            } else {
8554                tmp[i] = false;
8555            }
8556        }
8557        if (numMatch == 0) {
8558            return;
8559        }
8560        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8561
8562        // The above might return null in cases of uninstalled apps or install-state
8563        // skew across users/profiles.
8564        if (pi != null) {
8565            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8566                if (numMatch == permissions.length) {
8567                    pi.requestedPermissions = permissions;
8568                } else {
8569                    pi.requestedPermissions = new String[numMatch];
8570                    numMatch = 0;
8571                    for (int i=0; i<permissions.length; i++) {
8572                        if (tmp[i]) {
8573                            pi.requestedPermissions[numMatch] = permissions[i];
8574                            numMatch++;
8575                        }
8576                    }
8577                }
8578            }
8579            list.add(pi);
8580        }
8581    }
8582
8583    @Override
8584    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8585            String[] permissions, int flags, int userId) {
8586        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8587        flags = updateFlagsForPackage(flags, userId, permissions);
8588        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8589                true /* requireFullPermission */, false /* checkShell */,
8590                "get packages holding permissions");
8591        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8592
8593        // writer
8594        synchronized (mPackages) {
8595            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8596            boolean[] tmpBools = new boolean[permissions.length];
8597            if (listUninstalled) {
8598                for (PackageSetting ps : mSettings.mPackages.values()) {
8599                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8600                            userId);
8601                }
8602            } else {
8603                for (PackageParser.Package pkg : mPackages.values()) {
8604                    PackageSetting ps = (PackageSetting)pkg.mExtras;
8605                    if (ps != null) {
8606                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8607                                userId);
8608                    }
8609                }
8610            }
8611
8612            return new ParceledListSlice<PackageInfo>(list);
8613        }
8614    }
8615
8616    @Override
8617    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8618        final int callingUid = Binder.getCallingUid();
8619        if (getInstantAppPackageName(callingUid) != null) {
8620            return ParceledListSlice.emptyList();
8621        }
8622        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8623        flags = updateFlagsForApplication(flags, userId, null);
8624        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8625
8626        // writer
8627        synchronized (mPackages) {
8628            ArrayList<ApplicationInfo> list;
8629            if (listUninstalled) {
8630                list = new ArrayList<>(mSettings.mPackages.size());
8631                for (PackageSetting ps : mSettings.mPackages.values()) {
8632                    ApplicationInfo ai;
8633                    int effectiveFlags = flags;
8634                    if (ps.isSystem()) {
8635                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8636                    }
8637                    if (ps.pkg != null) {
8638                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8639                            continue;
8640                        }
8641                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8642                            return null;
8643                        }
8644                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8645                                ps.readUserState(userId), userId);
8646                        if (ai != null) {
8647                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8648                        }
8649                    } else {
8650                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8651                        // and already converts to externally visible package name
8652                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8653                                callingUid, effectiveFlags, userId);
8654                    }
8655                    if (ai != null) {
8656                        list.add(ai);
8657                    }
8658                }
8659            } else {
8660                list = new ArrayList<>(mPackages.size());
8661                for (PackageParser.Package p : mPackages.values()) {
8662                    if (p.mExtras != null) {
8663                        PackageSetting ps = (PackageSetting) p.mExtras;
8664                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8665                            continue;
8666                        }
8667                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8668                            return null;
8669                        }
8670                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8671                                ps.readUserState(userId), userId);
8672                        if (ai != null) {
8673                            ai.packageName = resolveExternalPackageNameLPr(p);
8674                            list.add(ai);
8675                        }
8676                    }
8677                }
8678            }
8679
8680            return new ParceledListSlice<>(list);
8681        }
8682    }
8683
8684    @Override
8685    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8686        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8687            return null;
8688        }
8689        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8690            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8691                    "getEphemeralApplications");
8692        }
8693        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8694                true /* requireFullPermission */, false /* checkShell */,
8695                "getEphemeralApplications");
8696        synchronized (mPackages) {
8697            List<InstantAppInfo> instantApps = mInstantAppRegistry
8698                    .getInstantAppsLPr(userId);
8699            if (instantApps != null) {
8700                return new ParceledListSlice<>(instantApps);
8701            }
8702        }
8703        return null;
8704    }
8705
8706    @Override
8707    public boolean isInstantApp(String packageName, int userId) {
8708        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8709                true /* requireFullPermission */, false /* checkShell */,
8710                "isInstantApp");
8711        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8712            return false;
8713        }
8714
8715        synchronized (mPackages) {
8716            int callingUid = Binder.getCallingUid();
8717            if (Process.isIsolated(callingUid)) {
8718                callingUid = mIsolatedOwners.get(callingUid);
8719            }
8720            final PackageSetting ps = mSettings.mPackages.get(packageName);
8721            PackageParser.Package pkg = mPackages.get(packageName);
8722            final boolean returnAllowed =
8723                    ps != null
8724                    && (isCallerSameApp(packageName, callingUid)
8725                            || canViewInstantApps(callingUid, userId)
8726                            || mInstantAppRegistry.isInstantAccessGranted(
8727                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8728            if (returnAllowed) {
8729                return ps.getInstantApp(userId);
8730            }
8731        }
8732        return false;
8733    }
8734
8735    @Override
8736    public byte[] getInstantAppCookie(String packageName, int userId) {
8737        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8738            return null;
8739        }
8740
8741        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8742                true /* requireFullPermission */, false /* checkShell */,
8743                "getInstantAppCookie");
8744        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8745            return null;
8746        }
8747        synchronized (mPackages) {
8748            return mInstantAppRegistry.getInstantAppCookieLPw(
8749                    packageName, userId);
8750        }
8751    }
8752
8753    @Override
8754    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8755        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8756            return true;
8757        }
8758
8759        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8760                true /* requireFullPermission */, true /* checkShell */,
8761                "setInstantAppCookie");
8762        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8763            return false;
8764        }
8765        synchronized (mPackages) {
8766            return mInstantAppRegistry.setInstantAppCookieLPw(
8767                    packageName, cookie, userId);
8768        }
8769    }
8770
8771    @Override
8772    public Bitmap getInstantAppIcon(String packageName, int userId) {
8773        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8774            return null;
8775        }
8776
8777        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8778            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8779                    "getInstantAppIcon");
8780        }
8781        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8782                true /* requireFullPermission */, false /* checkShell */,
8783                "getInstantAppIcon");
8784
8785        synchronized (mPackages) {
8786            return mInstantAppRegistry.getInstantAppIconLPw(
8787                    packageName, userId);
8788        }
8789    }
8790
8791    private boolean isCallerSameApp(String packageName, int uid) {
8792        PackageParser.Package pkg = mPackages.get(packageName);
8793        return pkg != null
8794                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8795    }
8796
8797    @Override
8798    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8799        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8800            return ParceledListSlice.emptyList();
8801        }
8802        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8803    }
8804
8805    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8806        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8807
8808        // reader
8809        synchronized (mPackages) {
8810            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8811            final int userId = UserHandle.getCallingUserId();
8812            while (i.hasNext()) {
8813                final PackageParser.Package p = i.next();
8814                if (p.applicationInfo == null) continue;
8815
8816                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8817                        && !p.applicationInfo.isDirectBootAware();
8818                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8819                        && p.applicationInfo.isDirectBootAware();
8820
8821                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8822                        && (!mSafeMode || isSystemApp(p))
8823                        && (matchesUnaware || matchesAware)) {
8824                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8825                    if (ps != null) {
8826                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8827                                ps.readUserState(userId), userId);
8828                        if (ai != null) {
8829                            finalList.add(ai);
8830                        }
8831                    }
8832                }
8833            }
8834        }
8835
8836        return finalList;
8837    }
8838
8839    @Override
8840    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8841        if (!sUserManager.exists(userId)) return null;
8842        flags = updateFlagsForComponent(flags, userId, name);
8843        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8844        // reader
8845        synchronized (mPackages) {
8846            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8847            PackageSetting ps = provider != null
8848                    ? mSettings.mPackages.get(provider.owner.packageName)
8849                    : null;
8850            if (ps != null) {
8851                final boolean isInstantApp = ps.getInstantApp(userId);
8852                // normal application; filter out instant application provider
8853                if (instantAppPkgName == null && isInstantApp) {
8854                    return null;
8855                }
8856                // instant application; filter out other instant applications
8857                if (instantAppPkgName != null
8858                        && isInstantApp
8859                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8860                    return null;
8861                }
8862                // instant application; filter out non-exposed provider
8863                if (instantAppPkgName != null
8864                        && !isInstantApp
8865                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8866                    return null;
8867                }
8868                // provider not enabled
8869                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8870                    return null;
8871                }
8872                return PackageParser.generateProviderInfo(
8873                        provider, flags, ps.readUserState(userId), userId);
8874            }
8875            return null;
8876        }
8877    }
8878
8879    /**
8880     * @deprecated
8881     */
8882    @Deprecated
8883    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8884        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8885            return;
8886        }
8887        // reader
8888        synchronized (mPackages) {
8889            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8890                    .entrySet().iterator();
8891            final int userId = UserHandle.getCallingUserId();
8892            while (i.hasNext()) {
8893                Map.Entry<String, PackageParser.Provider> entry = i.next();
8894                PackageParser.Provider p = entry.getValue();
8895                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8896
8897                if (ps != null && p.syncable
8898                        && (!mSafeMode || (p.info.applicationInfo.flags
8899                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8900                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8901                            ps.readUserState(userId), userId);
8902                    if (info != null) {
8903                        outNames.add(entry.getKey());
8904                        outInfo.add(info);
8905                    }
8906                }
8907            }
8908        }
8909    }
8910
8911    @Override
8912    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8913            int uid, int flags, String metaDataKey) {
8914        final int callingUid = Binder.getCallingUid();
8915        final int userId = processName != null ? UserHandle.getUserId(uid)
8916                : UserHandle.getCallingUserId();
8917        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8918        flags = updateFlagsForComponent(flags, userId, processName);
8919        ArrayList<ProviderInfo> finalList = null;
8920        // reader
8921        synchronized (mPackages) {
8922            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8923            while (i.hasNext()) {
8924                final PackageParser.Provider p = i.next();
8925                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8926                if (ps != null && p.info.authority != null
8927                        && (processName == null
8928                                || (p.info.processName.equals(processName)
8929                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8930                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8931
8932                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8933                    // parameter.
8934                    if (metaDataKey != null
8935                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8936                        continue;
8937                    }
8938                    final ComponentName component =
8939                            new ComponentName(p.info.packageName, p.info.name);
8940                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8941                        continue;
8942                    }
8943                    if (finalList == null) {
8944                        finalList = new ArrayList<ProviderInfo>(3);
8945                    }
8946                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8947                            ps.readUserState(userId), userId);
8948                    if (info != null) {
8949                        finalList.add(info);
8950                    }
8951                }
8952            }
8953        }
8954
8955        if (finalList != null) {
8956            Collections.sort(finalList, mProviderInitOrderSorter);
8957            return new ParceledListSlice<ProviderInfo>(finalList);
8958        }
8959
8960        return ParceledListSlice.emptyList();
8961    }
8962
8963    @Override
8964    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8965        // reader
8966        synchronized (mPackages) {
8967            final int callingUid = Binder.getCallingUid();
8968            final int callingUserId = UserHandle.getUserId(callingUid);
8969            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8970            if (ps == null) return null;
8971            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8972                return null;
8973            }
8974            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8975            return PackageParser.generateInstrumentationInfo(i, flags);
8976        }
8977    }
8978
8979    @Override
8980    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8981            String targetPackage, int flags) {
8982        final int callingUid = Binder.getCallingUid();
8983        final int callingUserId = UserHandle.getUserId(callingUid);
8984        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8985        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8986            return ParceledListSlice.emptyList();
8987        }
8988        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8989    }
8990
8991    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8992            int flags) {
8993        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8994
8995        // reader
8996        synchronized (mPackages) {
8997            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8998            while (i.hasNext()) {
8999                final PackageParser.Instrumentation p = i.next();
9000                if (targetPackage == null
9001                        || targetPackage.equals(p.info.targetPackage)) {
9002                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
9003                            flags);
9004                    if (ii != null) {
9005                        finalList.add(ii);
9006                    }
9007                }
9008            }
9009        }
9010
9011        return finalList;
9012    }
9013
9014    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
9015        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
9016        try {
9017            scanDirLI(dir, parseFlags, scanFlags, currentTime);
9018        } finally {
9019            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9020        }
9021    }
9022
9023    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
9024        final File[] files = dir.listFiles();
9025        if (ArrayUtils.isEmpty(files)) {
9026            Log.d(TAG, "No files in app dir " + dir);
9027            return;
9028        }
9029
9030        if (DEBUG_PACKAGE_SCANNING) {
9031            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
9032                    + " flags=0x" + Integer.toHexString(parseFlags));
9033        }
9034        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
9035                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
9036                mParallelPackageParserCallback);
9037
9038        // Submit files for parsing in parallel
9039        int fileCount = 0;
9040        for (File file : files) {
9041            final boolean isPackage = (isApkFile(file) || file.isDirectory())
9042                    && !PackageInstallerService.isStageName(file.getName());
9043            if (!isPackage) {
9044                // Ignore entries which are not packages
9045                continue;
9046            }
9047            parallelPackageParser.submit(file, parseFlags);
9048            fileCount++;
9049        }
9050
9051        // Process results one by one
9052        for (; fileCount > 0; fileCount--) {
9053            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
9054            Throwable throwable = parseResult.throwable;
9055            int errorCode = PackageManager.INSTALL_SUCCEEDED;
9056
9057            if (throwable == null) {
9058                // Static shared libraries have synthetic package names
9059                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
9060                    renameStaticSharedLibraryPackage(parseResult.pkg);
9061                }
9062                try {
9063                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
9064                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
9065                                currentTime, null);
9066                    }
9067                } catch (PackageManagerException e) {
9068                    errorCode = e.error;
9069                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
9070                }
9071            } else if (throwable instanceof PackageParser.PackageParserException) {
9072                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
9073                        throwable;
9074                errorCode = e.error;
9075                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
9076            } else {
9077                throw new IllegalStateException("Unexpected exception occurred while parsing "
9078                        + parseResult.scanFile, throwable);
9079            }
9080
9081            // Delete invalid userdata apps
9082            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
9083                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
9084                logCriticalInfo(Log.WARN,
9085                        "Deleting invalid package at " + parseResult.scanFile);
9086                removeCodePathLI(parseResult.scanFile);
9087            }
9088        }
9089        parallelPackageParser.close();
9090    }
9091
9092    private static File getSettingsProblemFile() {
9093        File dataDir = Environment.getDataDirectory();
9094        File systemDir = new File(dataDir, "system");
9095        File fname = new File(systemDir, "uiderrors.txt");
9096        return fname;
9097    }
9098
9099    static void reportSettingsProblem(int priority, String msg) {
9100        logCriticalInfo(priority, msg);
9101    }
9102
9103    public static void logCriticalInfo(int priority, String msg) {
9104        Slog.println(priority, TAG, msg);
9105        EventLogTags.writePmCriticalInfo(msg);
9106        try {
9107            File fname = getSettingsProblemFile();
9108            FileOutputStream out = new FileOutputStream(fname, true);
9109            PrintWriter pw = new FastPrintWriter(out);
9110            SimpleDateFormat formatter = new SimpleDateFormat();
9111            String dateString = formatter.format(new Date(System.currentTimeMillis()));
9112            pw.println(dateString + ": " + msg);
9113            pw.close();
9114            FileUtils.setPermissions(
9115                    fname.toString(),
9116                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
9117                    -1, -1);
9118        } catch (java.io.IOException e) {
9119        }
9120    }
9121
9122    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
9123        if (srcFile.isDirectory()) {
9124            final File baseFile = new File(pkg.baseCodePath);
9125            long maxModifiedTime = baseFile.lastModified();
9126            if (pkg.splitCodePaths != null) {
9127                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
9128                    final File splitFile = new File(pkg.splitCodePaths[i]);
9129                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
9130                }
9131            }
9132            return maxModifiedTime;
9133        }
9134        return srcFile.lastModified();
9135    }
9136
9137    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
9138            final int policyFlags) throws PackageManagerException {
9139        // When upgrading from pre-N MR1, verify the package time stamp using the package
9140        // directory and not the APK file.
9141        final long lastModifiedTime = mIsPreNMR1Upgrade
9142                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
9143        if (ps != null
9144                && ps.codePath.equals(srcFile)
9145                && ps.timeStamp == lastModifiedTime
9146                && !isCompatSignatureUpdateNeeded(pkg)
9147                && !isRecoverSignatureUpdateNeeded(pkg)) {
9148            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
9149            KeySetManagerService ksms = mSettings.mKeySetManagerService;
9150            ArraySet<PublicKey> signingKs;
9151            synchronized (mPackages) {
9152                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
9153            }
9154            if (ps.signatures.mSignatures != null
9155                    && ps.signatures.mSignatures.length != 0
9156                    && signingKs != null) {
9157                // Optimization: reuse the existing cached certificates
9158                // if the package appears to be unchanged.
9159                pkg.mSignatures = ps.signatures.mSignatures;
9160                pkg.mSigningKeys = signingKs;
9161                return;
9162            }
9163
9164            Slog.w(TAG, "PackageSetting for " + ps.name
9165                    + " is missing signatures.  Collecting certs again to recover them.");
9166        } else {
9167            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
9168        }
9169
9170        try {
9171            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
9172            PackageParser.collectCertificates(pkg, policyFlags);
9173        } catch (PackageParserException e) {
9174            throw PackageManagerException.from(e);
9175        } finally {
9176            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9177        }
9178    }
9179
9180    /**
9181     *  Traces a package scan.
9182     *  @see #scanPackageLI(File, int, int, long, UserHandle)
9183     */
9184    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
9185            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
9186        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
9187        try {
9188            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
9189        } finally {
9190            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9191        }
9192    }
9193
9194    /**
9195     *  Scans a package and returns the newly parsed package.
9196     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
9197     */
9198    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
9199            long currentTime, UserHandle user) throws PackageManagerException {
9200        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
9201        PackageParser pp = new PackageParser();
9202        pp.setSeparateProcesses(mSeparateProcesses);
9203        pp.setOnlyCoreApps(mOnlyCore);
9204        pp.setDisplayMetrics(mMetrics);
9205        pp.setCallback(mPackageParserCallback);
9206
9207        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
9208            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
9209        }
9210
9211        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
9212        final PackageParser.Package pkg;
9213        try {
9214            pkg = pp.parsePackage(scanFile, parseFlags);
9215        } catch (PackageParserException e) {
9216            throw PackageManagerException.from(e);
9217        } finally {
9218            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9219        }
9220
9221        // Static shared libraries have synthetic package names
9222        if (pkg.applicationInfo.isStaticSharedLibrary()) {
9223            renameStaticSharedLibraryPackage(pkg);
9224        }
9225
9226        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
9227    }
9228
9229    /**
9230     *  Scans a package and returns the newly parsed package.
9231     *  @throws PackageManagerException on a parse error.
9232     */
9233    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
9234            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9235            throws PackageManagerException {
9236        // If the package has children and this is the first dive in the function
9237        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
9238        // packages (parent and children) would be successfully scanned before the
9239        // actual scan since scanning mutates internal state and we want to atomically
9240        // install the package and its children.
9241        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9242            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9243                scanFlags |= SCAN_CHECK_ONLY;
9244            }
9245        } else {
9246            scanFlags &= ~SCAN_CHECK_ONLY;
9247        }
9248
9249        // Scan the parent
9250        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
9251                scanFlags, currentTime, user);
9252
9253        // Scan the children
9254        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9255        for (int i = 0; i < childCount; i++) {
9256            PackageParser.Package childPackage = pkg.childPackages.get(i);
9257            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
9258                    currentTime, user);
9259        }
9260
9261
9262        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9263            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
9264        }
9265
9266        return scannedPkg;
9267    }
9268
9269    /**
9270     *  Scans a package and returns the newly parsed package.
9271     *  @throws PackageManagerException on a parse error.
9272     */
9273    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
9274            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9275            throws PackageManagerException {
9276        PackageSetting ps = null;
9277        PackageSetting updatedPkg;
9278        // reader
9279        synchronized (mPackages) {
9280            // Look to see if we already know about this package.
9281            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
9282            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
9283                // This package has been renamed to its original name.  Let's
9284                // use that.
9285                ps = mSettings.getPackageLPr(oldName);
9286            }
9287            // If there was no original package, see one for the real package name.
9288            if (ps == null) {
9289                ps = mSettings.getPackageLPr(pkg.packageName);
9290            }
9291            // Check to see if this package could be hiding/updating a system
9292            // package.  Must look for it either under the original or real
9293            // package name depending on our state.
9294            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
9295            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
9296
9297            // If this is a package we don't know about on the system partition, we
9298            // may need to remove disabled child packages on the system partition
9299            // or may need to not add child packages if the parent apk is updated
9300            // on the data partition and no longer defines this child package.
9301            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
9302                // If this is a parent package for an updated system app and this system
9303                // app got an OTA update which no longer defines some of the child packages
9304                // we have to prune them from the disabled system packages.
9305                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9306                if (disabledPs != null) {
9307                    final int scannedChildCount = (pkg.childPackages != null)
9308                            ? pkg.childPackages.size() : 0;
9309                    final int disabledChildCount = disabledPs.childPackageNames != null
9310                            ? disabledPs.childPackageNames.size() : 0;
9311                    for (int i = 0; i < disabledChildCount; i++) {
9312                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
9313                        boolean disabledPackageAvailable = false;
9314                        for (int j = 0; j < scannedChildCount; j++) {
9315                            PackageParser.Package childPkg = pkg.childPackages.get(j);
9316                            if (childPkg.packageName.equals(disabledChildPackageName)) {
9317                                disabledPackageAvailable = true;
9318                                break;
9319                            }
9320                         }
9321                         if (!disabledPackageAvailable) {
9322                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
9323                         }
9324                    }
9325                }
9326            }
9327        }
9328
9329        final boolean isUpdatedPkg = updatedPkg != null;
9330        final boolean isUpdatedSystemPkg = isUpdatedPkg
9331                && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0;
9332        boolean isUpdatedPkgBetter = false;
9333        // First check if this is a system package that may involve an update
9334        if (isUpdatedSystemPkg) {
9335            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
9336            // it needs to drop FLAG_PRIVILEGED.
9337            if (locationIsPrivileged(scanFile)) {
9338                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9339            } else {
9340                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9341            }
9342
9343            if (ps != null && !ps.codePath.equals(scanFile)) {
9344                // The path has changed from what was last scanned...  check the
9345                // version of the new path against what we have stored to determine
9346                // what to do.
9347                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
9348                if (pkg.mVersionCode <= ps.versionCode) {
9349                    // The system package has been updated and the code path does not match
9350                    // Ignore entry. Skip it.
9351                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
9352                            + " ignored: updated version " + ps.versionCode
9353                            + " better than this " + pkg.mVersionCode);
9354                    if (!updatedPkg.codePath.equals(scanFile)) {
9355                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
9356                                + ps.name + " changing from " + updatedPkg.codePathString
9357                                + " to " + scanFile);
9358                        updatedPkg.codePath = scanFile;
9359                        updatedPkg.codePathString = scanFile.toString();
9360                        updatedPkg.resourcePath = scanFile;
9361                        updatedPkg.resourcePathString = scanFile.toString();
9362                    }
9363                    updatedPkg.pkg = pkg;
9364                    updatedPkg.versionCode = pkg.mVersionCode;
9365
9366                    // Update the disabled system child packages to point to the package too.
9367                    final int childCount = updatedPkg.childPackageNames != null
9368                            ? updatedPkg.childPackageNames.size() : 0;
9369                    for (int i = 0; i < childCount; i++) {
9370                        String childPackageName = updatedPkg.childPackageNames.get(i);
9371                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
9372                                childPackageName);
9373                        if (updatedChildPkg != null) {
9374                            updatedChildPkg.pkg = pkg;
9375                            updatedChildPkg.versionCode = pkg.mVersionCode;
9376                        }
9377                    }
9378                } else {
9379                    // The current app on the system partition is better than
9380                    // what we have updated to on the data partition; switch
9381                    // back to the system partition version.
9382                    // At this point, its safely assumed that package installation for
9383                    // apps in system partition will go through. If not there won't be a working
9384                    // version of the app
9385                    // writer
9386                    synchronized (mPackages) {
9387                        // Just remove the loaded entries from package lists.
9388                        mPackages.remove(ps.name);
9389                    }
9390
9391                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9392                            + " reverting from " + ps.codePathString
9393                            + ": new version " + pkg.mVersionCode
9394                            + " better than installed " + ps.versionCode);
9395
9396                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9397                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9398                    synchronized (mInstallLock) {
9399                        args.cleanUpResourcesLI();
9400                    }
9401                    synchronized (mPackages) {
9402                        mSettings.enableSystemPackageLPw(ps.name);
9403                    }
9404                    isUpdatedPkgBetter = true;
9405                }
9406            }
9407        }
9408
9409        String resourcePath = null;
9410        String baseResourcePath = null;
9411        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) {
9412            if (ps != null && ps.resourcePathString != null) {
9413                resourcePath = ps.resourcePathString;
9414                baseResourcePath = ps.resourcePathString;
9415            } else {
9416                // Should not happen at all. Just log an error.
9417                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9418            }
9419        } else {
9420            resourcePath = pkg.codePath;
9421            baseResourcePath = pkg.baseCodePath;
9422        }
9423
9424        // Set application objects path explicitly.
9425        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9426        pkg.setApplicationInfoCodePath(pkg.codePath);
9427        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9428        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9429        pkg.setApplicationInfoResourcePath(resourcePath);
9430        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9431        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9432
9433        // throw an exception if we have an update to a system application, but, it's not more
9434        // recent than the package we've already scanned
9435        if (isUpdatedSystemPkg && !isUpdatedPkgBetter) {
9436            // Set CPU Abis to application info.
9437            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9438                final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, updatedPkg);
9439                derivePackageAbi(pkg, scanFile, cpuAbiOverride, false, mAppLib32InstallDir);
9440            } else {
9441                pkg.applicationInfo.primaryCpuAbi = updatedPkg.primaryCpuAbiString;
9442                pkg.applicationInfo.secondaryCpuAbi = updatedPkg.secondaryCpuAbiString;
9443            }
9444
9445            throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
9446                    + scanFile + " ignored: updated version " + ps.versionCode
9447                    + " better than this " + pkg.mVersionCode);
9448        }
9449
9450        if (isUpdatedPkg) {
9451            // An updated system app will not have the PARSE_IS_SYSTEM flag set
9452            // initially
9453            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
9454
9455            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
9456            // flag set initially
9457            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9458                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9459            }
9460        }
9461
9462        // Verify certificates against what was last scanned
9463        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
9464
9465        /*
9466         * A new system app appeared, but we already had a non-system one of the
9467         * same name installed earlier.
9468         */
9469        boolean shouldHideSystemApp = false;
9470        if (!isUpdatedPkg && ps != null
9471                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
9472            /*
9473             * Check to make sure the signatures match first. If they don't,
9474             * wipe the installed application and its data.
9475             */
9476            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
9477                    != PackageManager.SIGNATURE_MATCH) {
9478                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
9479                        + " signatures don't match existing userdata copy; removing");
9480                try (PackageFreezer freezer = freezePackage(pkg.packageName,
9481                        "scanPackageInternalLI")) {
9482                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9483                }
9484                ps = null;
9485            } else {
9486                /*
9487                 * If the newly-added system app is an older version than the
9488                 * already installed version, hide it. It will be scanned later
9489                 * and re-added like an update.
9490                 */
9491                if (pkg.mVersionCode <= ps.versionCode) {
9492                    shouldHideSystemApp = true;
9493                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9494                            + " but new version " + pkg.mVersionCode + " better than installed "
9495                            + ps.versionCode + "; hiding system");
9496                } else {
9497                    /*
9498                     * The newly found system app is a newer version that the
9499                     * one previously installed. Simply remove the
9500                     * already-installed application and replace it with our own
9501                     * while keeping the application data.
9502                     */
9503                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9504                            + " reverting from " + ps.codePathString + ": new version "
9505                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
9506                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9507                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9508                    synchronized (mInstallLock) {
9509                        args.cleanUpResourcesLI();
9510                    }
9511                }
9512            }
9513        }
9514
9515        // The apk is forward locked (not public) if its code and resources
9516        // are kept in different files. (except for app in either system or
9517        // vendor path).
9518        // TODO grab this value from PackageSettings
9519        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9520            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9521                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9522            }
9523        }
9524
9525        final int userId = ((user == null) ? 0 : user.getIdentifier());
9526        if (ps != null && ps.getInstantApp(userId)) {
9527            scanFlags |= SCAN_AS_INSTANT_APP;
9528        }
9529        if (ps != null && ps.getVirtulalPreload(userId)) {
9530            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
9531        }
9532
9533        // Note that we invoke the following method only if we are about to unpack an application
9534        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9535                | SCAN_UPDATE_SIGNATURE, currentTime, user);
9536
9537        /*
9538         * If the system app should be overridden by a previously installed
9539         * data, hide the system app now and let the /data/app scan pick it up
9540         * again.
9541         */
9542        if (shouldHideSystemApp) {
9543            synchronized (mPackages) {
9544                mSettings.disableSystemPackageLPw(pkg.packageName, true);
9545            }
9546        }
9547
9548        return scannedPkg;
9549    }
9550
9551    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9552        // Derive the new package synthetic package name
9553        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9554                + pkg.staticSharedLibVersion);
9555    }
9556
9557    private static String fixProcessName(String defProcessName,
9558            String processName) {
9559        if (processName == null) {
9560            return defProcessName;
9561        }
9562        return processName;
9563    }
9564
9565    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9566            throws PackageManagerException {
9567        if (pkgSetting.signatures.mSignatures != null) {
9568            // Already existing package. Make sure signatures match
9569            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9570                    == PackageManager.SIGNATURE_MATCH;
9571            if (!match) {
9572                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9573                        == PackageManager.SIGNATURE_MATCH;
9574            }
9575            if (!match) {
9576                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9577                        == PackageManager.SIGNATURE_MATCH;
9578            }
9579            if (!match) {
9580                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9581                        + pkg.packageName + " signatures do not match the "
9582                        + "previously installed version; ignoring!");
9583            }
9584        }
9585
9586        // Check for shared user signatures
9587        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9588            // Already existing package. Make sure signatures match
9589            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9590                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9591            if (!match) {
9592                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9593                        == PackageManager.SIGNATURE_MATCH;
9594            }
9595            if (!match) {
9596                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9597                        == PackageManager.SIGNATURE_MATCH;
9598            }
9599            if (!match) {
9600                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9601                        "Package " + pkg.packageName
9602                        + " has no signatures that match those in shared user "
9603                        + pkgSetting.sharedUser.name + "; ignoring!");
9604            }
9605        }
9606    }
9607
9608    /**
9609     * Enforces that only the system UID or root's UID can call a method exposed
9610     * via Binder.
9611     *
9612     * @param message used as message if SecurityException is thrown
9613     * @throws SecurityException if the caller is not system or root
9614     */
9615    private static final void enforceSystemOrRoot(String message) {
9616        final int uid = Binder.getCallingUid();
9617        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9618            throw new SecurityException(message);
9619        }
9620    }
9621
9622    @Override
9623    public void performFstrimIfNeeded() {
9624        enforceSystemOrRoot("Only the system can request fstrim");
9625
9626        // Before everything else, see whether we need to fstrim.
9627        try {
9628            IStorageManager sm = PackageHelper.getStorageManager();
9629            if (sm != null) {
9630                boolean doTrim = false;
9631                final long interval = android.provider.Settings.Global.getLong(
9632                        mContext.getContentResolver(),
9633                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9634                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9635                if (interval > 0) {
9636                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9637                    if (timeSinceLast > interval) {
9638                        doTrim = true;
9639                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9640                                + "; running immediately");
9641                    }
9642                }
9643                if (doTrim) {
9644                    final boolean dexOptDialogShown;
9645                    synchronized (mPackages) {
9646                        dexOptDialogShown = mDexOptDialogShown;
9647                    }
9648                    if (!isFirstBoot() && dexOptDialogShown) {
9649                        try {
9650                            ActivityManager.getService().showBootMessage(
9651                                    mContext.getResources().getString(
9652                                            R.string.android_upgrading_fstrim), true);
9653                        } catch (RemoteException e) {
9654                        }
9655                    }
9656                    sm.runMaintenance();
9657                }
9658            } else {
9659                Slog.e(TAG, "storageManager service unavailable!");
9660            }
9661        } catch (RemoteException e) {
9662            // Can't happen; StorageManagerService is local
9663        }
9664    }
9665
9666    @Override
9667    public void updatePackagesIfNeeded() {
9668        enforceSystemOrRoot("Only the system can request package update");
9669
9670        // We need to re-extract after an OTA.
9671        boolean causeUpgrade = isUpgrade();
9672
9673        // First boot or factory reset.
9674        // Note: we also handle devices that are upgrading to N right now as if it is their
9675        //       first boot, as they do not have profile data.
9676        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9677
9678        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9679        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9680
9681        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9682            return;
9683        }
9684
9685        List<PackageParser.Package> pkgs;
9686        synchronized (mPackages) {
9687            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9688        }
9689
9690        final long startTime = System.nanoTime();
9691        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9692                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
9693                    false /* bootComplete */);
9694
9695        final int elapsedTimeSeconds =
9696                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9697
9698        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9699        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9700        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9701        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9702        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9703    }
9704
9705    /*
9706     * Return the prebuilt profile path given a package base code path.
9707     */
9708    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
9709        return pkg.baseCodePath + ".prof";
9710    }
9711
9712    /**
9713     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9714     * containing statistics about the invocation. The array consists of three elements,
9715     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9716     * and {@code numberOfPackagesFailed}.
9717     */
9718    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9719            String compilerFilter, boolean bootComplete) {
9720
9721        int numberOfPackagesVisited = 0;
9722        int numberOfPackagesOptimized = 0;
9723        int numberOfPackagesSkipped = 0;
9724        int numberOfPackagesFailed = 0;
9725        final int numberOfPackagesToDexopt = pkgs.size();
9726
9727        for (PackageParser.Package pkg : pkgs) {
9728            numberOfPackagesVisited++;
9729
9730            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9731                // Copy over initial preopt profiles since we won't get any JIT samples for methods
9732                // that are already compiled.
9733                File profileFile = new File(getPrebuildProfilePath(pkg));
9734                // Copy profile if it exists.
9735                if (profileFile.exists()) {
9736                    try {
9737                        // We could also do this lazily before calling dexopt in
9738                        // PackageDexOptimizer to prevent this happening on first boot. The issue
9739                        // is that we don't have a good way to say "do this only once".
9740                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9741                                pkg.applicationInfo.uid, pkg.packageName)) {
9742                            Log.e(TAG, "Installer failed to copy system profile!");
9743                        }
9744                    } catch (Exception e) {
9745                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9746                                e);
9747                    }
9748                }
9749            }
9750
9751            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9752                if (DEBUG_DEXOPT) {
9753                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9754                }
9755                numberOfPackagesSkipped++;
9756                continue;
9757            }
9758
9759            if (DEBUG_DEXOPT) {
9760                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9761                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9762            }
9763
9764            if (showDialog) {
9765                try {
9766                    ActivityManager.getService().showBootMessage(
9767                            mContext.getResources().getString(R.string.android_upgrading_apk,
9768                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9769                } catch (RemoteException e) {
9770                }
9771                synchronized (mPackages) {
9772                    mDexOptDialogShown = true;
9773                }
9774            }
9775
9776            // If the OTA updates a system app which was previously preopted to a non-preopted state
9777            // the app might end up being verified at runtime. That's because by default the apps
9778            // are verify-profile but for preopted apps there's no profile.
9779            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
9780            // that before the OTA the app was preopted) the app gets compiled with a non-profile
9781            // filter (by default 'quicken').
9782            // Note that at this stage unused apps are already filtered.
9783            if (isSystemApp(pkg) &&
9784                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
9785                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
9786                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
9787            }
9788
9789            // checkProfiles is false to avoid merging profiles during boot which
9790            // might interfere with background compilation (b/28612421).
9791            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9792            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9793            // trade-off worth doing to save boot time work.
9794            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9795            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9796                    pkg.packageName,
9797                    compilerFilter,
9798                    dexoptFlags));
9799
9800            if (pkg.isSystemApp()) {
9801                // Only dexopt shared secondary dex files belonging to system apps to not slow down
9802                // too much boot after an OTA.
9803                int secondaryDexoptFlags = dexoptFlags |
9804                        DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9805                        DexoptOptions.DEXOPT_ONLY_SHARED_DEX;
9806                mDexManager.dexoptSecondaryDex(new DexoptOptions(
9807                        pkg.packageName,
9808                        compilerFilter,
9809                        secondaryDexoptFlags));
9810            }
9811
9812            // TODO(shubhamajmera): Record secondary dexopt stats.
9813            switch (primaryDexOptStaus) {
9814                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9815                    numberOfPackagesOptimized++;
9816                    break;
9817                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9818                    numberOfPackagesSkipped++;
9819                    break;
9820                case PackageDexOptimizer.DEX_OPT_FAILED:
9821                    numberOfPackagesFailed++;
9822                    break;
9823                default:
9824                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9825                    break;
9826            }
9827        }
9828
9829        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9830                numberOfPackagesFailed };
9831    }
9832
9833    @Override
9834    public void notifyPackageUse(String packageName, int reason) {
9835        synchronized (mPackages) {
9836            final int callingUid = Binder.getCallingUid();
9837            final int callingUserId = UserHandle.getUserId(callingUid);
9838            if (getInstantAppPackageName(callingUid) != null) {
9839                if (!isCallerSameApp(packageName, callingUid)) {
9840                    return;
9841                }
9842            } else {
9843                if (isInstantApp(packageName, callingUserId)) {
9844                    return;
9845                }
9846            }
9847            notifyPackageUseLocked(packageName, reason);
9848        }
9849    }
9850
9851    private void notifyPackageUseLocked(String packageName, int reason) {
9852        final PackageParser.Package p = mPackages.get(packageName);
9853        if (p == null) {
9854            return;
9855        }
9856        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9857    }
9858
9859    @Override
9860    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9861            List<String> classPaths, String loaderIsa) {
9862        int userId = UserHandle.getCallingUserId();
9863        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9864        if (ai == null) {
9865            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9866                + loadingPackageName + ", user=" + userId);
9867            return;
9868        }
9869        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9870    }
9871
9872    @Override
9873    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9874            IDexModuleRegisterCallback callback) {
9875        int userId = UserHandle.getCallingUserId();
9876        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9877        DexManager.RegisterDexModuleResult result;
9878        if (ai == null) {
9879            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9880                     " calling user. package=" + packageName + ", user=" + userId);
9881            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9882        } else {
9883            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9884        }
9885
9886        if (callback != null) {
9887            mHandler.post(() -> {
9888                try {
9889                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9890                } catch (RemoteException e) {
9891                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9892                }
9893            });
9894        }
9895    }
9896
9897    /**
9898     * Ask the package manager to perform a dex-opt with the given compiler filter.
9899     *
9900     * Note: exposed only for the shell command to allow moving packages explicitly to a
9901     *       definite state.
9902     */
9903    @Override
9904    public boolean performDexOptMode(String packageName,
9905            boolean checkProfiles, String targetCompilerFilter, boolean force,
9906            boolean bootComplete, String splitName) {
9907        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9908                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9909                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9910        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
9911                splitName, flags));
9912    }
9913
9914    /**
9915     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9916     * secondary dex files belonging to the given package.
9917     *
9918     * Note: exposed only for the shell command to allow moving packages explicitly to a
9919     *       definite state.
9920     */
9921    @Override
9922    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9923            boolean force) {
9924        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9925                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9926                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9927                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9928        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9929    }
9930
9931    /*package*/ boolean performDexOpt(DexoptOptions options) {
9932        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9933            return false;
9934        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9935            return false;
9936        }
9937
9938        if (options.isDexoptOnlySecondaryDex()) {
9939            return mDexManager.dexoptSecondaryDex(options);
9940        } else {
9941            int dexoptStatus = performDexOptWithStatus(options);
9942            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9943        }
9944    }
9945
9946    /**
9947     * Perform dexopt on the given package and return one of following result:
9948     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9949     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9950     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9951     */
9952    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9953        return performDexOptTraced(options);
9954    }
9955
9956    private int performDexOptTraced(DexoptOptions options) {
9957        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9958        try {
9959            return performDexOptInternal(options);
9960        } finally {
9961            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9962        }
9963    }
9964
9965    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9966    // if the package can now be considered up to date for the given filter.
9967    private int performDexOptInternal(DexoptOptions options) {
9968        PackageParser.Package p;
9969        synchronized (mPackages) {
9970            p = mPackages.get(options.getPackageName());
9971            if (p == null) {
9972                // Package could not be found. Report failure.
9973                return PackageDexOptimizer.DEX_OPT_FAILED;
9974            }
9975            mPackageUsage.maybeWriteAsync(mPackages);
9976            mCompilerStats.maybeWriteAsync();
9977        }
9978        long callingId = Binder.clearCallingIdentity();
9979        try {
9980            synchronized (mInstallLock) {
9981                return performDexOptInternalWithDependenciesLI(p, options);
9982            }
9983        } finally {
9984            Binder.restoreCallingIdentity(callingId);
9985        }
9986    }
9987
9988    public ArraySet<String> getOptimizablePackages() {
9989        ArraySet<String> pkgs = new ArraySet<String>();
9990        synchronized (mPackages) {
9991            for (PackageParser.Package p : mPackages.values()) {
9992                if (PackageDexOptimizer.canOptimizePackage(p)) {
9993                    pkgs.add(p.packageName);
9994                }
9995            }
9996        }
9997        return pkgs;
9998    }
9999
10000    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
10001            DexoptOptions options) {
10002        // Select the dex optimizer based on the force parameter.
10003        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
10004        //       allocate an object here.
10005        PackageDexOptimizer pdo = options.isForce()
10006                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
10007                : mPackageDexOptimizer;
10008
10009        // Dexopt all dependencies first. Note: we ignore the return value and march on
10010        // on errors.
10011        // Note that we are going to call performDexOpt on those libraries as many times as
10012        // they are referenced in packages. When we do a batch of performDexOpt (for example
10013        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
10014        // and the first package that uses the library will dexopt it. The
10015        // others will see that the compiled code for the library is up to date.
10016        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
10017        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
10018        if (!deps.isEmpty()) {
10019            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
10020                    options.getCompilerFilter(), options.getSplitName(),
10021                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
10022            for (PackageParser.Package depPackage : deps) {
10023                // TODO: Analyze and investigate if we (should) profile libraries.
10024                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
10025                        getOrCreateCompilerPackageStats(depPackage),
10026                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
10027            }
10028        }
10029        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
10030                getOrCreateCompilerPackageStats(p),
10031                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
10032    }
10033
10034    /**
10035     * Reconcile the information we have about the secondary dex files belonging to
10036     * {@code packagName} and the actual dex files. For all dex files that were
10037     * deleted, update the internal records and delete the generated oat files.
10038     */
10039    @Override
10040    public void reconcileSecondaryDexFiles(String packageName) {
10041        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
10042            return;
10043        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
10044            return;
10045        }
10046        mDexManager.reconcileSecondaryDexFiles(packageName);
10047    }
10048
10049    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
10050    // a reference there.
10051    /*package*/ DexManager getDexManager() {
10052        return mDexManager;
10053    }
10054
10055    /**
10056     * Execute the background dexopt job immediately.
10057     */
10058    @Override
10059    public boolean runBackgroundDexoptJob() {
10060        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
10061            return false;
10062        }
10063        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
10064    }
10065
10066    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
10067        if (p.usesLibraries != null || p.usesOptionalLibraries != null
10068                || p.usesStaticLibraries != null) {
10069            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
10070            Set<String> collectedNames = new HashSet<>();
10071            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
10072
10073            retValue.remove(p);
10074
10075            return retValue;
10076        } else {
10077            return Collections.emptyList();
10078        }
10079    }
10080
10081    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
10082            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
10083        if (!collectedNames.contains(p.packageName)) {
10084            collectedNames.add(p.packageName);
10085            collected.add(p);
10086
10087            if (p.usesLibraries != null) {
10088                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
10089                        null, collected, collectedNames);
10090            }
10091            if (p.usesOptionalLibraries != null) {
10092                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
10093                        null, collected, collectedNames);
10094            }
10095            if (p.usesStaticLibraries != null) {
10096                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
10097                        p.usesStaticLibrariesVersions, collected, collectedNames);
10098            }
10099        }
10100    }
10101
10102    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
10103            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
10104        final int libNameCount = libs.size();
10105        for (int i = 0; i < libNameCount; i++) {
10106            String libName = libs.get(i);
10107            int version = (versions != null && versions.length == libNameCount)
10108                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
10109            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
10110            if (libPkg != null) {
10111                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
10112            }
10113        }
10114    }
10115
10116    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
10117        synchronized (mPackages) {
10118            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
10119            if (libEntry != null) {
10120                return mPackages.get(libEntry.apk);
10121            }
10122            return null;
10123        }
10124    }
10125
10126    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
10127        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10128        if (versionedLib == null) {
10129            return null;
10130        }
10131        return versionedLib.get(version);
10132    }
10133
10134    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
10135        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10136                pkg.staticSharedLibName);
10137        if (versionedLib == null) {
10138            return null;
10139        }
10140        int previousLibVersion = -1;
10141        final int versionCount = versionedLib.size();
10142        for (int i = 0; i < versionCount; i++) {
10143            final int libVersion = versionedLib.keyAt(i);
10144            if (libVersion < pkg.staticSharedLibVersion) {
10145                previousLibVersion = Math.max(previousLibVersion, libVersion);
10146            }
10147        }
10148        if (previousLibVersion >= 0) {
10149            return versionedLib.get(previousLibVersion);
10150        }
10151        return null;
10152    }
10153
10154    public void shutdown() {
10155        mPackageUsage.writeNow(mPackages);
10156        mCompilerStats.writeNow();
10157        mDexManager.writePackageDexUsageNow();
10158    }
10159
10160    @Override
10161    public void dumpProfiles(String packageName) {
10162        PackageParser.Package pkg;
10163        synchronized (mPackages) {
10164            pkg = mPackages.get(packageName);
10165            if (pkg == null) {
10166                throw new IllegalArgumentException("Unknown package: " + packageName);
10167            }
10168        }
10169        /* Only the shell, root, or the app user should be able to dump profiles. */
10170        int callingUid = Binder.getCallingUid();
10171        if (callingUid != Process.SHELL_UID &&
10172            callingUid != Process.ROOT_UID &&
10173            callingUid != pkg.applicationInfo.uid) {
10174            throw new SecurityException("dumpProfiles");
10175        }
10176
10177        synchronized (mInstallLock) {
10178            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
10179            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
10180            try {
10181                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
10182                String codePaths = TextUtils.join(";", allCodePaths);
10183                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
10184            } catch (InstallerException e) {
10185                Slog.w(TAG, "Failed to dump profiles", e);
10186            }
10187            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10188        }
10189    }
10190
10191    @Override
10192    public void forceDexOpt(String packageName) {
10193        enforceSystemOrRoot("forceDexOpt");
10194
10195        PackageParser.Package pkg;
10196        synchronized (mPackages) {
10197            pkg = mPackages.get(packageName);
10198            if (pkg == null) {
10199                throw new IllegalArgumentException("Unknown package: " + packageName);
10200            }
10201        }
10202
10203        synchronized (mInstallLock) {
10204            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
10205
10206            // Whoever is calling forceDexOpt wants a compiled package.
10207            // Don't use profiles since that may cause compilation to be skipped.
10208            final int res = performDexOptInternalWithDependenciesLI(
10209                    pkg,
10210                    new DexoptOptions(packageName,
10211                            getDefaultCompilerFilter(),
10212                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
10213
10214            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10215            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
10216                throw new IllegalStateException("Failed to dexopt: " + res);
10217            }
10218        }
10219    }
10220
10221    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
10222        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
10223            Slog.w(TAG, "Unable to update from " + oldPkg.name
10224                    + " to " + newPkg.packageName
10225                    + ": old package not in system partition");
10226            return false;
10227        } else if (mPackages.get(oldPkg.name) != null) {
10228            Slog.w(TAG, "Unable to update from " + oldPkg.name
10229                    + " to " + newPkg.packageName
10230                    + ": old package still exists");
10231            return false;
10232        }
10233        return true;
10234    }
10235
10236    void removeCodePathLI(File codePath) {
10237        if (codePath.isDirectory()) {
10238            try {
10239                mInstaller.rmPackageDir(codePath.getAbsolutePath());
10240            } catch (InstallerException e) {
10241                Slog.w(TAG, "Failed to remove code path", e);
10242            }
10243        } else {
10244            codePath.delete();
10245        }
10246    }
10247
10248    private int[] resolveUserIds(int userId) {
10249        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
10250    }
10251
10252    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10253        if (pkg == null) {
10254            Slog.wtf(TAG, "Package was null!", new Throwable());
10255            return;
10256        }
10257        clearAppDataLeafLIF(pkg, userId, flags);
10258        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10259        for (int i = 0; i < childCount; i++) {
10260            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10261        }
10262    }
10263
10264    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10265        final PackageSetting ps;
10266        synchronized (mPackages) {
10267            ps = mSettings.mPackages.get(pkg.packageName);
10268        }
10269        for (int realUserId : resolveUserIds(userId)) {
10270            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10271            try {
10272                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10273                        ceDataInode);
10274            } catch (InstallerException e) {
10275                Slog.w(TAG, String.valueOf(e));
10276            }
10277        }
10278    }
10279
10280    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10281        if (pkg == null) {
10282            Slog.wtf(TAG, "Package was null!", new Throwable());
10283            return;
10284        }
10285        destroyAppDataLeafLIF(pkg, userId, flags);
10286        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10287        for (int i = 0; i < childCount; i++) {
10288            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10289        }
10290    }
10291
10292    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10293        final PackageSetting ps;
10294        synchronized (mPackages) {
10295            ps = mSettings.mPackages.get(pkg.packageName);
10296        }
10297        for (int realUserId : resolveUserIds(userId)) {
10298            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10299            try {
10300                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10301                        ceDataInode);
10302            } catch (InstallerException e) {
10303                Slog.w(TAG, String.valueOf(e));
10304            }
10305            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
10306        }
10307    }
10308
10309    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
10310        if (pkg == null) {
10311            Slog.wtf(TAG, "Package was null!", new Throwable());
10312            return;
10313        }
10314        destroyAppProfilesLeafLIF(pkg);
10315        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10316        for (int i = 0; i < childCount; i++) {
10317            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
10318        }
10319    }
10320
10321    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
10322        try {
10323            mInstaller.destroyAppProfiles(pkg.packageName);
10324        } catch (InstallerException e) {
10325            Slog.w(TAG, String.valueOf(e));
10326        }
10327    }
10328
10329    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
10330        if (pkg == null) {
10331            Slog.wtf(TAG, "Package was null!", new Throwable());
10332            return;
10333        }
10334        clearAppProfilesLeafLIF(pkg);
10335        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10336        for (int i = 0; i < childCount; i++) {
10337            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
10338        }
10339    }
10340
10341    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
10342        try {
10343            mInstaller.clearAppProfiles(pkg.packageName);
10344        } catch (InstallerException e) {
10345            Slog.w(TAG, String.valueOf(e));
10346        }
10347    }
10348
10349    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
10350            long lastUpdateTime) {
10351        // Set parent install/update time
10352        PackageSetting ps = (PackageSetting) pkg.mExtras;
10353        if (ps != null) {
10354            ps.firstInstallTime = firstInstallTime;
10355            ps.lastUpdateTime = lastUpdateTime;
10356        }
10357        // Set children install/update time
10358        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10359        for (int i = 0; i < childCount; i++) {
10360            PackageParser.Package childPkg = pkg.childPackages.get(i);
10361            ps = (PackageSetting) childPkg.mExtras;
10362            if (ps != null) {
10363                ps.firstInstallTime = firstInstallTime;
10364                ps.lastUpdateTime = lastUpdateTime;
10365            }
10366        }
10367    }
10368
10369    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
10370            PackageParser.Package changingLib) {
10371        if (file.path != null) {
10372            usesLibraryFiles.add(file.path);
10373            return;
10374        }
10375        PackageParser.Package p = mPackages.get(file.apk);
10376        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
10377            // If we are doing this while in the middle of updating a library apk,
10378            // then we need to make sure to use that new apk for determining the
10379            // dependencies here.  (We haven't yet finished committing the new apk
10380            // to the package manager state.)
10381            if (p == null || p.packageName.equals(changingLib.packageName)) {
10382                p = changingLib;
10383            }
10384        }
10385        if (p != null) {
10386            usesLibraryFiles.addAll(p.getAllCodePaths());
10387            if (p.usesLibraryFiles != null) {
10388                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
10389            }
10390        }
10391    }
10392
10393    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
10394            PackageParser.Package changingLib) throws PackageManagerException {
10395        if (pkg == null) {
10396            return;
10397        }
10398        ArraySet<String> usesLibraryFiles = null;
10399        if (pkg.usesLibraries != null) {
10400            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
10401                    null, null, pkg.packageName, changingLib, true,
10402                    pkg.applicationInfo.targetSdkVersion, null);
10403        }
10404        if (pkg.usesStaticLibraries != null) {
10405            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
10406                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
10407                    pkg.packageName, changingLib, true,
10408                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
10409        }
10410        if (pkg.usesOptionalLibraries != null) {
10411            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
10412                    null, null, pkg.packageName, changingLib, false,
10413                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
10414        }
10415        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
10416            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
10417        } else {
10418            pkg.usesLibraryFiles = null;
10419        }
10420    }
10421
10422    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
10423            @Nullable int[] requiredVersions, @Nullable String[][] requiredCertDigests,
10424            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
10425            boolean required, int targetSdk, @Nullable ArraySet<String> outUsedLibraries)
10426            throws PackageManagerException {
10427        final int libCount = requestedLibraries.size();
10428        for (int i = 0; i < libCount; i++) {
10429            final String libName = requestedLibraries.get(i);
10430            final int libVersion = requiredVersions != null ? requiredVersions[i]
10431                    : SharedLibraryInfo.VERSION_UNDEFINED;
10432            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
10433            if (libEntry == null) {
10434                if (required) {
10435                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10436                            "Package " + packageName + " requires unavailable shared library "
10437                                    + libName + "; failing!");
10438                } else if (DEBUG_SHARED_LIBRARIES) {
10439                    Slog.i(TAG, "Package " + packageName
10440                            + " desires unavailable shared library "
10441                            + libName + "; ignoring!");
10442                }
10443            } else {
10444                if (requiredVersions != null && requiredCertDigests != null) {
10445                    if (libEntry.info.getVersion() != requiredVersions[i]) {
10446                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10447                            "Package " + packageName + " requires unavailable static shared"
10448                                    + " library " + libName + " version "
10449                                    + libEntry.info.getVersion() + "; failing!");
10450                    }
10451
10452                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
10453                    if (libPkg == null) {
10454                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10455                                "Package " + packageName + " requires unavailable static shared"
10456                                        + " library; failing!");
10457                    }
10458
10459                    final String[] expectedCertDigests = requiredCertDigests[i];
10460                    // For apps targeting O MR1 we require explicit enumeration of all certs.
10461                    final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
10462                            ? PackageUtils.computeSignaturesSha256Digests(libPkg.mSignatures)
10463                            : PackageUtils.computeSignaturesSha256Digests(
10464                                    new Signature[]{libPkg.mSignatures[0]});
10465
10466                    // Take a shortcut if sizes don't match. Note that if an app doesn't
10467                    // target O we don't parse the "additional-certificate" tags similarly
10468                    // how we only consider all certs only for apps targeting O (see above).
10469                    // Therefore, the size check is safe to make.
10470                    if (expectedCertDigests.length != libCertDigests.length) {
10471                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10472                                "Package " + packageName + " requires differently signed" +
10473                                        " static sDexLoadReporter.java:45.19hared library; failing!");
10474                    }
10475
10476                    // Use a predictable order as signature order may vary
10477                    Arrays.sort(libCertDigests);
10478                    Arrays.sort(expectedCertDigests);
10479
10480                    final int certCount = libCertDigests.length;
10481                    for (int j = 0; j < certCount; j++) {
10482                        if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
10483                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10484                                    "Package " + packageName + " requires differently signed" +
10485                                            " static shared library; failing!");
10486                        }
10487                    }
10488                }
10489
10490                if (outUsedLibraries == null) {
10491                    outUsedLibraries = new ArraySet<>();
10492                }
10493                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
10494            }
10495        }
10496        return outUsedLibraries;
10497    }
10498
10499    private static boolean hasString(List<String> list, List<String> which) {
10500        if (list == null) {
10501            return false;
10502        }
10503        for (int i=list.size()-1; i>=0; i--) {
10504            for (int j=which.size()-1; j>=0; j--) {
10505                if (which.get(j).equals(list.get(i))) {
10506                    return true;
10507                }
10508            }
10509        }
10510        return false;
10511    }
10512
10513    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
10514            PackageParser.Package changingPkg) {
10515        ArrayList<PackageParser.Package> res = null;
10516        for (PackageParser.Package pkg : mPackages.values()) {
10517            if (changingPkg != null
10518                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
10519                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
10520                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
10521                            changingPkg.staticSharedLibName)) {
10522                return null;
10523            }
10524            if (res == null) {
10525                res = new ArrayList<>();
10526            }
10527            res.add(pkg);
10528            try {
10529                updateSharedLibrariesLPr(pkg, changingPkg);
10530            } catch (PackageManagerException e) {
10531                // If a system app update or an app and a required lib missing we
10532                // delete the package and for updated system apps keep the data as
10533                // it is better for the user to reinstall than to be in an limbo
10534                // state. Also libs disappearing under an app should never happen
10535                // - just in case.
10536                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
10537                    final int flags = pkg.isUpdatedSystemApp()
10538                            ? PackageManager.DELETE_KEEP_DATA : 0;
10539                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
10540                            flags , null, true, null);
10541                }
10542                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
10543            }
10544        }
10545        return res;
10546    }
10547
10548    /**
10549     * Derive the value of the {@code cpuAbiOverride} based on the provided
10550     * value and an optional stored value from the package settings.
10551     */
10552    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
10553        String cpuAbiOverride = null;
10554
10555        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10556            cpuAbiOverride = null;
10557        } else if (abiOverride != null) {
10558            cpuAbiOverride = abiOverride;
10559        } else if (settings != null) {
10560            cpuAbiOverride = settings.cpuAbiOverrideString;
10561        }
10562
10563        return cpuAbiOverride;
10564    }
10565
10566    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10567            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10568                    throws PackageManagerException {
10569        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10570        // If the package has children and this is the first dive in the function
10571        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10572        // whether all packages (parent and children) would be successfully scanned
10573        // before the actual scan since scanning mutates internal state and we want
10574        // to atomically install the package and its children.
10575        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10576            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10577                scanFlags |= SCAN_CHECK_ONLY;
10578            }
10579        } else {
10580            scanFlags &= ~SCAN_CHECK_ONLY;
10581        }
10582
10583        final PackageParser.Package scannedPkg;
10584        try {
10585            // Scan the parent
10586            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10587            // Scan the children
10588            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10589            for (int i = 0; i < childCount; i++) {
10590                PackageParser.Package childPkg = pkg.childPackages.get(i);
10591                scanPackageLI(childPkg, policyFlags,
10592                        scanFlags, currentTime, user);
10593            }
10594        } finally {
10595            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10596        }
10597
10598        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10599            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10600        }
10601
10602        return scannedPkg;
10603    }
10604
10605    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10606            int scanFlags, long currentTime, @Nullable UserHandle user)
10607                    throws PackageManagerException {
10608        boolean success = false;
10609        try {
10610            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10611                    currentTime, user);
10612            success = true;
10613            return res;
10614        } finally {
10615            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10616                // DELETE_DATA_ON_FAILURES is only used by frozen paths
10617                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10618                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10619                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10620            }
10621        }
10622    }
10623
10624    /**
10625     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10626     */
10627    private static boolean apkHasCode(String fileName) {
10628        StrictJarFile jarFile = null;
10629        try {
10630            jarFile = new StrictJarFile(fileName,
10631                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10632            return jarFile.findEntry("classes.dex") != null;
10633        } catch (IOException ignore) {
10634        } finally {
10635            try {
10636                if (jarFile != null) {
10637                    jarFile.close();
10638                }
10639            } catch (IOException ignore) {}
10640        }
10641        return false;
10642    }
10643
10644    /**
10645     * Enforces code policy for the package. This ensures that if an APK has
10646     * declared hasCode="true" in its manifest that the APK actually contains
10647     * code.
10648     *
10649     * @throws PackageManagerException If bytecode could not be found when it should exist
10650     */
10651    private static void assertCodePolicy(PackageParser.Package pkg)
10652            throws PackageManagerException {
10653        final boolean shouldHaveCode =
10654                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10655        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10656            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10657                    "Package " + pkg.baseCodePath + " code is missing");
10658        }
10659
10660        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10661            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10662                final boolean splitShouldHaveCode =
10663                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10664                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10665                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10666                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10667                }
10668            }
10669        }
10670    }
10671
10672    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10673            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10674                    throws PackageManagerException {
10675        if (DEBUG_PACKAGE_SCANNING) {
10676            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10677                Log.d(TAG, "Scanning package " + pkg.packageName);
10678        }
10679
10680        applyPolicy(pkg, policyFlags);
10681
10682        assertPackageIsValid(pkg, policyFlags, scanFlags);
10683
10684        // Initialize package source and resource directories
10685        final File scanFile = new File(pkg.codePath);
10686        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10687        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10688
10689        SharedUserSetting suid = null;
10690        PackageSetting pkgSetting = null;
10691
10692        // Getting the package setting may have a side-effect, so if we
10693        // are only checking if scan would succeed, stash a copy of the
10694        // old setting to restore at the end.
10695        PackageSetting nonMutatedPs = null;
10696
10697        // We keep references to the derived CPU Abis from settings in oder to reuse
10698        // them in the case where we're not upgrading or booting for the first time.
10699        String primaryCpuAbiFromSettings = null;
10700        String secondaryCpuAbiFromSettings = null;
10701
10702        // writer
10703        synchronized (mPackages) {
10704            if (pkg.mSharedUserId != null) {
10705                // SIDE EFFECTS; may potentially allocate a new shared user
10706                suid = mSettings.getSharedUserLPw(
10707                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10708                if (DEBUG_PACKAGE_SCANNING) {
10709                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10710                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10711                                + "): packages=" + suid.packages);
10712                }
10713            }
10714
10715            // Check if we are renaming from an original package name.
10716            PackageSetting origPackage = null;
10717            String realName = null;
10718            if (pkg.mOriginalPackages != null) {
10719                // This package may need to be renamed to a previously
10720                // installed name.  Let's check on that...
10721                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10722                if (pkg.mOriginalPackages.contains(renamed)) {
10723                    // This package had originally been installed as the
10724                    // original name, and we have already taken care of
10725                    // transitioning to the new one.  Just update the new
10726                    // one to continue using the old name.
10727                    realName = pkg.mRealPackage;
10728                    if (!pkg.packageName.equals(renamed)) {
10729                        // Callers into this function may have already taken
10730                        // care of renaming the package; only do it here if
10731                        // it is not already done.
10732                        pkg.setPackageName(renamed);
10733                    }
10734                } else {
10735                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10736                        if ((origPackage = mSettings.getPackageLPr(
10737                                pkg.mOriginalPackages.get(i))) != null) {
10738                            // We do have the package already installed under its
10739                            // original name...  should we use it?
10740                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10741                                // New package is not compatible with original.
10742                                origPackage = null;
10743                                continue;
10744                            } else if (origPackage.sharedUser != null) {
10745                                // Make sure uid is compatible between packages.
10746                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10747                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10748                                            + " to " + pkg.packageName + ": old uid "
10749                                            + origPackage.sharedUser.name
10750                                            + " differs from " + pkg.mSharedUserId);
10751                                    origPackage = null;
10752                                    continue;
10753                                }
10754                                // TODO: Add case when shared user id is added [b/28144775]
10755                            } else {
10756                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10757                                        + pkg.packageName + " to old name " + origPackage.name);
10758                            }
10759                            break;
10760                        }
10761                    }
10762                }
10763            }
10764
10765            if (mTransferedPackages.contains(pkg.packageName)) {
10766                Slog.w(TAG, "Package " + pkg.packageName
10767                        + " was transferred to another, but its .apk remains");
10768            }
10769
10770            // See comments in nonMutatedPs declaration
10771            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10772                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10773                if (foundPs != null) {
10774                    nonMutatedPs = new PackageSetting(foundPs);
10775                }
10776            }
10777
10778            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10779                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10780                if (foundPs != null) {
10781                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10782                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10783                }
10784            }
10785
10786            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10787            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10788                PackageManagerService.reportSettingsProblem(Log.WARN,
10789                        "Package " + pkg.packageName + " shared user changed from "
10790                                + (pkgSetting.sharedUser != null
10791                                        ? pkgSetting.sharedUser.name : "<nothing>")
10792                                + " to "
10793                                + (suid != null ? suid.name : "<nothing>")
10794                                + "; replacing with new");
10795                pkgSetting = null;
10796            }
10797            final PackageSetting oldPkgSetting =
10798                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10799            final PackageSetting disabledPkgSetting =
10800                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10801
10802            String[] usesStaticLibraries = null;
10803            if (pkg.usesStaticLibraries != null) {
10804                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10805                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10806            }
10807
10808            if (pkgSetting == null) {
10809                final String parentPackageName = (pkg.parentPackage != null)
10810                        ? pkg.parentPackage.packageName : null;
10811                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10812                final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10813                // REMOVE SharedUserSetting from method; update in a separate call
10814                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10815                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10816                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10817                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10818                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10819                        true /*allowInstall*/, instantApp, virtualPreload,
10820                        parentPackageName, pkg.getChildPackageNames(),
10821                        UserManagerService.getInstance(), usesStaticLibraries,
10822                        pkg.usesStaticLibrariesVersions);
10823                // SIDE EFFECTS; updates system state; move elsewhere
10824                if (origPackage != null) {
10825                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10826                }
10827                mSettings.addUserToSettingLPw(pkgSetting);
10828            } else {
10829                // REMOVE SharedUserSetting from method; update in a separate call.
10830                //
10831                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10832                // secondaryCpuAbi are not known at this point so we always update them
10833                // to null here, only to reset them at a later point.
10834                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10835                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10836                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10837                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10838                        UserManagerService.getInstance(), usesStaticLibraries,
10839                        pkg.usesStaticLibrariesVersions);
10840            }
10841            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10842            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10843
10844            // SIDE EFFECTS; modifies system state; move elsewhere
10845            if (pkgSetting.origPackage != null) {
10846                // If we are first transitioning from an original package,
10847                // fix up the new package's name now.  We need to do this after
10848                // looking up the package under its new name, so getPackageLP
10849                // can take care of fiddling things correctly.
10850                pkg.setPackageName(origPackage.name);
10851
10852                // File a report about this.
10853                String msg = "New package " + pkgSetting.realName
10854                        + " renamed to replace old package " + pkgSetting.name;
10855                reportSettingsProblem(Log.WARN, msg);
10856
10857                // Make a note of it.
10858                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10859                    mTransferedPackages.add(origPackage.name);
10860                }
10861
10862                // No longer need to retain this.
10863                pkgSetting.origPackage = null;
10864            }
10865
10866            // SIDE EFFECTS; modifies system state; move elsewhere
10867            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10868                // Make a note of it.
10869                mTransferedPackages.add(pkg.packageName);
10870            }
10871
10872            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10873                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10874            }
10875
10876            if ((scanFlags & SCAN_BOOTING) == 0
10877                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10878                // Check all shared libraries and map to their actual file path.
10879                // We only do this here for apps not on a system dir, because those
10880                // are the only ones that can fail an install due to this.  We
10881                // will take care of the system apps by updating all of their
10882                // library paths after the scan is done. Also during the initial
10883                // scan don't update any libs as we do this wholesale after all
10884                // apps are scanned to avoid dependency based scanning.
10885                updateSharedLibrariesLPr(pkg, null);
10886            }
10887
10888            if (mFoundPolicyFile) {
10889                SELinuxMMAC.assignSeInfoValue(pkg);
10890            }
10891            pkg.applicationInfo.uid = pkgSetting.appId;
10892            pkg.mExtras = pkgSetting;
10893
10894
10895            // Static shared libs have same package with different versions where
10896            // we internally use a synthetic package name to allow multiple versions
10897            // of the same package, therefore we need to compare signatures against
10898            // the package setting for the latest library version.
10899            PackageSetting signatureCheckPs = pkgSetting;
10900            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10901                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10902                if (libraryEntry != null) {
10903                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10904                }
10905            }
10906
10907            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10908                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10909                    // We just determined the app is signed correctly, so bring
10910                    // over the latest parsed certs.
10911                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10912                } else {
10913                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10914                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10915                                "Package " + pkg.packageName + " upgrade keys do not match the "
10916                                + "previously installed version");
10917                    } else {
10918                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10919                        String msg = "System package " + pkg.packageName
10920                                + " signature changed; retaining data.";
10921                        reportSettingsProblem(Log.WARN, msg);
10922                    }
10923                }
10924            } else {
10925                try {
10926                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10927                    verifySignaturesLP(signatureCheckPs, pkg);
10928                    // We just determined the app is signed correctly, so bring
10929                    // over the latest parsed certs.
10930                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10931                } catch (PackageManagerException e) {
10932                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10933                        throw e;
10934                    }
10935                    // The signature has changed, but this package is in the system
10936                    // image...  let's recover!
10937                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10938                    // However...  if this package is part of a shared user, but it
10939                    // doesn't match the signature of the shared user, let's fail.
10940                    // What this means is that you can't change the signatures
10941                    // associated with an overall shared user, which doesn't seem all
10942                    // that unreasonable.
10943                    if (signatureCheckPs.sharedUser != null) {
10944                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10945                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10946                            throw new PackageManagerException(
10947                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10948                                    "Signature mismatch for shared user: "
10949                                            + pkgSetting.sharedUser);
10950                        }
10951                    }
10952                    // File a report about this.
10953                    String msg = "System package " + pkg.packageName
10954                            + " signature changed; retaining data.";
10955                    reportSettingsProblem(Log.WARN, msg);
10956                }
10957            }
10958
10959            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10960                // This package wants to adopt ownership of permissions from
10961                // another package.
10962                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10963                    final String origName = pkg.mAdoptPermissions.get(i);
10964                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10965                    if (orig != null) {
10966                        if (verifyPackageUpdateLPr(orig, pkg)) {
10967                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10968                                    + pkg.packageName);
10969                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10970                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
10971                        }
10972                    }
10973                }
10974            }
10975        }
10976
10977        pkg.applicationInfo.processName = fixProcessName(
10978                pkg.applicationInfo.packageName,
10979                pkg.applicationInfo.processName);
10980
10981        if (pkg != mPlatformPackage) {
10982            // Get all of our default paths setup
10983            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10984        }
10985
10986        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10987
10988        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10989            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10990                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10991                final boolean extractNativeLibs = !pkg.isLibrary();
10992                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
10993                        mAppLib32InstallDir);
10994                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10995
10996                // Some system apps still use directory structure for native libraries
10997                // in which case we might end up not detecting abi solely based on apk
10998                // structure. Try to detect abi based on directory structure.
10999                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
11000                        pkg.applicationInfo.primaryCpuAbi == null) {
11001                    setBundledAppAbisAndRoots(pkg, pkgSetting);
11002                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
11003                }
11004            } else {
11005                // This is not a first boot or an upgrade, don't bother deriving the
11006                // ABI during the scan. Instead, trust the value that was stored in the
11007                // package setting.
11008                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
11009                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
11010
11011                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
11012
11013                if (DEBUG_ABI_SELECTION) {
11014                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
11015                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
11016                        pkg.applicationInfo.secondaryCpuAbi);
11017                }
11018            }
11019        } else {
11020            if ((scanFlags & SCAN_MOVE) != 0) {
11021                // We haven't run dex-opt for this move (since we've moved the compiled output too)
11022                // but we already have this packages package info in the PackageSetting. We just
11023                // use that and derive the native library path based on the new codepath.
11024                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
11025                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
11026            }
11027
11028            // Set native library paths again. For moves, the path will be updated based on the
11029            // ABIs we've determined above. For non-moves, the path will be updated based on the
11030            // ABIs we determined during compilation, but the path will depend on the final
11031            // package path (after the rename away from the stage path).
11032            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
11033        }
11034
11035        // This is a special case for the "system" package, where the ABI is
11036        // dictated by the zygote configuration (and init.rc). We should keep track
11037        // of this ABI so that we can deal with "normal" applications that run under
11038        // the same UID correctly.
11039        if (mPlatformPackage == pkg) {
11040            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
11041                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
11042        }
11043
11044        // If there's a mismatch between the abi-override in the package setting
11045        // and the abiOverride specified for the install. Warn about this because we
11046        // would've already compiled the app without taking the package setting into
11047        // account.
11048        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
11049            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
11050                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
11051                        " for package " + pkg.packageName);
11052            }
11053        }
11054
11055        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11056        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11057        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
11058
11059        // Copy the derived override back to the parsed package, so that we can
11060        // update the package settings accordingly.
11061        pkg.cpuAbiOverride = cpuAbiOverride;
11062
11063        if (DEBUG_ABI_SELECTION) {
11064            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
11065                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
11066                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
11067        }
11068
11069        // Push the derived path down into PackageSettings so we know what to
11070        // clean up at uninstall time.
11071        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
11072
11073        if (DEBUG_ABI_SELECTION) {
11074            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
11075                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
11076                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
11077        }
11078
11079        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
11080        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
11081            // We don't do this here during boot because we can do it all
11082            // at once after scanning all existing packages.
11083            //
11084            // We also do this *before* we perform dexopt on this package, so that
11085            // we can avoid redundant dexopts, and also to make sure we've got the
11086            // code and package path correct.
11087            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
11088        }
11089
11090        if (mFactoryTest && pkg.requestedPermissions.contains(
11091                android.Manifest.permission.FACTORY_TEST)) {
11092            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
11093        }
11094
11095        if (isSystemApp(pkg)) {
11096            pkgSetting.isOrphaned = true;
11097        }
11098
11099        // Take care of first install / last update times.
11100        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
11101        if (currentTime != 0) {
11102            if (pkgSetting.firstInstallTime == 0) {
11103                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
11104            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
11105                pkgSetting.lastUpdateTime = currentTime;
11106            }
11107        } else if (pkgSetting.firstInstallTime == 0) {
11108            // We need *something*.  Take time time stamp of the file.
11109            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
11110        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
11111            if (scanFileTime != pkgSetting.timeStamp) {
11112                // A package on the system image has changed; consider this
11113                // to be an update.
11114                pkgSetting.lastUpdateTime = scanFileTime;
11115            }
11116        }
11117        pkgSetting.setTimeStamp(scanFileTime);
11118
11119        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
11120            if (nonMutatedPs != null) {
11121                synchronized (mPackages) {
11122                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
11123                }
11124            }
11125        } else {
11126            final int userId = user == null ? 0 : user.getIdentifier();
11127            // Modify state for the given package setting
11128            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
11129                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
11130            if (pkgSetting.getInstantApp(userId)) {
11131                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
11132            }
11133        }
11134        return pkg;
11135    }
11136
11137    /**
11138     * Applies policy to the parsed package based upon the given policy flags.
11139     * Ensures the package is in a good state.
11140     * <p>
11141     * Implementation detail: This method must NOT have any side effect. It would
11142     * ideally be static, but, it requires locks to read system state.
11143     */
11144    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
11145        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
11146            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
11147            if (pkg.applicationInfo.isDirectBootAware()) {
11148                // we're direct boot aware; set for all components
11149                for (PackageParser.Service s : pkg.services) {
11150                    s.info.encryptionAware = s.info.directBootAware = true;
11151                }
11152                for (PackageParser.Provider p : pkg.providers) {
11153                    p.info.encryptionAware = p.info.directBootAware = true;
11154                }
11155                for (PackageParser.Activity a : pkg.activities) {
11156                    a.info.encryptionAware = a.info.directBootAware = true;
11157                }
11158                for (PackageParser.Activity r : pkg.receivers) {
11159                    r.info.encryptionAware = r.info.directBootAware = true;
11160                }
11161            }
11162            if (compressedFileExists(pkg.codePath)) {
11163                pkg.isStub = true;
11164            }
11165        } else {
11166            // Only allow system apps to be flagged as core apps.
11167            pkg.coreApp = false;
11168            // clear flags not applicable to regular apps
11169            pkg.applicationInfo.privateFlags &=
11170                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
11171            pkg.applicationInfo.privateFlags &=
11172                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
11173        }
11174        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
11175
11176        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
11177            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
11178        }
11179
11180        if (!isSystemApp(pkg)) {
11181            // Only system apps can use these features.
11182            pkg.mOriginalPackages = null;
11183            pkg.mRealPackage = null;
11184            pkg.mAdoptPermissions = null;
11185        }
11186    }
11187
11188    /**
11189     * Asserts the parsed package is valid according to the given policy. If the
11190     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
11191     * <p>
11192     * Implementation detail: This method must NOT have any side effects. It would
11193     * ideally be static, but, it requires locks to read system state.
11194     *
11195     * @throws PackageManagerException If the package fails any of the validation checks
11196     */
11197    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
11198            throws PackageManagerException {
11199        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
11200            assertCodePolicy(pkg);
11201        }
11202
11203        if (pkg.applicationInfo.getCodePath() == null ||
11204                pkg.applicationInfo.getResourcePath() == null) {
11205            // Bail out. The resource and code paths haven't been set.
11206            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
11207                    "Code and resource paths haven't been set correctly");
11208        }
11209
11210        // Make sure we're not adding any bogus keyset info
11211        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11212        ksms.assertScannedPackageValid(pkg);
11213
11214        synchronized (mPackages) {
11215            // The special "android" package can only be defined once
11216            if (pkg.packageName.equals("android")) {
11217                if (mAndroidApplication != null) {
11218                    Slog.w(TAG, "*************************************************");
11219                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
11220                    Slog.w(TAG, " codePath=" + pkg.codePath);
11221                    Slog.w(TAG, "*************************************************");
11222                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11223                            "Core android package being redefined.  Skipping.");
11224                }
11225            }
11226
11227            // A package name must be unique; don't allow duplicates
11228            if (mPackages.containsKey(pkg.packageName)) {
11229                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11230                        "Application package " + pkg.packageName
11231                        + " already installed.  Skipping duplicate.");
11232            }
11233
11234            if (pkg.applicationInfo.isStaticSharedLibrary()) {
11235                // Static libs have a synthetic package name containing the version
11236                // but we still want the base name to be unique.
11237                if (mPackages.containsKey(pkg.manifestPackageName)) {
11238                    throw new PackageManagerException(
11239                            "Duplicate static shared lib provider package");
11240                }
11241
11242                // Static shared libraries should have at least O target SDK
11243                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
11244                    throw new PackageManagerException(
11245                            "Packages declaring static-shared libs must target O SDK or higher");
11246                }
11247
11248                // Package declaring static a shared lib cannot be instant apps
11249                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11250                    throw new PackageManagerException(
11251                            "Packages declaring static-shared libs cannot be instant apps");
11252                }
11253
11254                // Package declaring static a shared lib cannot be renamed since the package
11255                // name is synthetic and apps can't code around package manager internals.
11256                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
11257                    throw new PackageManagerException(
11258                            "Packages declaring static-shared libs cannot be renamed");
11259                }
11260
11261                // Package declaring static a shared lib cannot declare child packages
11262                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
11263                    throw new PackageManagerException(
11264                            "Packages declaring static-shared libs cannot have child packages");
11265                }
11266
11267                // Package declaring static a shared lib cannot declare dynamic libs
11268                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
11269                    throw new PackageManagerException(
11270                            "Packages declaring static-shared libs cannot declare dynamic libs");
11271                }
11272
11273                // Package declaring static a shared lib cannot declare shared users
11274                if (pkg.mSharedUserId != null) {
11275                    throw new PackageManagerException(
11276                            "Packages declaring static-shared libs cannot declare shared users");
11277                }
11278
11279                // Static shared libs cannot declare activities
11280                if (!pkg.activities.isEmpty()) {
11281                    throw new PackageManagerException(
11282                            "Static shared libs cannot declare activities");
11283                }
11284
11285                // Static shared libs cannot declare services
11286                if (!pkg.services.isEmpty()) {
11287                    throw new PackageManagerException(
11288                            "Static shared libs cannot declare services");
11289                }
11290
11291                // Static shared libs cannot declare providers
11292                if (!pkg.providers.isEmpty()) {
11293                    throw new PackageManagerException(
11294                            "Static shared libs cannot declare content providers");
11295                }
11296
11297                // Static shared libs cannot declare receivers
11298                if (!pkg.receivers.isEmpty()) {
11299                    throw new PackageManagerException(
11300                            "Static shared libs cannot declare broadcast receivers");
11301                }
11302
11303                // Static shared libs cannot declare permission groups
11304                if (!pkg.permissionGroups.isEmpty()) {
11305                    throw new PackageManagerException(
11306                            "Static shared libs cannot declare permission groups");
11307                }
11308
11309                // Static shared libs cannot declare permissions
11310                if (!pkg.permissions.isEmpty()) {
11311                    throw new PackageManagerException(
11312                            "Static shared libs cannot declare permissions");
11313                }
11314
11315                // Static shared libs cannot declare protected broadcasts
11316                if (pkg.protectedBroadcasts != null) {
11317                    throw new PackageManagerException(
11318                            "Static shared libs cannot declare protected broadcasts");
11319                }
11320
11321                // Static shared libs cannot be overlay targets
11322                if (pkg.mOverlayTarget != null) {
11323                    throw new PackageManagerException(
11324                            "Static shared libs cannot be overlay targets");
11325                }
11326
11327                // The version codes must be ordered as lib versions
11328                int minVersionCode = Integer.MIN_VALUE;
11329                int maxVersionCode = Integer.MAX_VALUE;
11330
11331                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
11332                        pkg.staticSharedLibName);
11333                if (versionedLib != null) {
11334                    final int versionCount = versionedLib.size();
11335                    for (int i = 0; i < versionCount; i++) {
11336                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
11337                        final int libVersionCode = libInfo.getDeclaringPackage()
11338                                .getVersionCode();
11339                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
11340                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
11341                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
11342                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
11343                        } else {
11344                            minVersionCode = maxVersionCode = libVersionCode;
11345                            break;
11346                        }
11347                    }
11348                }
11349                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
11350                    throw new PackageManagerException("Static shared"
11351                            + " lib version codes must be ordered as lib versions");
11352                }
11353            }
11354
11355            // Only privileged apps and updated privileged apps can add child packages.
11356            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
11357                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
11358                    throw new PackageManagerException("Only privileged apps can add child "
11359                            + "packages. Ignoring package " + pkg.packageName);
11360                }
11361                final int childCount = pkg.childPackages.size();
11362                for (int i = 0; i < childCount; i++) {
11363                    PackageParser.Package childPkg = pkg.childPackages.get(i);
11364                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
11365                            childPkg.packageName)) {
11366                        throw new PackageManagerException("Can't override child of "
11367                                + "another disabled app. Ignoring package " + pkg.packageName);
11368                    }
11369                }
11370            }
11371
11372            // If we're only installing presumed-existing packages, require that the
11373            // scanned APK is both already known and at the path previously established
11374            // for it.  Previously unknown packages we pick up normally, but if we have an
11375            // a priori expectation about this package's install presence, enforce it.
11376            // With a singular exception for new system packages. When an OTA contains
11377            // a new system package, we allow the codepath to change from a system location
11378            // to the user-installed location. If we don't allow this change, any newer,
11379            // user-installed version of the application will be ignored.
11380            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
11381                if (mExpectingBetter.containsKey(pkg.packageName)) {
11382                    logCriticalInfo(Log.WARN,
11383                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
11384                } else {
11385                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
11386                    if (known != null) {
11387                        if (DEBUG_PACKAGE_SCANNING) {
11388                            Log.d(TAG, "Examining " + pkg.codePath
11389                                    + " and requiring known paths " + known.codePathString
11390                                    + " & " + known.resourcePathString);
11391                        }
11392                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
11393                                || !pkg.applicationInfo.getResourcePath().equals(
11394                                        known.resourcePathString)) {
11395                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
11396                                    "Application package " + pkg.packageName
11397                                    + " found at " + pkg.applicationInfo.getCodePath()
11398                                    + " but expected at " + known.codePathString
11399                                    + "; ignoring.");
11400                        }
11401                    }
11402                }
11403            }
11404
11405            // Verify that this new package doesn't have any content providers
11406            // that conflict with existing packages.  Only do this if the
11407            // package isn't already installed, since we don't want to break
11408            // things that are installed.
11409            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
11410                final int N = pkg.providers.size();
11411                int i;
11412                for (i=0; i<N; i++) {
11413                    PackageParser.Provider p = pkg.providers.get(i);
11414                    if (p.info.authority != null) {
11415                        String names[] = p.info.authority.split(";");
11416                        for (int j = 0; j < names.length; j++) {
11417                            if (mProvidersByAuthority.containsKey(names[j])) {
11418                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11419                                final String otherPackageName =
11420                                        ((other != null && other.getComponentName() != null) ?
11421                                                other.getComponentName().getPackageName() : "?");
11422                                throw new PackageManagerException(
11423                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11424                                        "Can't install because provider name " + names[j]
11425                                                + " (in package " + pkg.applicationInfo.packageName
11426                                                + ") is already used by " + otherPackageName);
11427                            }
11428                        }
11429                    }
11430                }
11431            }
11432        }
11433    }
11434
11435    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
11436            int type, String declaringPackageName, int declaringVersionCode) {
11437        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11438        if (versionedLib == null) {
11439            versionedLib = new SparseArray<>();
11440            mSharedLibraries.put(name, versionedLib);
11441            if (type == SharedLibraryInfo.TYPE_STATIC) {
11442                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11443            }
11444        } else if (versionedLib.indexOfKey(version) >= 0) {
11445            return false;
11446        }
11447        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11448                version, type, declaringPackageName, declaringVersionCode);
11449        versionedLib.put(version, libEntry);
11450        return true;
11451    }
11452
11453    private boolean removeSharedLibraryLPw(String name, int version) {
11454        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11455        if (versionedLib == null) {
11456            return false;
11457        }
11458        final int libIdx = versionedLib.indexOfKey(version);
11459        if (libIdx < 0) {
11460            return false;
11461        }
11462        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11463        versionedLib.remove(version);
11464        if (versionedLib.size() <= 0) {
11465            mSharedLibraries.remove(name);
11466            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11467                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11468                        .getPackageName());
11469            }
11470        }
11471        return true;
11472    }
11473
11474    /**
11475     * Adds a scanned package to the system. When this method is finished, the package will
11476     * be available for query, resolution, etc...
11477     */
11478    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11479            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
11480        final String pkgName = pkg.packageName;
11481        if (mCustomResolverComponentName != null &&
11482                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11483            setUpCustomResolverActivity(pkg);
11484        }
11485
11486        if (pkg.packageName.equals("android")) {
11487            synchronized (mPackages) {
11488                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11489                    // Set up information for our fall-back user intent resolution activity.
11490                    mPlatformPackage = pkg;
11491                    pkg.mVersionCode = mSdkVersion;
11492                    mAndroidApplication = pkg.applicationInfo;
11493                    if (!mResolverReplaced) {
11494                        mResolveActivity.applicationInfo = mAndroidApplication;
11495                        mResolveActivity.name = ResolverActivity.class.getName();
11496                        mResolveActivity.packageName = mAndroidApplication.packageName;
11497                        mResolveActivity.processName = "system:ui";
11498                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11499                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11500                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11501                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11502                        mResolveActivity.exported = true;
11503                        mResolveActivity.enabled = true;
11504                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11505                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11506                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11507                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11508                                | ActivityInfo.CONFIG_ORIENTATION
11509                                | ActivityInfo.CONFIG_KEYBOARD
11510                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11511                        mResolveInfo.activityInfo = mResolveActivity;
11512                        mResolveInfo.priority = 0;
11513                        mResolveInfo.preferredOrder = 0;
11514                        mResolveInfo.match = 0;
11515                        mResolveComponentName = new ComponentName(
11516                                mAndroidApplication.packageName, mResolveActivity.name);
11517                    }
11518                }
11519            }
11520        }
11521
11522        ArrayList<PackageParser.Package> clientLibPkgs = null;
11523        // writer
11524        synchronized (mPackages) {
11525            boolean hasStaticSharedLibs = false;
11526
11527            // Any app can add new static shared libraries
11528            if (pkg.staticSharedLibName != null) {
11529                // Static shared libs don't allow renaming as they have synthetic package
11530                // names to allow install of multiple versions, so use name from manifest.
11531                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11532                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11533                        pkg.manifestPackageName, pkg.mVersionCode)) {
11534                    hasStaticSharedLibs = true;
11535                } else {
11536                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11537                                + pkg.staticSharedLibName + " already exists; skipping");
11538                }
11539                // Static shared libs cannot be updated once installed since they
11540                // use synthetic package name which includes the version code, so
11541                // not need to update other packages's shared lib dependencies.
11542            }
11543
11544            if (!hasStaticSharedLibs
11545                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11546                // Only system apps can add new dynamic shared libraries.
11547                if (pkg.libraryNames != null) {
11548                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11549                        String name = pkg.libraryNames.get(i);
11550                        boolean allowed = false;
11551                        if (pkg.isUpdatedSystemApp()) {
11552                            // New library entries can only be added through the
11553                            // system image.  This is important to get rid of a lot
11554                            // of nasty edge cases: for example if we allowed a non-
11555                            // system update of the app to add a library, then uninstalling
11556                            // the update would make the library go away, and assumptions
11557                            // we made such as through app install filtering would now
11558                            // have allowed apps on the device which aren't compatible
11559                            // with it.  Better to just have the restriction here, be
11560                            // conservative, and create many fewer cases that can negatively
11561                            // impact the user experience.
11562                            final PackageSetting sysPs = mSettings
11563                                    .getDisabledSystemPkgLPr(pkg.packageName);
11564                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11565                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11566                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11567                                        allowed = true;
11568                                        break;
11569                                    }
11570                                }
11571                            }
11572                        } else {
11573                            allowed = true;
11574                        }
11575                        if (allowed) {
11576                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11577                                    SharedLibraryInfo.VERSION_UNDEFINED,
11578                                    SharedLibraryInfo.TYPE_DYNAMIC,
11579                                    pkg.packageName, pkg.mVersionCode)) {
11580                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11581                                        + name + " already exists; skipping");
11582                            }
11583                        } else {
11584                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11585                                    + name + " that is not declared on system image; skipping");
11586                        }
11587                    }
11588
11589                    if ((scanFlags & SCAN_BOOTING) == 0) {
11590                        // If we are not booting, we need to update any applications
11591                        // that are clients of our shared library.  If we are booting,
11592                        // this will all be done once the scan is complete.
11593                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11594                    }
11595                }
11596            }
11597        }
11598
11599        if ((scanFlags & SCAN_BOOTING) != 0) {
11600            // No apps can run during boot scan, so they don't need to be frozen
11601        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11602            // Caller asked to not kill app, so it's probably not frozen
11603        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11604            // Caller asked us to ignore frozen check for some reason; they
11605            // probably didn't know the package name
11606        } else {
11607            // We're doing major surgery on this package, so it better be frozen
11608            // right now to keep it from launching
11609            checkPackageFrozen(pkgName);
11610        }
11611
11612        // Also need to kill any apps that are dependent on the library.
11613        if (clientLibPkgs != null) {
11614            for (int i=0; i<clientLibPkgs.size(); i++) {
11615                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11616                killApplication(clientPkg.applicationInfo.packageName,
11617                        clientPkg.applicationInfo.uid, "update lib");
11618            }
11619        }
11620
11621        // writer
11622        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11623
11624        synchronized (mPackages) {
11625            // We don't expect installation to fail beyond this point
11626
11627            // Add the new setting to mSettings
11628            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11629            // Add the new setting to mPackages
11630            mPackages.put(pkg.applicationInfo.packageName, pkg);
11631            // Make sure we don't accidentally delete its data.
11632            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11633            while (iter.hasNext()) {
11634                PackageCleanItem item = iter.next();
11635                if (pkgName.equals(item.packageName)) {
11636                    iter.remove();
11637                }
11638            }
11639
11640            // Add the package's KeySets to the global KeySetManagerService
11641            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11642            ksms.addScannedPackageLPw(pkg);
11643
11644            int N = pkg.providers.size();
11645            StringBuilder r = null;
11646            int i;
11647            for (i=0; i<N; i++) {
11648                PackageParser.Provider p = pkg.providers.get(i);
11649                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11650                        p.info.processName);
11651                mProviders.addProvider(p);
11652                p.syncable = p.info.isSyncable;
11653                if (p.info.authority != null) {
11654                    String names[] = p.info.authority.split(";");
11655                    p.info.authority = null;
11656                    for (int j = 0; j < names.length; j++) {
11657                        if (j == 1 && p.syncable) {
11658                            // We only want the first authority for a provider to possibly be
11659                            // syncable, so if we already added this provider using a different
11660                            // authority clear the syncable flag. We copy the provider before
11661                            // changing it because the mProviders object contains a reference
11662                            // to a provider that we don't want to change.
11663                            // Only do this for the second authority since the resulting provider
11664                            // object can be the same for all future authorities for this provider.
11665                            p = new PackageParser.Provider(p);
11666                            p.syncable = false;
11667                        }
11668                        if (!mProvidersByAuthority.containsKey(names[j])) {
11669                            mProvidersByAuthority.put(names[j], p);
11670                            if (p.info.authority == null) {
11671                                p.info.authority = names[j];
11672                            } else {
11673                                p.info.authority = p.info.authority + ";" + names[j];
11674                            }
11675                            if (DEBUG_PACKAGE_SCANNING) {
11676                                if (chatty)
11677                                    Log.d(TAG, "Registered content provider: " + names[j]
11678                                            + ", className = " + p.info.name + ", isSyncable = "
11679                                            + p.info.isSyncable);
11680                            }
11681                        } else {
11682                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11683                            Slog.w(TAG, "Skipping provider name " + names[j] +
11684                                    " (in package " + pkg.applicationInfo.packageName +
11685                                    "): name already used by "
11686                                    + ((other != null && other.getComponentName() != null)
11687                                            ? other.getComponentName().getPackageName() : "?"));
11688                        }
11689                    }
11690                }
11691                if (chatty) {
11692                    if (r == null) {
11693                        r = new StringBuilder(256);
11694                    } else {
11695                        r.append(' ');
11696                    }
11697                    r.append(p.info.name);
11698                }
11699            }
11700            if (r != null) {
11701                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11702            }
11703
11704            N = pkg.services.size();
11705            r = null;
11706            for (i=0; i<N; i++) {
11707                PackageParser.Service s = pkg.services.get(i);
11708                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11709                        s.info.processName);
11710                mServices.addService(s);
11711                if (chatty) {
11712                    if (r == null) {
11713                        r = new StringBuilder(256);
11714                    } else {
11715                        r.append(' ');
11716                    }
11717                    r.append(s.info.name);
11718                }
11719            }
11720            if (r != null) {
11721                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11722            }
11723
11724            N = pkg.receivers.size();
11725            r = null;
11726            for (i=0; i<N; i++) {
11727                PackageParser.Activity a = pkg.receivers.get(i);
11728                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11729                        a.info.processName);
11730                mReceivers.addActivity(a, "receiver");
11731                if (chatty) {
11732                    if (r == null) {
11733                        r = new StringBuilder(256);
11734                    } else {
11735                        r.append(' ');
11736                    }
11737                    r.append(a.info.name);
11738                }
11739            }
11740            if (r != null) {
11741                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11742            }
11743
11744            N = pkg.activities.size();
11745            r = null;
11746            for (i=0; i<N; i++) {
11747                PackageParser.Activity a = pkg.activities.get(i);
11748                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11749                        a.info.processName);
11750                mActivities.addActivity(a, "activity");
11751                if (chatty) {
11752                    if (r == null) {
11753                        r = new StringBuilder(256);
11754                    } else {
11755                        r.append(' ');
11756                    }
11757                    r.append(a.info.name);
11758                }
11759            }
11760            if (r != null) {
11761                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11762            }
11763
11764            N = pkg.permissionGroups.size();
11765            r = null;
11766            for (i=0; i<N; i++) {
11767                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11768                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11769                final String curPackageName = cur == null ? null : cur.info.packageName;
11770                // Dont allow ephemeral apps to define new permission groups.
11771                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11772                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11773                            + pg.info.packageName
11774                            + " ignored: instant apps cannot define new permission groups.");
11775                    continue;
11776                }
11777                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11778                if (cur == null || isPackageUpdate) {
11779                    mPermissionGroups.put(pg.info.name, pg);
11780                    if (chatty) {
11781                        if (r == null) {
11782                            r = new StringBuilder(256);
11783                        } else {
11784                            r.append(' ');
11785                        }
11786                        if (isPackageUpdate) {
11787                            r.append("UPD:");
11788                        }
11789                        r.append(pg.info.name);
11790                    }
11791                } else {
11792                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11793                            + pg.info.packageName + " ignored: original from "
11794                            + cur.info.packageName);
11795                    if (chatty) {
11796                        if (r == null) {
11797                            r = new StringBuilder(256);
11798                        } else {
11799                            r.append(' ');
11800                        }
11801                        r.append("DUP:");
11802                        r.append(pg.info.name);
11803                    }
11804                }
11805            }
11806            if (r != null) {
11807                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11808            }
11809
11810            N = pkg.permissions.size();
11811            r = null;
11812            for (i=0; i<N; i++) {
11813                PackageParser.Permission p = pkg.permissions.get(i);
11814
11815                // Dont allow ephemeral apps to define new permissions.
11816                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11817                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11818                            + p.info.packageName
11819                            + " ignored: instant apps cannot define new permissions.");
11820                    continue;
11821                }
11822
11823                // Assume by default that we did not install this permission into the system.
11824                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11825
11826                // Now that permission groups have a special meaning, we ignore permission
11827                // groups for legacy apps to prevent unexpected behavior. In particular,
11828                // permissions for one app being granted to someone just because they happen
11829                // to be in a group defined by another app (before this had no implications).
11830                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11831                    p.group = mPermissionGroups.get(p.info.group);
11832                    // Warn for a permission in an unknown group.
11833                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11834                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11835                                + p.info.packageName + " in an unknown group " + p.info.group);
11836                    }
11837                }
11838
11839                ArrayMap<String, BasePermission> permissionMap =
11840                        p.tree ? mSettings.mPermissionTrees
11841                                : mSettings.mPermissions;
11842                BasePermission bp = permissionMap.get(p.info.name);
11843
11844                // Allow system apps to redefine non-system permissions
11845                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11846                    final boolean currentOwnerIsSystem = (bp.perm != null
11847                            && isSystemApp(bp.perm.owner));
11848                    if (isSystemApp(p.owner)) {
11849                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11850                            // It's a built-in permission and no owner, take ownership now
11851                            bp.packageSetting = pkgSetting;
11852                            bp.perm = p;
11853                            bp.uid = pkg.applicationInfo.uid;
11854                            bp.sourcePackage = p.info.packageName;
11855                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11856                        } else if (!currentOwnerIsSystem) {
11857                            String msg = "New decl " + p.owner + " of permission  "
11858                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
11859                            reportSettingsProblem(Log.WARN, msg);
11860                            bp = null;
11861                        }
11862                    }
11863                }
11864
11865                if (bp == null) {
11866                    bp = new BasePermission(p.info.name, p.info.packageName,
11867                            BasePermission.TYPE_NORMAL);
11868                    permissionMap.put(p.info.name, bp);
11869                }
11870
11871                if (bp.perm == null) {
11872                    if (bp.sourcePackage == null
11873                            || bp.sourcePackage.equals(p.info.packageName)) {
11874                        BasePermission tree = findPermissionTreeLP(p.info.name);
11875                        if (tree == null
11876                                || tree.sourcePackage.equals(p.info.packageName)) {
11877                            bp.packageSetting = pkgSetting;
11878                            bp.perm = p;
11879                            bp.uid = pkg.applicationInfo.uid;
11880                            bp.sourcePackage = p.info.packageName;
11881                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11882                            if (chatty) {
11883                                if (r == null) {
11884                                    r = new StringBuilder(256);
11885                                } else {
11886                                    r.append(' ');
11887                                }
11888                                r.append(p.info.name);
11889                            }
11890                        } else {
11891                            Slog.w(TAG, "Permission " + p.info.name + " from package "
11892                                    + p.info.packageName + " ignored: base tree "
11893                                    + tree.name + " is from package "
11894                                    + tree.sourcePackage);
11895                        }
11896                    } else {
11897                        Slog.w(TAG, "Permission " + p.info.name + " from package "
11898                                + p.info.packageName + " ignored: original from "
11899                                + bp.sourcePackage);
11900                    }
11901                } else if (chatty) {
11902                    if (r == null) {
11903                        r = new StringBuilder(256);
11904                    } else {
11905                        r.append(' ');
11906                    }
11907                    r.append("DUP:");
11908                    r.append(p.info.name);
11909                }
11910                if (bp.perm == p) {
11911                    bp.protectionLevel = p.info.protectionLevel;
11912                }
11913            }
11914
11915            if (r != null) {
11916                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
11917            }
11918
11919            N = pkg.instrumentation.size();
11920            r = null;
11921            for (i=0; i<N; i++) {
11922                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11923                a.info.packageName = pkg.applicationInfo.packageName;
11924                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11925                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11926                a.info.splitNames = pkg.splitNames;
11927                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11928                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11929                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11930                a.info.dataDir = pkg.applicationInfo.dataDir;
11931                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11932                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11933                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11934                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11935                mInstrumentation.put(a.getComponentName(), a);
11936                if (chatty) {
11937                    if (r == null) {
11938                        r = new StringBuilder(256);
11939                    } else {
11940                        r.append(' ');
11941                    }
11942                    r.append(a.info.name);
11943                }
11944            }
11945            if (r != null) {
11946                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11947            }
11948
11949            if (pkg.protectedBroadcasts != null) {
11950                N = pkg.protectedBroadcasts.size();
11951                synchronized (mProtectedBroadcasts) {
11952                    for (i = 0; i < N; i++) {
11953                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11954                    }
11955                }
11956            }
11957        }
11958
11959        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11960    }
11961
11962    /**
11963     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11964     * is derived purely on the basis of the contents of {@code scanFile} and
11965     * {@code cpuAbiOverride}.
11966     *
11967     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11968     */
11969    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11970                                 String cpuAbiOverride, boolean extractLibs,
11971                                 File appLib32InstallDir)
11972            throws PackageManagerException {
11973        // Give ourselves some initial paths; we'll come back for another
11974        // pass once we've determined ABI below.
11975        setNativeLibraryPaths(pkg, appLib32InstallDir);
11976
11977        // We would never need to extract libs for forward-locked and external packages,
11978        // since the container service will do it for us. We shouldn't attempt to
11979        // extract libs from system app when it was not updated.
11980        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11981                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11982            extractLibs = false;
11983        }
11984
11985        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11986        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11987
11988        NativeLibraryHelper.Handle handle = null;
11989        try {
11990            handle = NativeLibraryHelper.Handle.create(pkg);
11991            // TODO(multiArch): This can be null for apps that didn't go through the
11992            // usual installation process. We can calculate it again, like we
11993            // do during install time.
11994            //
11995            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11996            // unnecessary.
11997            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11998
11999            // Null out the abis so that they can be recalculated.
12000            pkg.applicationInfo.primaryCpuAbi = null;
12001            pkg.applicationInfo.secondaryCpuAbi = null;
12002            if (isMultiArch(pkg.applicationInfo)) {
12003                // Warn if we've set an abiOverride for multi-lib packages..
12004                // By definition, we need to copy both 32 and 64 bit libraries for
12005                // such packages.
12006                if (pkg.cpuAbiOverride != null
12007                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
12008                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
12009                }
12010
12011                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
12012                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
12013                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
12014                    if (extractLibs) {
12015                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
12016                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
12017                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
12018                                useIsaSpecificSubdirs);
12019                    } else {
12020                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
12021                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
12022                    }
12023                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12024                }
12025
12026                // Shared library native code should be in the APK zip aligned
12027                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
12028                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12029                            "Shared library native lib extraction not supported");
12030                }
12031
12032                maybeThrowExceptionForMultiArchCopy(
12033                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
12034
12035                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
12036                    if (extractLibs) {
12037                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
12038                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
12039                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
12040                                useIsaSpecificSubdirs);
12041                    } else {
12042                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
12043                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
12044                    }
12045                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12046                }
12047
12048                maybeThrowExceptionForMultiArchCopy(
12049                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
12050
12051                if (abi64 >= 0) {
12052                    // Shared library native libs should be in the APK zip aligned
12053                    if (extractLibs && pkg.isLibrary()) {
12054                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12055                                "Shared library native lib extraction not supported");
12056                    }
12057                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
12058                }
12059
12060                if (abi32 >= 0) {
12061                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
12062                    if (abi64 >= 0) {
12063                        if (pkg.use32bitAbi) {
12064                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
12065                            pkg.applicationInfo.primaryCpuAbi = abi;
12066                        } else {
12067                            pkg.applicationInfo.secondaryCpuAbi = abi;
12068                        }
12069                    } else {
12070                        pkg.applicationInfo.primaryCpuAbi = abi;
12071                    }
12072                }
12073            } else {
12074                String[] abiList = (cpuAbiOverride != null) ?
12075                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
12076
12077                // Enable gross and lame hacks for apps that are built with old
12078                // SDK tools. We must scan their APKs for renderscript bitcode and
12079                // not launch them if it's present. Don't bother checking on devices
12080                // that don't have 64 bit support.
12081                boolean needsRenderScriptOverride = false;
12082                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
12083                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
12084                    abiList = Build.SUPPORTED_32_BIT_ABIS;
12085                    needsRenderScriptOverride = true;
12086                }
12087
12088                final int copyRet;
12089                if (extractLibs) {
12090                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
12091                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
12092                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
12093                } else {
12094                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
12095                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
12096                }
12097                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12098
12099                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
12100                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12101                            "Error unpackaging native libs for app, errorCode=" + copyRet);
12102                }
12103
12104                if (copyRet >= 0) {
12105                    // Shared libraries that have native libs must be multi-architecture
12106                    if (pkg.isLibrary()) {
12107                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12108                                "Shared library with native libs must be multiarch");
12109                    }
12110                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
12111                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
12112                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
12113                } else if (needsRenderScriptOverride) {
12114                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
12115                }
12116            }
12117        } catch (IOException ioe) {
12118            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
12119        } finally {
12120            IoUtils.closeQuietly(handle);
12121        }
12122
12123        // Now that we've calculated the ABIs and determined if it's an internal app,
12124        // we will go ahead and populate the nativeLibraryPath.
12125        setNativeLibraryPaths(pkg, appLib32InstallDir);
12126    }
12127
12128    /**
12129     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
12130     * i.e, so that all packages can be run inside a single process if required.
12131     *
12132     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
12133     * this function will either try and make the ABI for all packages in {@code packagesForUser}
12134     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
12135     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
12136     * updating a package that belongs to a shared user.
12137     *
12138     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
12139     * adds unnecessary complexity.
12140     */
12141    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
12142            PackageParser.Package scannedPackage) {
12143        String requiredInstructionSet = null;
12144        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
12145            requiredInstructionSet = VMRuntime.getInstructionSet(
12146                     scannedPackage.applicationInfo.primaryCpuAbi);
12147        }
12148
12149        PackageSetting requirer = null;
12150        for (PackageSetting ps : packagesForUser) {
12151            // If packagesForUser contains scannedPackage, we skip it. This will happen
12152            // when scannedPackage is an update of an existing package. Without this check,
12153            // we will never be able to change the ABI of any package belonging to a shared
12154            // user, even if it's compatible with other packages.
12155            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
12156                if (ps.primaryCpuAbiString == null) {
12157                    continue;
12158                }
12159
12160                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
12161                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
12162                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
12163                    // this but there's not much we can do.
12164                    String errorMessage = "Instruction set mismatch, "
12165                            + ((requirer == null) ? "[caller]" : requirer)
12166                            + " requires " + requiredInstructionSet + " whereas " + ps
12167                            + " requires " + instructionSet;
12168                    Slog.w(TAG, errorMessage);
12169                }
12170
12171                if (requiredInstructionSet == null) {
12172                    requiredInstructionSet = instructionSet;
12173                    requirer = ps;
12174                }
12175            }
12176        }
12177
12178        if (requiredInstructionSet != null) {
12179            String adjustedAbi;
12180            if (requirer != null) {
12181                // requirer != null implies that either scannedPackage was null or that scannedPackage
12182                // did not require an ABI, in which case we have to adjust scannedPackage to match
12183                // the ABI of the set (which is the same as requirer's ABI)
12184                adjustedAbi = requirer.primaryCpuAbiString;
12185                if (scannedPackage != null) {
12186                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
12187                }
12188            } else {
12189                // requirer == null implies that we're updating all ABIs in the set to
12190                // match scannedPackage.
12191                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
12192            }
12193
12194            for (PackageSetting ps : packagesForUser) {
12195                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
12196                    if (ps.primaryCpuAbiString != null) {
12197                        continue;
12198                    }
12199
12200                    ps.primaryCpuAbiString = adjustedAbi;
12201                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
12202                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
12203                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
12204                        if (DEBUG_ABI_SELECTION) {
12205                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
12206                                    + " (requirer="
12207                                    + (requirer != null ? requirer.pkg : "null")
12208                                    + ", scannedPackage="
12209                                    + (scannedPackage != null ? scannedPackage : "null")
12210                                    + ")");
12211                        }
12212                        try {
12213                            mInstaller.rmdex(ps.codePathString,
12214                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
12215                        } catch (InstallerException ignored) {
12216                        }
12217                    }
12218                }
12219            }
12220        }
12221    }
12222
12223    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
12224        synchronized (mPackages) {
12225            mResolverReplaced = true;
12226            // Set up information for custom user intent resolution activity.
12227            mResolveActivity.applicationInfo = pkg.applicationInfo;
12228            mResolveActivity.name = mCustomResolverComponentName.getClassName();
12229            mResolveActivity.packageName = pkg.applicationInfo.packageName;
12230            mResolveActivity.processName = pkg.applicationInfo.packageName;
12231            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
12232            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
12233                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12234            mResolveActivity.theme = 0;
12235            mResolveActivity.exported = true;
12236            mResolveActivity.enabled = true;
12237            mResolveInfo.activityInfo = mResolveActivity;
12238            mResolveInfo.priority = 0;
12239            mResolveInfo.preferredOrder = 0;
12240            mResolveInfo.match = 0;
12241            mResolveComponentName = mCustomResolverComponentName;
12242            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
12243                    mResolveComponentName);
12244        }
12245    }
12246
12247    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
12248        if (installerActivity == null) {
12249            if (DEBUG_EPHEMERAL) {
12250                Slog.d(TAG, "Clear ephemeral installer activity");
12251            }
12252            mInstantAppInstallerActivity = null;
12253            return;
12254        }
12255
12256        if (DEBUG_EPHEMERAL) {
12257            Slog.d(TAG, "Set ephemeral installer activity: "
12258                    + installerActivity.getComponentName());
12259        }
12260        // Set up information for ephemeral installer activity
12261        mInstantAppInstallerActivity = installerActivity;
12262        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
12263                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12264        mInstantAppInstallerActivity.exported = true;
12265        mInstantAppInstallerActivity.enabled = true;
12266        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
12267        mInstantAppInstallerInfo.priority = 0;
12268        mInstantAppInstallerInfo.preferredOrder = 1;
12269        mInstantAppInstallerInfo.isDefault = true;
12270        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
12271                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
12272    }
12273
12274    private static String calculateBundledApkRoot(final String codePathString) {
12275        final File codePath = new File(codePathString);
12276        final File codeRoot;
12277        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
12278            codeRoot = Environment.getRootDirectory();
12279        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
12280            codeRoot = Environment.getOemDirectory();
12281        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
12282            codeRoot = Environment.getVendorDirectory();
12283        } else {
12284            // Unrecognized code path; take its top real segment as the apk root:
12285            // e.g. /something/app/blah.apk => /something
12286            try {
12287                File f = codePath.getCanonicalFile();
12288                File parent = f.getParentFile();    // non-null because codePath is a file
12289                File tmp;
12290                while ((tmp = parent.getParentFile()) != null) {
12291                    f = parent;
12292                    parent = tmp;
12293                }
12294                codeRoot = f;
12295                Slog.w(TAG, "Unrecognized code path "
12296                        + codePath + " - using " + codeRoot);
12297            } catch (IOException e) {
12298                // Can't canonicalize the code path -- shenanigans?
12299                Slog.w(TAG, "Can't canonicalize code path " + codePath);
12300                return Environment.getRootDirectory().getPath();
12301            }
12302        }
12303        return codeRoot.getPath();
12304    }
12305
12306    /**
12307     * Derive and set the location of native libraries for the given package,
12308     * which varies depending on where and how the package was installed.
12309     */
12310    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
12311        final ApplicationInfo info = pkg.applicationInfo;
12312        final String codePath = pkg.codePath;
12313        final File codeFile = new File(codePath);
12314        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
12315        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
12316
12317        info.nativeLibraryRootDir = null;
12318        info.nativeLibraryRootRequiresIsa = false;
12319        info.nativeLibraryDir = null;
12320        info.secondaryNativeLibraryDir = null;
12321
12322        if (isApkFile(codeFile)) {
12323            // Monolithic install
12324            if (bundledApp) {
12325                // If "/system/lib64/apkname" exists, assume that is the per-package
12326                // native library directory to use; otherwise use "/system/lib/apkname".
12327                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
12328                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
12329                        getPrimaryInstructionSet(info));
12330
12331                // This is a bundled system app so choose the path based on the ABI.
12332                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
12333                // is just the default path.
12334                final String apkName = deriveCodePathName(codePath);
12335                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
12336                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
12337                        apkName).getAbsolutePath();
12338
12339                if (info.secondaryCpuAbi != null) {
12340                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
12341                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
12342                            secondaryLibDir, apkName).getAbsolutePath();
12343                }
12344            } else if (asecApp) {
12345                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
12346                        .getAbsolutePath();
12347            } else {
12348                final String apkName = deriveCodePathName(codePath);
12349                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
12350                        .getAbsolutePath();
12351            }
12352
12353            info.nativeLibraryRootRequiresIsa = false;
12354            info.nativeLibraryDir = info.nativeLibraryRootDir;
12355        } else {
12356            // Cluster install
12357            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
12358            info.nativeLibraryRootRequiresIsa = true;
12359
12360            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
12361                    getPrimaryInstructionSet(info)).getAbsolutePath();
12362
12363            if (info.secondaryCpuAbi != null) {
12364                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
12365                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
12366            }
12367        }
12368    }
12369
12370    /**
12371     * Calculate the abis and roots for a bundled app. These can uniquely
12372     * be determined from the contents of the system partition, i.e whether
12373     * it contains 64 or 32 bit shared libraries etc. We do not validate any
12374     * of this information, and instead assume that the system was built
12375     * sensibly.
12376     */
12377    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
12378                                           PackageSetting pkgSetting) {
12379        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
12380
12381        // If "/system/lib64/apkname" exists, assume that is the per-package
12382        // native library directory to use; otherwise use "/system/lib/apkname".
12383        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
12384        setBundledAppAbi(pkg, apkRoot, apkName);
12385        // pkgSetting might be null during rescan following uninstall of updates
12386        // to a bundled app, so accommodate that possibility.  The settings in
12387        // that case will be established later from the parsed package.
12388        //
12389        // If the settings aren't null, sync them up with what we've just derived.
12390        // note that apkRoot isn't stored in the package settings.
12391        if (pkgSetting != null) {
12392            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
12393            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
12394        }
12395    }
12396
12397    /**
12398     * Deduces the ABI of a bundled app and sets the relevant fields on the
12399     * parsed pkg object.
12400     *
12401     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
12402     *        under which system libraries are installed.
12403     * @param apkName the name of the installed package.
12404     */
12405    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
12406        final File codeFile = new File(pkg.codePath);
12407
12408        final boolean has64BitLibs;
12409        final boolean has32BitLibs;
12410        if (isApkFile(codeFile)) {
12411            // Monolithic install
12412            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
12413            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
12414        } else {
12415            // Cluster install
12416            final File rootDir = new File(codeFile, LIB_DIR_NAME);
12417            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
12418                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
12419                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
12420                has64BitLibs = (new File(rootDir, isa)).exists();
12421            } else {
12422                has64BitLibs = false;
12423            }
12424            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
12425                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
12426                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
12427                has32BitLibs = (new File(rootDir, isa)).exists();
12428            } else {
12429                has32BitLibs = false;
12430            }
12431        }
12432
12433        if (has64BitLibs && !has32BitLibs) {
12434            // The package has 64 bit libs, but not 32 bit libs. Its primary
12435            // ABI should be 64 bit. We can safely assume here that the bundled
12436            // native libraries correspond to the most preferred ABI in the list.
12437
12438            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12439            pkg.applicationInfo.secondaryCpuAbi = null;
12440        } else if (has32BitLibs && !has64BitLibs) {
12441            // The package has 32 bit libs but not 64 bit libs. Its primary
12442            // ABI should be 32 bit.
12443
12444            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12445            pkg.applicationInfo.secondaryCpuAbi = null;
12446        } else if (has32BitLibs && has64BitLibs) {
12447            // The application has both 64 and 32 bit bundled libraries. We check
12448            // here that the app declares multiArch support, and warn if it doesn't.
12449            //
12450            // We will be lenient here and record both ABIs. The primary will be the
12451            // ABI that's higher on the list, i.e, a device that's configured to prefer
12452            // 64 bit apps will see a 64 bit primary ABI,
12453
12454            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
12455                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12456            }
12457
12458            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12459                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12460                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12461            } else {
12462                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12463                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12464            }
12465        } else {
12466            pkg.applicationInfo.primaryCpuAbi = null;
12467            pkg.applicationInfo.secondaryCpuAbi = null;
12468        }
12469    }
12470
12471    private void killApplication(String pkgName, int appId, String reason) {
12472        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12473    }
12474
12475    private void killApplication(String pkgName, int appId, int userId, String reason) {
12476        // Request the ActivityManager to kill the process(only for existing packages)
12477        // so that we do not end up in a confused state while the user is still using the older
12478        // version of the application while the new one gets installed.
12479        final long token = Binder.clearCallingIdentity();
12480        try {
12481            IActivityManager am = ActivityManager.getService();
12482            if (am != null) {
12483                try {
12484                    am.killApplication(pkgName, appId, userId, reason);
12485                } catch (RemoteException e) {
12486                }
12487            }
12488        } finally {
12489            Binder.restoreCallingIdentity(token);
12490        }
12491    }
12492
12493    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12494        // Remove the parent package setting
12495        PackageSetting ps = (PackageSetting) pkg.mExtras;
12496        if (ps != null) {
12497            removePackageLI(ps, chatty);
12498        }
12499        // Remove the child package setting
12500        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12501        for (int i = 0; i < childCount; i++) {
12502            PackageParser.Package childPkg = pkg.childPackages.get(i);
12503            ps = (PackageSetting) childPkg.mExtras;
12504            if (ps != null) {
12505                removePackageLI(ps, chatty);
12506            }
12507        }
12508    }
12509
12510    void removePackageLI(PackageSetting ps, boolean chatty) {
12511        if (DEBUG_INSTALL) {
12512            if (chatty)
12513                Log.d(TAG, "Removing package " + ps.name);
12514        }
12515
12516        // writer
12517        synchronized (mPackages) {
12518            mPackages.remove(ps.name);
12519            final PackageParser.Package pkg = ps.pkg;
12520            if (pkg != null) {
12521                cleanPackageDataStructuresLILPw(pkg, chatty);
12522            }
12523        }
12524    }
12525
12526    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12527        if (DEBUG_INSTALL) {
12528            if (chatty)
12529                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12530        }
12531
12532        // writer
12533        synchronized (mPackages) {
12534            // Remove the parent package
12535            mPackages.remove(pkg.applicationInfo.packageName);
12536            cleanPackageDataStructuresLILPw(pkg, chatty);
12537
12538            // Remove the child packages
12539            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12540            for (int i = 0; i < childCount; i++) {
12541                PackageParser.Package childPkg = pkg.childPackages.get(i);
12542                mPackages.remove(childPkg.applicationInfo.packageName);
12543                cleanPackageDataStructuresLILPw(childPkg, chatty);
12544            }
12545        }
12546    }
12547
12548    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12549        int N = pkg.providers.size();
12550        StringBuilder r = null;
12551        int i;
12552        for (i=0; i<N; i++) {
12553            PackageParser.Provider p = pkg.providers.get(i);
12554            mProviders.removeProvider(p);
12555            if (p.info.authority == null) {
12556
12557                /* There was another ContentProvider with this authority when
12558                 * this app was installed so this authority is null,
12559                 * Ignore it as we don't have to unregister the provider.
12560                 */
12561                continue;
12562            }
12563            String names[] = p.info.authority.split(";");
12564            for (int j = 0; j < names.length; j++) {
12565                if (mProvidersByAuthority.get(names[j]) == p) {
12566                    mProvidersByAuthority.remove(names[j]);
12567                    if (DEBUG_REMOVE) {
12568                        if (chatty)
12569                            Log.d(TAG, "Unregistered content provider: " + names[j]
12570                                    + ", className = " + p.info.name + ", isSyncable = "
12571                                    + p.info.isSyncable);
12572                    }
12573                }
12574            }
12575            if (DEBUG_REMOVE && chatty) {
12576                if (r == null) {
12577                    r = new StringBuilder(256);
12578                } else {
12579                    r.append(' ');
12580                }
12581                r.append(p.info.name);
12582            }
12583        }
12584        if (r != null) {
12585            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12586        }
12587
12588        N = pkg.services.size();
12589        r = null;
12590        for (i=0; i<N; i++) {
12591            PackageParser.Service s = pkg.services.get(i);
12592            mServices.removeService(s);
12593            if (chatty) {
12594                if (r == null) {
12595                    r = new StringBuilder(256);
12596                } else {
12597                    r.append(' ');
12598                }
12599                r.append(s.info.name);
12600            }
12601        }
12602        if (r != null) {
12603            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12604        }
12605
12606        N = pkg.receivers.size();
12607        r = null;
12608        for (i=0; i<N; i++) {
12609            PackageParser.Activity a = pkg.receivers.get(i);
12610            mReceivers.removeActivity(a, "receiver");
12611            if (DEBUG_REMOVE && chatty) {
12612                if (r == null) {
12613                    r = new StringBuilder(256);
12614                } else {
12615                    r.append(' ');
12616                }
12617                r.append(a.info.name);
12618            }
12619        }
12620        if (r != null) {
12621            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12622        }
12623
12624        N = pkg.activities.size();
12625        r = null;
12626        for (i=0; i<N; i++) {
12627            PackageParser.Activity a = pkg.activities.get(i);
12628            mActivities.removeActivity(a, "activity");
12629            if (DEBUG_REMOVE && chatty) {
12630                if (r == null) {
12631                    r = new StringBuilder(256);
12632                } else {
12633                    r.append(' ');
12634                }
12635                r.append(a.info.name);
12636            }
12637        }
12638        if (r != null) {
12639            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12640        }
12641
12642        N = pkg.permissions.size();
12643        r = null;
12644        for (i=0; i<N; i++) {
12645            PackageParser.Permission p = pkg.permissions.get(i);
12646            BasePermission bp = mSettings.mPermissions.get(p.info.name);
12647            if (bp == null) {
12648                bp = mSettings.mPermissionTrees.get(p.info.name);
12649            }
12650            if (bp != null && bp.perm == p) {
12651                bp.perm = null;
12652                if (DEBUG_REMOVE && chatty) {
12653                    if (r == null) {
12654                        r = new StringBuilder(256);
12655                    } else {
12656                        r.append(' ');
12657                    }
12658                    r.append(p.info.name);
12659                }
12660            }
12661            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12662                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12663                if (appOpPkgs != null) {
12664                    appOpPkgs.remove(pkg.packageName);
12665                }
12666            }
12667        }
12668        if (r != null) {
12669            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12670        }
12671
12672        N = pkg.requestedPermissions.size();
12673        r = null;
12674        for (i=0; i<N; i++) {
12675            String perm = pkg.requestedPermissions.get(i);
12676            BasePermission bp = mSettings.mPermissions.get(perm);
12677            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12678                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12679                if (appOpPkgs != null) {
12680                    appOpPkgs.remove(pkg.packageName);
12681                    if (appOpPkgs.isEmpty()) {
12682                        mAppOpPermissionPackages.remove(perm);
12683                    }
12684                }
12685            }
12686        }
12687        if (r != null) {
12688            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12689        }
12690
12691        N = pkg.instrumentation.size();
12692        r = null;
12693        for (i=0; i<N; i++) {
12694            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12695            mInstrumentation.remove(a.getComponentName());
12696            if (DEBUG_REMOVE && chatty) {
12697                if (r == null) {
12698                    r = new StringBuilder(256);
12699                } else {
12700                    r.append(' ');
12701                }
12702                r.append(a.info.name);
12703            }
12704        }
12705        if (r != null) {
12706            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12707        }
12708
12709        r = null;
12710        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12711            // Only system apps can hold shared libraries.
12712            if (pkg.libraryNames != null) {
12713                for (i = 0; i < pkg.libraryNames.size(); i++) {
12714                    String name = pkg.libraryNames.get(i);
12715                    if (removeSharedLibraryLPw(name, 0)) {
12716                        if (DEBUG_REMOVE && chatty) {
12717                            if (r == null) {
12718                                r = new StringBuilder(256);
12719                            } else {
12720                                r.append(' ');
12721                            }
12722                            r.append(name);
12723                        }
12724                    }
12725                }
12726            }
12727        }
12728
12729        r = null;
12730
12731        // Any package can hold static shared libraries.
12732        if (pkg.staticSharedLibName != null) {
12733            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12734                if (DEBUG_REMOVE && chatty) {
12735                    if (r == null) {
12736                        r = new StringBuilder(256);
12737                    } else {
12738                        r.append(' ');
12739                    }
12740                    r.append(pkg.staticSharedLibName);
12741                }
12742            }
12743        }
12744
12745        if (r != null) {
12746            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12747        }
12748    }
12749
12750    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12751        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12752            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12753                return true;
12754            }
12755        }
12756        return false;
12757    }
12758
12759    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12760    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12761    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12762
12763    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12764        // Update the parent permissions
12765        updatePermissionsLPw(pkg.packageName, pkg, flags);
12766        // Update the child permissions
12767        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12768        for (int i = 0; i < childCount; i++) {
12769            PackageParser.Package childPkg = pkg.childPackages.get(i);
12770            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12771        }
12772    }
12773
12774    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12775            int flags) {
12776        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12777        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12778    }
12779
12780    private void updatePermissionsLPw(String changingPkg,
12781            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12782        // Make sure there are no dangling permission trees.
12783        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12784        while (it.hasNext()) {
12785            final BasePermission bp = it.next();
12786            if (bp.packageSetting == null) {
12787                // We may not yet have parsed the package, so just see if
12788                // we still know about its settings.
12789                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12790            }
12791            if (bp.packageSetting == null) {
12792                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12793                        + " from package " + bp.sourcePackage);
12794                it.remove();
12795            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12796                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12797                    Slog.i(TAG, "Removing old permission tree: " + bp.name
12798                            + " from package " + bp.sourcePackage);
12799                    flags |= UPDATE_PERMISSIONS_ALL;
12800                    it.remove();
12801                }
12802            }
12803        }
12804
12805        // Make sure all dynamic permissions have been assigned to a package,
12806        // and make sure there are no dangling permissions.
12807        it = mSettings.mPermissions.values().iterator();
12808        while (it.hasNext()) {
12809            final BasePermission bp = it.next();
12810            if (bp.type == BasePermission.TYPE_DYNAMIC) {
12811                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12812                        + bp.name + " pkg=" + bp.sourcePackage
12813                        + " info=" + bp.pendingInfo);
12814                if (bp.packageSetting == null && bp.pendingInfo != null) {
12815                    final BasePermission tree = findPermissionTreeLP(bp.name);
12816                    if (tree != null && tree.perm != null) {
12817                        bp.packageSetting = tree.packageSetting;
12818                        bp.perm = new PackageParser.Permission(tree.perm.owner,
12819                                new PermissionInfo(bp.pendingInfo));
12820                        bp.perm.info.packageName = tree.perm.info.packageName;
12821                        bp.perm.info.name = bp.name;
12822                        bp.uid = tree.uid;
12823                    }
12824                }
12825            }
12826            if (bp.packageSetting == null) {
12827                // We may not yet have parsed the package, so just see if
12828                // we still know about its settings.
12829                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12830            }
12831            if (bp.packageSetting == null) {
12832                Slog.w(TAG, "Removing dangling permission: " + bp.name
12833                        + " from package " + bp.sourcePackage);
12834                it.remove();
12835            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12836                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12837                    Slog.i(TAG, "Removing old permission: " + bp.name
12838                            + " from package " + bp.sourcePackage);
12839                    flags |= UPDATE_PERMISSIONS_ALL;
12840                    it.remove();
12841                }
12842            }
12843        }
12844
12845        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12846        // Now update the permissions for all packages, in particular
12847        // replace the granted permissions of the system packages.
12848        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12849            for (PackageParser.Package pkg : mPackages.values()) {
12850                if (pkg != pkgInfo) {
12851                    // Only replace for packages on requested volume
12852                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12853                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12854                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12855                    grantPermissionsLPw(pkg, replace, changingPkg);
12856                }
12857            }
12858        }
12859
12860        if (pkgInfo != null) {
12861            // Only replace for packages on requested volume
12862            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12863            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12864                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12865            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12866        }
12867        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12868    }
12869
12870    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12871            String packageOfInterest) {
12872        // IMPORTANT: There are two types of permissions: install and runtime.
12873        // Install time permissions are granted when the app is installed to
12874        // all device users and users added in the future. Runtime permissions
12875        // are granted at runtime explicitly to specific users. Normal and signature
12876        // protected permissions are install time permissions. Dangerous permissions
12877        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12878        // otherwise they are runtime permissions. This function does not manage
12879        // runtime permissions except for the case an app targeting Lollipop MR1
12880        // being upgraded to target a newer SDK, in which case dangerous permissions
12881        // are transformed from install time to runtime ones.
12882
12883        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12884        if (ps == null) {
12885            return;
12886        }
12887
12888        PermissionsState permissionsState = ps.getPermissionsState();
12889        PermissionsState origPermissions = permissionsState;
12890
12891        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12892
12893        boolean runtimePermissionsRevoked = false;
12894        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12895
12896        boolean changedInstallPermission = false;
12897
12898        if (replace) {
12899            ps.installPermissionsFixed = false;
12900            if (!ps.isSharedUser()) {
12901                origPermissions = new PermissionsState(permissionsState);
12902                permissionsState.reset();
12903            } else {
12904                // We need to know only about runtime permission changes since the
12905                // calling code always writes the install permissions state but
12906                // the runtime ones are written only if changed. The only cases of
12907                // changed runtime permissions here are promotion of an install to
12908                // runtime and revocation of a runtime from a shared user.
12909                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12910                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
12911                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12912                    runtimePermissionsRevoked = true;
12913                }
12914            }
12915        }
12916
12917        permissionsState.setGlobalGids(mGlobalGids);
12918
12919        final int N = pkg.requestedPermissions.size();
12920        for (int i=0; i<N; i++) {
12921            final String name = pkg.requestedPermissions.get(i);
12922            final BasePermission bp = mSettings.mPermissions.get(name);
12923            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12924                    >= Build.VERSION_CODES.M;
12925
12926            if (DEBUG_INSTALL) {
12927                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12928            }
12929
12930            if (bp == null || bp.packageSetting == null) {
12931                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12932                    if (DEBUG_PERMISSIONS) {
12933                        Slog.i(TAG, "Unknown permission " + name
12934                                + " in package " + pkg.packageName);
12935                    }
12936                }
12937                continue;
12938            }
12939
12940
12941            // Limit ephemeral apps to ephemeral allowed permissions.
12942            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12943                if (DEBUG_PERMISSIONS) {
12944                    Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
12945                            + pkg.packageName);
12946                }
12947                continue;
12948            }
12949
12950            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12951                if (DEBUG_PERMISSIONS) {
12952                    Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
12953                            + pkg.packageName);
12954                }
12955                continue;
12956            }
12957
12958            final String perm = bp.name;
12959            boolean allowedSig = false;
12960            int grant = GRANT_DENIED;
12961
12962            // Keep track of app op permissions.
12963            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12964                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
12965                if (pkgs == null) {
12966                    pkgs = new ArraySet<>();
12967                    mAppOpPermissionPackages.put(bp.name, pkgs);
12968                }
12969                pkgs.add(pkg.packageName);
12970            }
12971
12972            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
12973            switch (level) {
12974                case PermissionInfo.PROTECTION_NORMAL: {
12975                    // For all apps normal permissions are install time ones.
12976                    grant = GRANT_INSTALL;
12977                } break;
12978
12979                case PermissionInfo.PROTECTION_DANGEROUS: {
12980                    // If a permission review is required for legacy apps we represent
12981                    // their permissions as always granted runtime ones since we need
12982                    // to keep the review required permission flag per user while an
12983                    // install permission's state is shared across all users.
12984                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12985                        // For legacy apps dangerous permissions are install time ones.
12986                        grant = GRANT_INSTALL;
12987                    } else if (origPermissions.hasInstallPermission(bp.name)) {
12988                        // For legacy apps that became modern, install becomes runtime.
12989                        grant = GRANT_UPGRADE;
12990                    } else if (mPromoteSystemApps
12991                            && isSystemApp(ps)
12992                            && mExistingSystemPackages.contains(ps.name)) {
12993                        // For legacy system apps, install becomes runtime.
12994                        // We cannot check hasInstallPermission() for system apps since those
12995                        // permissions were granted implicitly and not persisted pre-M.
12996                        grant = GRANT_UPGRADE;
12997                    } else {
12998                        // For modern apps keep runtime permissions unchanged.
12999                        grant = GRANT_RUNTIME;
13000                    }
13001                } break;
13002
13003                case PermissionInfo.PROTECTION_SIGNATURE: {
13004                    // For all apps signature permissions are install time ones.
13005                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
13006                    if (allowedSig) {
13007                        grant = GRANT_INSTALL;
13008                    }
13009                } break;
13010            }
13011
13012            if (DEBUG_PERMISSIONS) {
13013                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
13014            }
13015
13016            if (grant != GRANT_DENIED) {
13017                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
13018                    // If this is an existing, non-system package, then
13019                    // we can't add any new permissions to it.
13020                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
13021                        // Except...  if this is a permission that was added
13022                        // to the platform (note: need to only do this when
13023                        // updating the platform).
13024                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
13025                            grant = GRANT_DENIED;
13026                        }
13027                    }
13028                }
13029
13030                switch (grant) {
13031                    case GRANT_INSTALL: {
13032                        // Revoke this as runtime permission to handle the case of
13033                        // a runtime permission being downgraded to an install one.
13034                        // Also in permission review mode we keep dangerous permissions
13035                        // for legacy apps
13036                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13037                            if (origPermissions.getRuntimePermissionState(
13038                                    bp.name, userId) != null) {
13039                                // Revoke the runtime permission and clear the flags.
13040                                origPermissions.revokeRuntimePermission(bp, userId);
13041                                origPermissions.updatePermissionFlags(bp, userId,
13042                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
13043                                // If we revoked a permission permission, we have to write.
13044                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13045                                        changedRuntimePermissionUserIds, userId);
13046                            }
13047                        }
13048                        // Grant an install permission.
13049                        if (permissionsState.grantInstallPermission(bp) !=
13050                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
13051                            changedInstallPermission = true;
13052                        }
13053                    } break;
13054
13055                    case GRANT_RUNTIME: {
13056                        // Grant previously granted runtime permissions.
13057                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13058                            PermissionState permissionState = origPermissions
13059                                    .getRuntimePermissionState(bp.name, userId);
13060                            int flags = permissionState != null
13061                                    ? permissionState.getFlags() : 0;
13062                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
13063                                // Don't propagate the permission in a permission review mode if
13064                                // the former was revoked, i.e. marked to not propagate on upgrade.
13065                                // Note that in a permission review mode install permissions are
13066                                // represented as constantly granted runtime ones since we need to
13067                                // keep a per user state associated with the permission. Also the
13068                                // revoke on upgrade flag is no longer applicable and is reset.
13069                                final boolean revokeOnUpgrade = (flags & PackageManager
13070                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
13071                                if (revokeOnUpgrade) {
13072                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13073                                    // Since we changed the flags, we have to write.
13074                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13075                                            changedRuntimePermissionUserIds, userId);
13076                                }
13077                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
13078                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
13079                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
13080                                        // If we cannot put the permission as it was,
13081                                        // we have to write.
13082                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13083                                                changedRuntimePermissionUserIds, userId);
13084                                    }
13085                                }
13086
13087                                // If the app supports runtime permissions no need for a review.
13088                                if (mPermissionReviewRequired
13089                                        && appSupportsRuntimePermissions
13090                                        && (flags & PackageManager
13091                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
13092                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
13093                                    // Since we changed the flags, we have to write.
13094                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13095                                            changedRuntimePermissionUserIds, userId);
13096                                }
13097                            } else if (mPermissionReviewRequired
13098                                    && !appSupportsRuntimePermissions) {
13099                                // For legacy apps that need a permission review, every new
13100                                // runtime permission is granted but it is pending a review.
13101                                // We also need to review only platform defined runtime
13102                                // permissions as these are the only ones the platform knows
13103                                // how to disable the API to simulate revocation as legacy
13104                                // apps don't expect to run with revoked permissions.
13105                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
13106                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
13107                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
13108                                        // We changed the flags, hence have to write.
13109                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13110                                                changedRuntimePermissionUserIds, userId);
13111                                    }
13112                                }
13113                                if (permissionsState.grantRuntimePermission(bp, userId)
13114                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
13115                                    // We changed the permission, hence have to write.
13116                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13117                                            changedRuntimePermissionUserIds, userId);
13118                                }
13119                            }
13120                            // Propagate the permission flags.
13121                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
13122                        }
13123                    } break;
13124
13125                    case GRANT_UPGRADE: {
13126                        // Grant runtime permissions for a previously held install permission.
13127                        PermissionState permissionState = origPermissions
13128                                .getInstallPermissionState(bp.name);
13129                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
13130
13131                        if (origPermissions.revokeInstallPermission(bp)
13132                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
13133                            // We will be transferring the permission flags, so clear them.
13134                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
13135                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
13136                            changedInstallPermission = true;
13137                        }
13138
13139                        // If the permission is not to be promoted to runtime we ignore it and
13140                        // also its other flags as they are not applicable to install permissions.
13141                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
13142                            for (int userId : currentUserIds) {
13143                                if (permissionsState.grantRuntimePermission(bp, userId) !=
13144                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
13145                                    // Transfer the permission flags.
13146                                    permissionsState.updatePermissionFlags(bp, userId,
13147                                            flags, flags);
13148                                    // If we granted the permission, we have to write.
13149                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13150                                            changedRuntimePermissionUserIds, userId);
13151                                }
13152                            }
13153                        }
13154                    } break;
13155
13156                    default: {
13157                        if (packageOfInterest == null
13158                                || packageOfInterest.equals(pkg.packageName)) {
13159                            if (DEBUG_PERMISSIONS) {
13160                                Slog.i(TAG, "Not granting permission " + perm
13161                                        + " to package " + pkg.packageName
13162                                        + " because it was previously installed without");
13163                            }
13164                        }
13165                    } break;
13166                }
13167            } else {
13168                if (permissionsState.revokeInstallPermission(bp) !=
13169                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
13170                    // Also drop the permission flags.
13171                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
13172                            PackageManager.MASK_PERMISSION_FLAGS, 0);
13173                    changedInstallPermission = true;
13174                    Slog.i(TAG, "Un-granting permission " + perm
13175                            + " from package " + pkg.packageName
13176                            + " (protectionLevel=" + bp.protectionLevel
13177                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
13178                            + ")");
13179                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
13180                    // Don't print warning for app op permissions, since it is fine for them
13181                    // not to be granted, there is a UI for the user to decide.
13182                    if (DEBUG_PERMISSIONS
13183                            && (packageOfInterest == null
13184                                    || packageOfInterest.equals(pkg.packageName))) {
13185                        Slog.i(TAG, "Not granting permission " + perm
13186                                + " to package " + pkg.packageName
13187                                + " (protectionLevel=" + bp.protectionLevel
13188                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
13189                                + ")");
13190                    }
13191                }
13192            }
13193        }
13194
13195        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
13196                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
13197            // This is the first that we have heard about this package, so the
13198            // permissions we have now selected are fixed until explicitly
13199            // changed.
13200            ps.installPermissionsFixed = true;
13201        }
13202
13203        // Persist the runtime permissions state for users with changes. If permissions
13204        // were revoked because no app in the shared user declares them we have to
13205        // write synchronously to avoid losing runtime permissions state.
13206        for (int userId : changedRuntimePermissionUserIds) {
13207            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
13208        }
13209    }
13210
13211    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
13212        boolean allowed = false;
13213        final int NP = PackageParser.NEW_PERMISSIONS.length;
13214        for (int ip=0; ip<NP; ip++) {
13215            final PackageParser.NewPermissionInfo npi
13216                    = PackageParser.NEW_PERMISSIONS[ip];
13217            if (npi.name.equals(perm)
13218                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
13219                allowed = true;
13220                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
13221                        + pkg.packageName);
13222                break;
13223            }
13224        }
13225        return allowed;
13226    }
13227
13228    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
13229            BasePermission bp, PermissionsState origPermissions) {
13230        boolean privilegedPermission = (bp.protectionLevel
13231                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
13232        boolean privappPermissionsDisable =
13233                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
13234        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
13235        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
13236        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
13237                && !platformPackage && platformPermission) {
13238            final ArraySet<String> allowedPermissions = SystemConfig.getInstance()
13239                    .getPrivAppPermissions(pkg.packageName);
13240            final boolean whitelisted =
13241                    allowedPermissions != null && allowedPermissions.contains(perm);
13242            if (!whitelisted) {
13243                Slog.w(TAG, "Privileged permission " + perm + " for package "
13244                        + pkg.packageName + " - not in privapp-permissions whitelist");
13245                // Only report violations for apps on system image
13246                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
13247                    // it's only a reportable violation if the permission isn't explicitly denied
13248                    final ArraySet<String> deniedPermissions = SystemConfig.getInstance()
13249                            .getPrivAppDenyPermissions(pkg.packageName);
13250                    final boolean permissionViolation =
13251                            deniedPermissions == null || !deniedPermissions.contains(perm);
13252                    if (permissionViolation) {
13253                        if (mPrivappPermissionsViolations == null) {
13254                            mPrivappPermissionsViolations = new ArraySet<>();
13255                        }
13256                        mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
13257                    } else {
13258                        return false;
13259                    }
13260                }
13261                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
13262                    return false;
13263                }
13264            }
13265        }
13266        boolean allowed = (compareSignatures(
13267                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
13268                        == PackageManager.SIGNATURE_MATCH)
13269                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
13270                        == PackageManager.SIGNATURE_MATCH);
13271        if (!allowed && privilegedPermission) {
13272            if (isSystemApp(pkg)) {
13273                // For updated system applications, a system permission
13274                // is granted only if it had been defined by the original application.
13275                if (pkg.isUpdatedSystemApp()) {
13276                    final PackageSetting sysPs = mSettings
13277                            .getDisabledSystemPkgLPr(pkg.packageName);
13278                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
13279                        // If the original was granted this permission, we take
13280                        // that grant decision as read and propagate it to the
13281                        // update.
13282                        if (sysPs.isPrivileged()) {
13283                            allowed = true;
13284                        }
13285                    } else {
13286                        // The system apk may have been updated with an older
13287                        // version of the one on the data partition, but which
13288                        // granted a new system permission that it didn't have
13289                        // before.  In this case we do want to allow the app to
13290                        // now get the new permission if the ancestral apk is
13291                        // privileged to get it.
13292                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
13293                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
13294                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
13295                                    allowed = true;
13296                                    break;
13297                                }
13298                            }
13299                        }
13300                        // Also if a privileged parent package on the system image or any of
13301                        // its children requested a privileged permission, the updated child
13302                        // packages can also get the permission.
13303                        if (pkg.parentPackage != null) {
13304                            final PackageSetting disabledSysParentPs = mSettings
13305                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
13306                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
13307                                    && disabledSysParentPs.isPrivileged()) {
13308                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
13309                                    allowed = true;
13310                                } else if (disabledSysParentPs.pkg.childPackages != null) {
13311                                    final int count = disabledSysParentPs.pkg.childPackages.size();
13312                                    for (int i = 0; i < count; i++) {
13313                                        PackageParser.Package disabledSysChildPkg =
13314                                                disabledSysParentPs.pkg.childPackages.get(i);
13315                                        if (isPackageRequestingPermission(disabledSysChildPkg,
13316                                                perm)) {
13317                                            allowed = true;
13318                                            break;
13319                                        }
13320                                    }
13321                                }
13322                            }
13323                        }
13324                    }
13325                } else {
13326                    allowed = isPrivilegedApp(pkg);
13327                }
13328            }
13329        }
13330        if (!allowed) {
13331            if (!allowed && (bp.protectionLevel
13332                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
13333                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
13334                // If this was a previously normal/dangerous permission that got moved
13335                // to a system permission as part of the runtime permission redesign, then
13336                // we still want to blindly grant it to old apps.
13337                allowed = true;
13338            }
13339            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
13340                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
13341                // If this permission is to be granted to the system installer and
13342                // this app is an installer, then it gets the permission.
13343                allowed = true;
13344            }
13345            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
13346                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
13347                // If this permission is to be granted to the system verifier and
13348                // this app is a verifier, then it gets the permission.
13349                allowed = true;
13350            }
13351            if (!allowed && (bp.protectionLevel
13352                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
13353                    && isSystemApp(pkg)) {
13354                // Any pre-installed system app is allowed to get this permission.
13355                allowed = true;
13356            }
13357            if (!allowed && (bp.protectionLevel
13358                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
13359                // For development permissions, a development permission
13360                // is granted only if it was already granted.
13361                allowed = origPermissions.hasInstallPermission(perm);
13362            }
13363            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
13364                    && pkg.packageName.equals(mSetupWizardPackage)) {
13365                // If this permission is to be granted to the system setup wizard and
13366                // this app is a setup wizard, then it gets the permission.
13367                allowed = true;
13368            }
13369        }
13370        return allowed;
13371    }
13372
13373    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
13374        final int permCount = pkg.requestedPermissions.size();
13375        for (int j = 0; j < permCount; j++) {
13376            String requestedPermission = pkg.requestedPermissions.get(j);
13377            if (permission.equals(requestedPermission)) {
13378                return true;
13379            }
13380        }
13381        return false;
13382    }
13383
13384    final class ActivityIntentResolver
13385            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
13386        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13387                boolean defaultOnly, int userId) {
13388            if (!sUserManager.exists(userId)) return null;
13389            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
13390            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13391        }
13392
13393        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13394                int userId) {
13395            if (!sUserManager.exists(userId)) return null;
13396            mFlags = flags;
13397            return super.queryIntent(intent, resolvedType,
13398                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13399                    userId);
13400        }
13401
13402        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13403                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
13404            if (!sUserManager.exists(userId)) return null;
13405            if (packageActivities == null) {
13406                return null;
13407            }
13408            mFlags = flags;
13409            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13410            final int N = packageActivities.size();
13411            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
13412                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
13413
13414            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
13415            for (int i = 0; i < N; ++i) {
13416                intentFilters = packageActivities.get(i).intents;
13417                if (intentFilters != null && intentFilters.size() > 0) {
13418                    PackageParser.ActivityIntentInfo[] array =
13419                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
13420                    intentFilters.toArray(array);
13421                    listCut.add(array);
13422                }
13423            }
13424            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13425        }
13426
13427        /**
13428         * Finds a privileged activity that matches the specified activity names.
13429         */
13430        private PackageParser.Activity findMatchingActivity(
13431                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
13432            for (PackageParser.Activity sysActivity : activityList) {
13433                if (sysActivity.info.name.equals(activityInfo.name)) {
13434                    return sysActivity;
13435                }
13436                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
13437                    return sysActivity;
13438                }
13439                if (sysActivity.info.targetActivity != null) {
13440                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
13441                        return sysActivity;
13442                    }
13443                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
13444                        return sysActivity;
13445                    }
13446                }
13447            }
13448            return null;
13449        }
13450
13451        public class IterGenerator<E> {
13452            public Iterator<E> generate(ActivityIntentInfo info) {
13453                return null;
13454            }
13455        }
13456
13457        public class ActionIterGenerator extends IterGenerator<String> {
13458            @Override
13459            public Iterator<String> generate(ActivityIntentInfo info) {
13460                return info.actionsIterator();
13461            }
13462        }
13463
13464        public class CategoriesIterGenerator extends IterGenerator<String> {
13465            @Override
13466            public Iterator<String> generate(ActivityIntentInfo info) {
13467                return info.categoriesIterator();
13468            }
13469        }
13470
13471        public class SchemesIterGenerator extends IterGenerator<String> {
13472            @Override
13473            public Iterator<String> generate(ActivityIntentInfo info) {
13474                return info.schemesIterator();
13475            }
13476        }
13477
13478        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
13479            @Override
13480            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
13481                return info.authoritiesIterator();
13482            }
13483        }
13484
13485        /**
13486         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
13487         * MODIFIED. Do not pass in a list that should not be changed.
13488         */
13489        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
13490                IterGenerator<T> generator, Iterator<T> searchIterator) {
13491            // loop through the set of actions; every one must be found in the intent filter
13492            while (searchIterator.hasNext()) {
13493                // we must have at least one filter in the list to consider a match
13494                if (intentList.size() == 0) {
13495                    break;
13496                }
13497
13498                final T searchAction = searchIterator.next();
13499
13500                // loop through the set of intent filters
13501                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
13502                while (intentIter.hasNext()) {
13503                    final ActivityIntentInfo intentInfo = intentIter.next();
13504                    boolean selectionFound = false;
13505
13506                    // loop through the intent filter's selection criteria; at least one
13507                    // of them must match the searched criteria
13508                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
13509                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
13510                        final T intentSelection = intentSelectionIter.next();
13511                        if (intentSelection != null && intentSelection.equals(searchAction)) {
13512                            selectionFound = true;
13513                            break;
13514                        }
13515                    }
13516
13517                    // the selection criteria wasn't found in this filter's set; this filter
13518                    // is not a potential match
13519                    if (!selectionFound) {
13520                        intentIter.remove();
13521                    }
13522                }
13523            }
13524        }
13525
13526        private boolean isProtectedAction(ActivityIntentInfo filter) {
13527            final Iterator<String> actionsIter = filter.actionsIterator();
13528            while (actionsIter != null && actionsIter.hasNext()) {
13529                final String filterAction = actionsIter.next();
13530                if (PROTECTED_ACTIONS.contains(filterAction)) {
13531                    return true;
13532                }
13533            }
13534            return false;
13535        }
13536
13537        /**
13538         * Adjusts the priority of the given intent filter according to policy.
13539         * <p>
13540         * <ul>
13541         * <li>The priority for non privileged applications is capped to '0'</li>
13542         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
13543         * <li>The priority for unbundled updates to privileged applications is capped to the
13544         *      priority defined on the system partition</li>
13545         * </ul>
13546         * <p>
13547         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
13548         * allowed to obtain any priority on any action.
13549         */
13550        private void adjustPriority(
13551                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
13552            // nothing to do; priority is fine as-is
13553            if (intent.getPriority() <= 0) {
13554                return;
13555            }
13556
13557            final ActivityInfo activityInfo = intent.activity.info;
13558            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
13559
13560            final boolean privilegedApp =
13561                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
13562            if (!privilegedApp) {
13563                // non-privileged applications can never define a priority >0
13564                if (DEBUG_FILTERS) {
13565                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
13566                            + " package: " + applicationInfo.packageName
13567                            + " activity: " + intent.activity.className
13568                            + " origPrio: " + intent.getPriority());
13569                }
13570                intent.setPriority(0);
13571                return;
13572            }
13573
13574            if (systemActivities == null) {
13575                // the system package is not disabled; we're parsing the system partition
13576                if (isProtectedAction(intent)) {
13577                    if (mDeferProtectedFilters) {
13578                        // We can't deal with these just yet. No component should ever obtain a
13579                        // >0 priority for a protected actions, with ONE exception -- the setup
13580                        // wizard. The setup wizard, however, cannot be known until we're able to
13581                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
13582                        // until all intent filters have been processed. Chicken, meet egg.
13583                        // Let the filter temporarily have a high priority and rectify the
13584                        // priorities after all system packages have been scanned.
13585                        mProtectedFilters.add(intent);
13586                        if (DEBUG_FILTERS) {
13587                            Slog.i(TAG, "Protected action; save for later;"
13588                                    + " package: " + applicationInfo.packageName
13589                                    + " activity: " + intent.activity.className
13590                                    + " origPrio: " + intent.getPriority());
13591                        }
13592                        return;
13593                    } else {
13594                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13595                            Slog.i(TAG, "No setup wizard;"
13596                                + " All protected intents capped to priority 0");
13597                        }
13598                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13599                            if (DEBUG_FILTERS) {
13600                                Slog.i(TAG, "Found setup wizard;"
13601                                    + " allow priority " + intent.getPriority() + ";"
13602                                    + " package: " + intent.activity.info.packageName
13603                                    + " activity: " + intent.activity.className
13604                                    + " priority: " + intent.getPriority());
13605                            }
13606                            // setup wizard gets whatever it wants
13607                            return;
13608                        }
13609                        if (DEBUG_FILTERS) {
13610                            Slog.i(TAG, "Protected action; cap priority to 0;"
13611                                    + " package: " + intent.activity.info.packageName
13612                                    + " activity: " + intent.activity.className
13613                                    + " origPrio: " + intent.getPriority());
13614                        }
13615                        intent.setPriority(0);
13616                        return;
13617                    }
13618                }
13619                // privileged apps on the system image get whatever priority they request
13620                return;
13621            }
13622
13623            // privileged app unbundled update ... try to find the same activity
13624            final PackageParser.Activity foundActivity =
13625                    findMatchingActivity(systemActivities, activityInfo);
13626            if (foundActivity == null) {
13627                // this is a new activity; it cannot obtain >0 priority
13628                if (DEBUG_FILTERS) {
13629                    Slog.i(TAG, "New activity; cap priority to 0;"
13630                            + " package: " + applicationInfo.packageName
13631                            + " activity: " + intent.activity.className
13632                            + " origPrio: " + intent.getPriority());
13633                }
13634                intent.setPriority(0);
13635                return;
13636            }
13637
13638            // found activity, now check for filter equivalence
13639
13640            // a shallow copy is enough; we modify the list, not its contents
13641            final List<ActivityIntentInfo> intentListCopy =
13642                    new ArrayList<>(foundActivity.intents);
13643            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13644
13645            // find matching action subsets
13646            final Iterator<String> actionsIterator = intent.actionsIterator();
13647            if (actionsIterator != null) {
13648                getIntentListSubset(
13649                        intentListCopy, new ActionIterGenerator(), actionsIterator);
13650                if (intentListCopy.size() == 0) {
13651                    // no more intents to match; we're not equivalent
13652                    if (DEBUG_FILTERS) {
13653                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
13654                                + " package: " + applicationInfo.packageName
13655                                + " activity: " + intent.activity.className
13656                                + " origPrio: " + intent.getPriority());
13657                    }
13658                    intent.setPriority(0);
13659                    return;
13660                }
13661            }
13662
13663            // find matching category subsets
13664            final Iterator<String> categoriesIterator = intent.categoriesIterator();
13665            if (categoriesIterator != null) {
13666                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13667                        categoriesIterator);
13668                if (intentListCopy.size() == 0) {
13669                    // no more intents to match; we're not equivalent
13670                    if (DEBUG_FILTERS) {
13671                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
13672                                + " package: " + applicationInfo.packageName
13673                                + " activity: " + intent.activity.className
13674                                + " origPrio: " + intent.getPriority());
13675                    }
13676                    intent.setPriority(0);
13677                    return;
13678                }
13679            }
13680
13681            // find matching schemes subsets
13682            final Iterator<String> schemesIterator = intent.schemesIterator();
13683            if (schemesIterator != null) {
13684                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13685                        schemesIterator);
13686                if (intentListCopy.size() == 0) {
13687                    // no more intents to match; we're not equivalent
13688                    if (DEBUG_FILTERS) {
13689                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
13690                                + " package: " + applicationInfo.packageName
13691                                + " activity: " + intent.activity.className
13692                                + " origPrio: " + intent.getPriority());
13693                    }
13694                    intent.setPriority(0);
13695                    return;
13696                }
13697            }
13698
13699            // find matching authorities subsets
13700            final Iterator<IntentFilter.AuthorityEntry>
13701                    authoritiesIterator = intent.authoritiesIterator();
13702            if (authoritiesIterator != null) {
13703                getIntentListSubset(intentListCopy,
13704                        new AuthoritiesIterGenerator(),
13705                        authoritiesIterator);
13706                if (intentListCopy.size() == 0) {
13707                    // no more intents to match; we're not equivalent
13708                    if (DEBUG_FILTERS) {
13709                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13710                                + " package: " + applicationInfo.packageName
13711                                + " activity: " + intent.activity.className
13712                                + " origPrio: " + intent.getPriority());
13713                    }
13714                    intent.setPriority(0);
13715                    return;
13716                }
13717            }
13718
13719            // we found matching filter(s); app gets the max priority of all intents
13720            int cappedPriority = 0;
13721            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13722                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13723            }
13724            if (intent.getPriority() > cappedPriority) {
13725                if (DEBUG_FILTERS) {
13726                    Slog.i(TAG, "Found matching filter(s);"
13727                            + " cap priority to " + cappedPriority + ";"
13728                            + " package: " + applicationInfo.packageName
13729                            + " activity: " + intent.activity.className
13730                            + " origPrio: " + intent.getPriority());
13731                }
13732                intent.setPriority(cappedPriority);
13733                return;
13734            }
13735            // all this for nothing; the requested priority was <= what was on the system
13736        }
13737
13738        public final void addActivity(PackageParser.Activity a, String type) {
13739            mActivities.put(a.getComponentName(), a);
13740            if (DEBUG_SHOW_INFO)
13741                Log.v(
13742                TAG, "  " + type + " " +
13743                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13744            if (DEBUG_SHOW_INFO)
13745                Log.v(TAG, "    Class=" + a.info.name);
13746            final int NI = a.intents.size();
13747            for (int j=0; j<NI; j++) {
13748                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13749                if ("activity".equals(type)) {
13750                    final PackageSetting ps =
13751                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13752                    final List<PackageParser.Activity> systemActivities =
13753                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
13754                    adjustPriority(systemActivities, intent);
13755                }
13756                if (DEBUG_SHOW_INFO) {
13757                    Log.v(TAG, "    IntentFilter:");
13758                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13759                }
13760                if (!intent.debugCheck()) {
13761                    Log.w(TAG, "==> For Activity " + a.info.name);
13762                }
13763                addFilter(intent);
13764            }
13765        }
13766
13767        public final void removeActivity(PackageParser.Activity a, String type) {
13768            mActivities.remove(a.getComponentName());
13769            if (DEBUG_SHOW_INFO) {
13770                Log.v(TAG, "  " + type + " "
13771                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13772                                : a.info.name) + ":");
13773                Log.v(TAG, "    Class=" + a.info.name);
13774            }
13775            final int NI = a.intents.size();
13776            for (int j=0; j<NI; j++) {
13777                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13778                if (DEBUG_SHOW_INFO) {
13779                    Log.v(TAG, "    IntentFilter:");
13780                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13781                }
13782                removeFilter(intent);
13783            }
13784        }
13785
13786        @Override
13787        protected boolean allowFilterResult(
13788                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13789            ActivityInfo filterAi = filter.activity.info;
13790            for (int i=dest.size()-1; i>=0; i--) {
13791                ActivityInfo destAi = dest.get(i).activityInfo;
13792                if (destAi.name == filterAi.name
13793                        && destAi.packageName == filterAi.packageName) {
13794                    return false;
13795                }
13796            }
13797            return true;
13798        }
13799
13800        @Override
13801        protected ActivityIntentInfo[] newArray(int size) {
13802            return new ActivityIntentInfo[size];
13803        }
13804
13805        @Override
13806        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13807            if (!sUserManager.exists(userId)) return true;
13808            PackageParser.Package p = filter.activity.owner;
13809            if (p != null) {
13810                PackageSetting ps = (PackageSetting)p.mExtras;
13811                if (ps != null) {
13812                    // System apps are never considered stopped for purposes of
13813                    // filtering, because there may be no way for the user to
13814                    // actually re-launch them.
13815                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13816                            && ps.getStopped(userId);
13817                }
13818            }
13819            return false;
13820        }
13821
13822        @Override
13823        protected boolean isPackageForFilter(String packageName,
13824                PackageParser.ActivityIntentInfo info) {
13825            return packageName.equals(info.activity.owner.packageName);
13826        }
13827
13828        @Override
13829        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13830                int match, int userId) {
13831            if (!sUserManager.exists(userId)) return null;
13832            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13833                return null;
13834            }
13835            final PackageParser.Activity activity = info.activity;
13836            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13837            if (ps == null) {
13838                return null;
13839            }
13840            final PackageUserState userState = ps.readUserState(userId);
13841            ActivityInfo ai =
13842                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13843            if (ai == null) {
13844                return null;
13845            }
13846            final boolean matchExplicitlyVisibleOnly =
13847                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13848            final boolean matchVisibleToInstantApp =
13849                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13850            final boolean componentVisible =
13851                    matchVisibleToInstantApp
13852                    && info.isVisibleToInstantApp()
13853                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13854            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13855            // throw out filters that aren't visible to ephemeral apps
13856            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13857                return null;
13858            }
13859            // throw out instant app filters if we're not explicitly requesting them
13860            if (!matchInstantApp && userState.instantApp) {
13861                return null;
13862            }
13863            // throw out instant app filters if updates are available; will trigger
13864            // instant app resolution
13865            if (userState.instantApp && ps.isUpdateAvailable()) {
13866                return null;
13867            }
13868            final ResolveInfo res = new ResolveInfo();
13869            res.activityInfo = ai;
13870            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13871                res.filter = info;
13872            }
13873            if (info != null) {
13874                res.handleAllWebDataURI = info.handleAllWebDataURI();
13875            }
13876            res.priority = info.getPriority();
13877            res.preferredOrder = activity.owner.mPreferredOrder;
13878            //System.out.println("Result: " + res.activityInfo.className +
13879            //                   " = " + res.priority);
13880            res.match = match;
13881            res.isDefault = info.hasDefault;
13882            res.labelRes = info.labelRes;
13883            res.nonLocalizedLabel = info.nonLocalizedLabel;
13884            if (userNeedsBadging(userId)) {
13885                res.noResourceId = true;
13886            } else {
13887                res.icon = info.icon;
13888            }
13889            res.iconResourceId = info.icon;
13890            res.system = res.activityInfo.applicationInfo.isSystemApp();
13891            res.isInstantAppAvailable = userState.instantApp;
13892            return res;
13893        }
13894
13895        @Override
13896        protected void sortResults(List<ResolveInfo> results) {
13897            Collections.sort(results, mResolvePrioritySorter);
13898        }
13899
13900        @Override
13901        protected void dumpFilter(PrintWriter out, String prefix,
13902                PackageParser.ActivityIntentInfo filter) {
13903            out.print(prefix); out.print(
13904                    Integer.toHexString(System.identityHashCode(filter.activity)));
13905                    out.print(' ');
13906                    filter.activity.printComponentShortName(out);
13907                    out.print(" filter ");
13908                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13909        }
13910
13911        @Override
13912        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13913            return filter.activity;
13914        }
13915
13916        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13917            PackageParser.Activity activity = (PackageParser.Activity)label;
13918            out.print(prefix); out.print(
13919                    Integer.toHexString(System.identityHashCode(activity)));
13920                    out.print(' ');
13921                    activity.printComponentShortName(out);
13922            if (count > 1) {
13923                out.print(" ("); out.print(count); out.print(" filters)");
13924            }
13925            out.println();
13926        }
13927
13928        // Keys are String (activity class name), values are Activity.
13929        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13930                = new ArrayMap<ComponentName, PackageParser.Activity>();
13931        private int mFlags;
13932    }
13933
13934    private final class ServiceIntentResolver
13935            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13936        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13937                boolean defaultOnly, int userId) {
13938            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13939            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13940        }
13941
13942        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13943                int userId) {
13944            if (!sUserManager.exists(userId)) return null;
13945            mFlags = flags;
13946            return super.queryIntent(intent, resolvedType,
13947                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13948                    userId);
13949        }
13950
13951        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13952                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13953            if (!sUserManager.exists(userId)) return null;
13954            if (packageServices == null) {
13955                return null;
13956            }
13957            mFlags = flags;
13958            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13959            final int N = packageServices.size();
13960            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13961                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13962
13963            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13964            for (int i = 0; i < N; ++i) {
13965                intentFilters = packageServices.get(i).intents;
13966                if (intentFilters != null && intentFilters.size() > 0) {
13967                    PackageParser.ServiceIntentInfo[] array =
13968                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
13969                    intentFilters.toArray(array);
13970                    listCut.add(array);
13971                }
13972            }
13973            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13974        }
13975
13976        public final void addService(PackageParser.Service s) {
13977            mServices.put(s.getComponentName(), s);
13978            if (DEBUG_SHOW_INFO) {
13979                Log.v(TAG, "  "
13980                        + (s.info.nonLocalizedLabel != null
13981                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13982                Log.v(TAG, "    Class=" + s.info.name);
13983            }
13984            final int NI = s.intents.size();
13985            int j;
13986            for (j=0; j<NI; j++) {
13987                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13988                if (DEBUG_SHOW_INFO) {
13989                    Log.v(TAG, "    IntentFilter:");
13990                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13991                }
13992                if (!intent.debugCheck()) {
13993                    Log.w(TAG, "==> For Service " + s.info.name);
13994                }
13995                addFilter(intent);
13996            }
13997        }
13998
13999        public final void removeService(PackageParser.Service s) {
14000            mServices.remove(s.getComponentName());
14001            if (DEBUG_SHOW_INFO) {
14002                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
14003                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
14004                Log.v(TAG, "    Class=" + s.info.name);
14005            }
14006            final int NI = s.intents.size();
14007            int j;
14008            for (j=0; j<NI; j++) {
14009                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
14010                if (DEBUG_SHOW_INFO) {
14011                    Log.v(TAG, "    IntentFilter:");
14012                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14013                }
14014                removeFilter(intent);
14015            }
14016        }
14017
14018        @Override
14019        protected boolean allowFilterResult(
14020                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
14021            ServiceInfo filterSi = filter.service.info;
14022            for (int i=dest.size()-1; i>=0; i--) {
14023                ServiceInfo destAi = dest.get(i).serviceInfo;
14024                if (destAi.name == filterSi.name
14025                        && destAi.packageName == filterSi.packageName) {
14026                    return false;
14027                }
14028            }
14029            return true;
14030        }
14031
14032        @Override
14033        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
14034            return new PackageParser.ServiceIntentInfo[size];
14035        }
14036
14037        @Override
14038        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
14039            if (!sUserManager.exists(userId)) return true;
14040            PackageParser.Package p = filter.service.owner;
14041            if (p != null) {
14042                PackageSetting ps = (PackageSetting)p.mExtras;
14043                if (ps != null) {
14044                    // System apps are never considered stopped for purposes of
14045                    // filtering, because there may be no way for the user to
14046                    // actually re-launch them.
14047                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
14048                            && ps.getStopped(userId);
14049                }
14050            }
14051            return false;
14052        }
14053
14054        @Override
14055        protected boolean isPackageForFilter(String packageName,
14056                PackageParser.ServiceIntentInfo info) {
14057            return packageName.equals(info.service.owner.packageName);
14058        }
14059
14060        @Override
14061        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
14062                int match, int userId) {
14063            if (!sUserManager.exists(userId)) return null;
14064            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
14065            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
14066                return null;
14067            }
14068            final PackageParser.Service service = info.service;
14069            PackageSetting ps = (PackageSetting) service.owner.mExtras;
14070            if (ps == null) {
14071                return null;
14072            }
14073            final PackageUserState userState = ps.readUserState(userId);
14074            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
14075                    userState, userId);
14076            if (si == null) {
14077                return null;
14078            }
14079            final boolean matchVisibleToInstantApp =
14080                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
14081            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
14082            // throw out filters that aren't visible to ephemeral apps
14083            if (matchVisibleToInstantApp
14084                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
14085                return null;
14086            }
14087            // throw out ephemeral filters if we're not explicitly requesting them
14088            if (!isInstantApp && userState.instantApp) {
14089                return null;
14090            }
14091            // throw out instant app filters if updates are available; will trigger
14092            // instant app resolution
14093            if (userState.instantApp && ps.isUpdateAvailable()) {
14094                return null;
14095            }
14096            final ResolveInfo res = new ResolveInfo();
14097            res.serviceInfo = si;
14098            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
14099                res.filter = filter;
14100            }
14101            res.priority = info.getPriority();
14102            res.preferredOrder = service.owner.mPreferredOrder;
14103            res.match = match;
14104            res.isDefault = info.hasDefault;
14105            res.labelRes = info.labelRes;
14106            res.nonLocalizedLabel = info.nonLocalizedLabel;
14107            res.icon = info.icon;
14108            res.system = res.serviceInfo.applicationInfo.isSystemApp();
14109            return res;
14110        }
14111
14112        @Override
14113        protected void sortResults(List<ResolveInfo> results) {
14114            Collections.sort(results, mResolvePrioritySorter);
14115        }
14116
14117        @Override
14118        protected void dumpFilter(PrintWriter out, String prefix,
14119                PackageParser.ServiceIntentInfo filter) {
14120            out.print(prefix); out.print(
14121                    Integer.toHexString(System.identityHashCode(filter.service)));
14122                    out.print(' ');
14123                    filter.service.printComponentShortName(out);
14124                    out.print(" filter ");
14125                    out.println(Integer.toHexString(System.identityHashCode(filter)));
14126        }
14127
14128        @Override
14129        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
14130            return filter.service;
14131        }
14132
14133        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
14134            PackageParser.Service service = (PackageParser.Service)label;
14135            out.print(prefix); out.print(
14136                    Integer.toHexString(System.identityHashCode(service)));
14137                    out.print(' ');
14138                    service.printComponentShortName(out);
14139            if (count > 1) {
14140                out.print(" ("); out.print(count); out.print(" filters)");
14141            }
14142            out.println();
14143        }
14144
14145//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
14146//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
14147//            final List<ResolveInfo> retList = Lists.newArrayList();
14148//            while (i.hasNext()) {
14149//                final ResolveInfo resolveInfo = (ResolveInfo) i;
14150//                if (isEnabledLP(resolveInfo.serviceInfo)) {
14151//                    retList.add(resolveInfo);
14152//                }
14153//            }
14154//            return retList;
14155//        }
14156
14157        // Keys are String (activity class name), values are Activity.
14158        private final ArrayMap<ComponentName, PackageParser.Service> mServices
14159                = new ArrayMap<ComponentName, PackageParser.Service>();
14160        private int mFlags;
14161    }
14162
14163    private final class ProviderIntentResolver
14164            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
14165        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
14166                boolean defaultOnly, int userId) {
14167            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
14168            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
14169        }
14170
14171        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
14172                int userId) {
14173            if (!sUserManager.exists(userId))
14174                return null;
14175            mFlags = flags;
14176            return super.queryIntent(intent, resolvedType,
14177                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
14178                    userId);
14179        }
14180
14181        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
14182                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
14183            if (!sUserManager.exists(userId))
14184                return null;
14185            if (packageProviders == null) {
14186                return null;
14187            }
14188            mFlags = flags;
14189            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
14190            final int N = packageProviders.size();
14191            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
14192                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
14193
14194            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
14195            for (int i = 0; i < N; ++i) {
14196                intentFilters = packageProviders.get(i).intents;
14197                if (intentFilters != null && intentFilters.size() > 0) {
14198                    PackageParser.ProviderIntentInfo[] array =
14199                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
14200                    intentFilters.toArray(array);
14201                    listCut.add(array);
14202                }
14203            }
14204            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
14205        }
14206
14207        public final void addProvider(PackageParser.Provider p) {
14208            if (mProviders.containsKey(p.getComponentName())) {
14209                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
14210                return;
14211            }
14212
14213            mProviders.put(p.getComponentName(), p);
14214            if (DEBUG_SHOW_INFO) {
14215                Log.v(TAG, "  "
14216                        + (p.info.nonLocalizedLabel != null
14217                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
14218                Log.v(TAG, "    Class=" + p.info.name);
14219            }
14220            final int NI = p.intents.size();
14221            int j;
14222            for (j = 0; j < NI; j++) {
14223                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
14224                if (DEBUG_SHOW_INFO) {
14225                    Log.v(TAG, "    IntentFilter:");
14226                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14227                }
14228                if (!intent.debugCheck()) {
14229                    Log.w(TAG, "==> For Provider " + p.info.name);
14230                }
14231                addFilter(intent);
14232            }
14233        }
14234
14235        public final void removeProvider(PackageParser.Provider p) {
14236            mProviders.remove(p.getComponentName());
14237            if (DEBUG_SHOW_INFO) {
14238                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
14239                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
14240                Log.v(TAG, "    Class=" + p.info.name);
14241            }
14242            final int NI = p.intents.size();
14243            int j;
14244            for (j = 0; j < NI; j++) {
14245                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
14246                if (DEBUG_SHOW_INFO) {
14247                    Log.v(TAG, "    IntentFilter:");
14248                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14249                }
14250                removeFilter(intent);
14251            }
14252        }
14253
14254        @Override
14255        protected boolean allowFilterResult(
14256                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
14257            ProviderInfo filterPi = filter.provider.info;
14258            for (int i = dest.size() - 1; i >= 0; i--) {
14259                ProviderInfo destPi = dest.get(i).providerInfo;
14260                if (destPi.name == filterPi.name
14261                        && destPi.packageName == filterPi.packageName) {
14262                    return false;
14263                }
14264            }
14265            return true;
14266        }
14267
14268        @Override
14269        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
14270            return new PackageParser.ProviderIntentInfo[size];
14271        }
14272
14273        @Override
14274        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
14275            if (!sUserManager.exists(userId))
14276                return true;
14277            PackageParser.Package p = filter.provider.owner;
14278            if (p != null) {
14279                PackageSetting ps = (PackageSetting) p.mExtras;
14280                if (ps != null) {
14281                    // System apps are never considered stopped for purposes of
14282                    // filtering, because there may be no way for the user to
14283                    // actually re-launch them.
14284                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
14285                            && ps.getStopped(userId);
14286                }
14287            }
14288            return false;
14289        }
14290
14291        @Override
14292        protected boolean isPackageForFilter(String packageName,
14293                PackageParser.ProviderIntentInfo info) {
14294            return packageName.equals(info.provider.owner.packageName);
14295        }
14296
14297        @Override
14298        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
14299                int match, int userId) {
14300            if (!sUserManager.exists(userId))
14301                return null;
14302            final PackageParser.ProviderIntentInfo info = filter;
14303            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
14304                return null;
14305            }
14306            final PackageParser.Provider provider = info.provider;
14307            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
14308            if (ps == null) {
14309                return null;
14310            }
14311            final PackageUserState userState = ps.readUserState(userId);
14312            final boolean matchVisibleToInstantApp =
14313                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
14314            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
14315            // throw out filters that aren't visible to instant applications
14316            if (matchVisibleToInstantApp
14317                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
14318                return null;
14319            }
14320            // throw out instant application filters if we're not explicitly requesting them
14321            if (!isInstantApp && userState.instantApp) {
14322                return null;
14323            }
14324            // throw out instant application filters if updates are available; will trigger
14325            // instant application resolution
14326            if (userState.instantApp && ps.isUpdateAvailable()) {
14327                return null;
14328            }
14329            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
14330                    userState, userId);
14331            if (pi == null) {
14332                return null;
14333            }
14334            final ResolveInfo res = new ResolveInfo();
14335            res.providerInfo = pi;
14336            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
14337                res.filter = filter;
14338            }
14339            res.priority = info.getPriority();
14340            res.preferredOrder = provider.owner.mPreferredOrder;
14341            res.match = match;
14342            res.isDefault = info.hasDefault;
14343            res.labelRes = info.labelRes;
14344            res.nonLocalizedLabel = info.nonLocalizedLabel;
14345            res.icon = info.icon;
14346            res.system = res.providerInfo.applicationInfo.isSystemApp();
14347            return res;
14348        }
14349
14350        @Override
14351        protected void sortResults(List<ResolveInfo> results) {
14352            Collections.sort(results, mResolvePrioritySorter);
14353        }
14354
14355        @Override
14356        protected void dumpFilter(PrintWriter out, String prefix,
14357                PackageParser.ProviderIntentInfo filter) {
14358            out.print(prefix);
14359            out.print(
14360                    Integer.toHexString(System.identityHashCode(filter.provider)));
14361            out.print(' ');
14362            filter.provider.printComponentShortName(out);
14363            out.print(" filter ");
14364            out.println(Integer.toHexString(System.identityHashCode(filter)));
14365        }
14366
14367        @Override
14368        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
14369            return filter.provider;
14370        }
14371
14372        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
14373            PackageParser.Provider provider = (PackageParser.Provider)label;
14374            out.print(prefix); out.print(
14375                    Integer.toHexString(System.identityHashCode(provider)));
14376                    out.print(' ');
14377                    provider.printComponentShortName(out);
14378            if (count > 1) {
14379                out.print(" ("); out.print(count); out.print(" filters)");
14380            }
14381            out.println();
14382        }
14383
14384        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
14385                = new ArrayMap<ComponentName, PackageParser.Provider>();
14386        private int mFlags;
14387    }
14388
14389    static final class EphemeralIntentResolver
14390            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
14391        /**
14392         * The result that has the highest defined order. Ordering applies on a
14393         * per-package basis. Mapping is from package name to Pair of order and
14394         * EphemeralResolveInfo.
14395         * <p>
14396         * NOTE: This is implemented as a field variable for convenience and efficiency.
14397         * By having a field variable, we're able to track filter ordering as soon as
14398         * a non-zero order is defined. Otherwise, multiple loops across the result set
14399         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
14400         * this needs to be contained entirely within {@link #filterResults}.
14401         */
14402        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
14403
14404        @Override
14405        protected AuxiliaryResolveInfo[] newArray(int size) {
14406            return new AuxiliaryResolveInfo[size];
14407        }
14408
14409        @Override
14410        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
14411            return true;
14412        }
14413
14414        @Override
14415        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
14416                int userId) {
14417            if (!sUserManager.exists(userId)) {
14418                return null;
14419            }
14420            final String packageName = responseObj.resolveInfo.getPackageName();
14421            final Integer order = responseObj.getOrder();
14422            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
14423                    mOrderResult.get(packageName);
14424            // ordering is enabled and this item's order isn't high enough
14425            if (lastOrderResult != null && lastOrderResult.first >= order) {
14426                return null;
14427            }
14428            final InstantAppResolveInfo res = responseObj.resolveInfo;
14429            if (order > 0) {
14430                // non-zero order, enable ordering
14431                mOrderResult.put(packageName, new Pair<>(order, res));
14432            }
14433            return responseObj;
14434        }
14435
14436        @Override
14437        protected void filterResults(List<AuxiliaryResolveInfo> results) {
14438            // only do work if ordering is enabled [most of the time it won't be]
14439            if (mOrderResult.size() == 0) {
14440                return;
14441            }
14442            int resultSize = results.size();
14443            for (int i = 0; i < resultSize; i++) {
14444                final InstantAppResolveInfo info = results.get(i).resolveInfo;
14445                final String packageName = info.getPackageName();
14446                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
14447                if (savedInfo == null) {
14448                    // package doesn't having ordering
14449                    continue;
14450                }
14451                if (savedInfo.second == info) {
14452                    // circled back to the highest ordered item; remove from order list
14453                    mOrderResult.remove(packageName);
14454                    if (mOrderResult.size() == 0) {
14455                        // no more ordered items
14456                        break;
14457                    }
14458                    continue;
14459                }
14460                // item has a worse order, remove it from the result list
14461                results.remove(i);
14462                resultSize--;
14463                i--;
14464            }
14465        }
14466    }
14467
14468    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
14469            new Comparator<ResolveInfo>() {
14470        public int compare(ResolveInfo r1, ResolveInfo r2) {
14471            int v1 = r1.priority;
14472            int v2 = r2.priority;
14473            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
14474            if (v1 != v2) {
14475                return (v1 > v2) ? -1 : 1;
14476            }
14477            v1 = r1.preferredOrder;
14478            v2 = r2.preferredOrder;
14479            if (v1 != v2) {
14480                return (v1 > v2) ? -1 : 1;
14481            }
14482            if (r1.isDefault != r2.isDefault) {
14483                return r1.isDefault ? -1 : 1;
14484            }
14485            v1 = r1.match;
14486            v2 = r2.match;
14487            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
14488            if (v1 != v2) {
14489                return (v1 > v2) ? -1 : 1;
14490            }
14491            if (r1.system != r2.system) {
14492                return r1.system ? -1 : 1;
14493            }
14494            if (r1.activityInfo != null) {
14495                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
14496            }
14497            if (r1.serviceInfo != null) {
14498                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
14499            }
14500            if (r1.providerInfo != null) {
14501                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
14502            }
14503            return 0;
14504        }
14505    };
14506
14507    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
14508            new Comparator<ProviderInfo>() {
14509        public int compare(ProviderInfo p1, ProviderInfo p2) {
14510            final int v1 = p1.initOrder;
14511            final int v2 = p2.initOrder;
14512            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
14513        }
14514    };
14515
14516    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
14517            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
14518            final int[] userIds) {
14519        mHandler.post(new Runnable() {
14520            @Override
14521            public void run() {
14522                try {
14523                    final IActivityManager am = ActivityManager.getService();
14524                    if (am == null) return;
14525                    final int[] resolvedUserIds;
14526                    if (userIds == null) {
14527                        resolvedUserIds = am.getRunningUserIds();
14528                    } else {
14529                        resolvedUserIds = userIds;
14530                    }
14531                    for (int id : resolvedUserIds) {
14532                        final Intent intent = new Intent(action,
14533                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
14534                        if (extras != null) {
14535                            intent.putExtras(extras);
14536                        }
14537                        if (targetPkg != null) {
14538                            intent.setPackage(targetPkg);
14539                        }
14540                        // Modify the UID when posting to other users
14541                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
14542                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
14543                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
14544                            intent.putExtra(Intent.EXTRA_UID, uid);
14545                        }
14546                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
14547                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
14548                        if (DEBUG_BROADCASTS) {
14549                            RuntimeException here = new RuntimeException("here");
14550                            here.fillInStackTrace();
14551                            Slog.d(TAG, "Sending to user " + id + ": "
14552                                    + intent.toShortString(false, true, false, false)
14553                                    + " " + intent.getExtras(), here);
14554                        }
14555                        am.broadcastIntent(null, intent, null, finishedReceiver,
14556                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
14557                                null, finishedReceiver != null, false, id);
14558                    }
14559                } catch (RemoteException ex) {
14560                }
14561            }
14562        });
14563    }
14564
14565    /**
14566     * Check if the external storage media is available. This is true if there
14567     * is a mounted external storage medium or if the external storage is
14568     * emulated.
14569     */
14570    private boolean isExternalMediaAvailable() {
14571        return mMediaMounted || Environment.isExternalStorageEmulated();
14572    }
14573
14574    @Override
14575    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
14576        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14577            return null;
14578        }
14579        // writer
14580        synchronized (mPackages) {
14581            if (!isExternalMediaAvailable()) {
14582                // If the external storage is no longer mounted at this point,
14583                // the caller may not have been able to delete all of this
14584                // packages files and can not delete any more.  Bail.
14585                return null;
14586            }
14587            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14588            if (lastPackage != null) {
14589                pkgs.remove(lastPackage);
14590            }
14591            if (pkgs.size() > 0) {
14592                return pkgs.get(0);
14593            }
14594        }
14595        return null;
14596    }
14597
14598    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14599        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14600                userId, andCode ? 1 : 0, packageName);
14601        if (mSystemReady) {
14602            msg.sendToTarget();
14603        } else {
14604            if (mPostSystemReadyMessages == null) {
14605                mPostSystemReadyMessages = new ArrayList<>();
14606            }
14607            mPostSystemReadyMessages.add(msg);
14608        }
14609    }
14610
14611    void startCleaningPackages() {
14612        // reader
14613        if (!isExternalMediaAvailable()) {
14614            return;
14615        }
14616        synchronized (mPackages) {
14617            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14618                return;
14619            }
14620        }
14621        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14622        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14623        IActivityManager am = ActivityManager.getService();
14624        if (am != null) {
14625            int dcsUid = -1;
14626            synchronized (mPackages) {
14627                if (!mDefaultContainerWhitelisted) {
14628                    mDefaultContainerWhitelisted = true;
14629                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14630                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14631                }
14632            }
14633            try {
14634                if (dcsUid > 0) {
14635                    am.backgroundWhitelistUid(dcsUid);
14636                }
14637                am.startService(null, intent, null, false, mContext.getOpPackageName(),
14638                        UserHandle.USER_SYSTEM);
14639            } catch (RemoteException e) {
14640            }
14641        }
14642    }
14643
14644    @Override
14645    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14646            int installFlags, String installerPackageName, int userId) {
14647        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14648
14649        final int callingUid = Binder.getCallingUid();
14650        enforceCrossUserPermission(callingUid, userId,
14651                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14652
14653        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14654            try {
14655                if (observer != null) {
14656                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14657                }
14658            } catch (RemoteException re) {
14659            }
14660            return;
14661        }
14662
14663        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14664            installFlags |= PackageManager.INSTALL_FROM_ADB;
14665
14666        } else {
14667            // Caller holds INSTALL_PACKAGES permission, so we're less strict
14668            // about installerPackageName.
14669
14670            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14671            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14672        }
14673
14674        UserHandle user;
14675        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14676            user = UserHandle.ALL;
14677        } else {
14678            user = new UserHandle(userId);
14679        }
14680
14681        // Only system components can circumvent runtime permissions when installing.
14682        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14683                && mContext.checkCallingOrSelfPermission(Manifest.permission
14684                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14685            throw new SecurityException("You need the "
14686                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14687                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14688        }
14689
14690        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14691                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14692            throw new IllegalArgumentException(
14693                    "New installs into ASEC containers no longer supported");
14694        }
14695
14696        final File originFile = new File(originPath);
14697        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14698
14699        final Message msg = mHandler.obtainMessage(INIT_COPY);
14700        final VerificationInfo verificationInfo = new VerificationInfo(
14701                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14702        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14703                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14704                null /*packageAbiOverride*/, null /*grantedPermissions*/,
14705                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14706        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14707        msg.obj = params;
14708
14709        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14710                System.identityHashCode(msg.obj));
14711        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14712                System.identityHashCode(msg.obj));
14713
14714        mHandler.sendMessage(msg);
14715    }
14716
14717
14718    /**
14719     * Ensure that the install reason matches what we know about the package installer (e.g. whether
14720     * it is acting on behalf on an enterprise or the user).
14721     *
14722     * Note that the ordering of the conditionals in this method is important. The checks we perform
14723     * are as follows, in this order:
14724     *
14725     * 1) If the install is being performed by a system app, we can trust the app to have set the
14726     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14727     *    what it is.
14728     * 2) If the install is being performed by a device or profile owner app, the install reason
14729     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14730     *    set the install reason correctly. If the app targets an older SDK version where install
14731     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14732     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14733     * 3) In all other cases, the install is being performed by a regular app that is neither part
14734     *    of the system nor a device or profile owner. We have no reason to believe that this app is
14735     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14736     *    set to enterprise policy and if so, change it to unknown instead.
14737     */
14738    private int fixUpInstallReason(String installerPackageName, int installerUid,
14739            int installReason) {
14740        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14741                == PERMISSION_GRANTED) {
14742            // If the install is being performed by a system app, we trust that app to have set the
14743            // install reason correctly.
14744            return installReason;
14745        }
14746
14747        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14748            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14749        if (dpm != null) {
14750            ComponentName owner = null;
14751            try {
14752                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14753                if (owner == null) {
14754                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14755                }
14756            } catch (RemoteException e) {
14757            }
14758            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14759                // If the install is being performed by a device or profile owner, the install
14760                // reason should be enterprise policy.
14761                return PackageManager.INSTALL_REASON_POLICY;
14762            }
14763        }
14764
14765        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14766            // If the install is being performed by a regular app (i.e. neither system app nor
14767            // device or profile owner), we have no reason to believe that the app is acting on
14768            // behalf of an enterprise. If the app set the install reason to enterprise policy,
14769            // change it to unknown instead.
14770            return PackageManager.INSTALL_REASON_UNKNOWN;
14771        }
14772
14773        // If the install is being performed by a regular app and the install reason was set to any
14774        // value but enterprise policy, leave the install reason unchanged.
14775        return installReason;
14776    }
14777
14778    void installStage(String packageName, File stagedDir, String stagedCid,
14779            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14780            String installerPackageName, int installerUid, UserHandle user,
14781            Certificate[][] certificates) {
14782        if (DEBUG_EPHEMERAL) {
14783            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14784                Slog.d(TAG, "Ephemeral install of " + packageName);
14785            }
14786        }
14787        final VerificationInfo verificationInfo = new VerificationInfo(
14788                sessionParams.originatingUri, sessionParams.referrerUri,
14789                sessionParams.originatingUid, installerUid);
14790
14791        final OriginInfo origin;
14792        if (stagedDir != null) {
14793            origin = OriginInfo.fromStagedFile(stagedDir);
14794        } else {
14795            origin = OriginInfo.fromStagedContainer(stagedCid);
14796        }
14797
14798        final Message msg = mHandler.obtainMessage(INIT_COPY);
14799        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14800                sessionParams.installReason);
14801        final InstallParams params = new InstallParams(origin, null, observer,
14802                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14803                verificationInfo, user, sessionParams.abiOverride,
14804                sessionParams.grantedRuntimePermissions, certificates, installReason);
14805        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14806        msg.obj = params;
14807
14808        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14809                System.identityHashCode(msg.obj));
14810        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14811                System.identityHashCode(msg.obj));
14812
14813        mHandler.sendMessage(msg);
14814    }
14815
14816    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14817            int userId) {
14818        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14819        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
14820                false /*startReceiver*/, pkgSetting.appId, userId);
14821
14822        // Send a session commit broadcast
14823        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14824        info.installReason = pkgSetting.getInstallReason(userId);
14825        info.appPackageName = packageName;
14826        sendSessionCommitBroadcast(info, userId);
14827    }
14828
14829    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
14830            boolean includeStopped, int appId, int... userIds) {
14831        if (ArrayUtils.isEmpty(userIds)) {
14832            return;
14833        }
14834        Bundle extras = new Bundle(1);
14835        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14836        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14837
14838        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14839                packageName, extras, 0, null, null, userIds);
14840        if (sendBootCompleted) {
14841            mHandler.post(() -> {
14842                        for (int userId : userIds) {
14843                            sendBootCompletedBroadcastToSystemApp(
14844                                    packageName, includeStopped, userId);
14845                        }
14846                    }
14847            );
14848        }
14849    }
14850
14851    /**
14852     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14853     * automatically without needing an explicit launch.
14854     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14855     */
14856    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
14857            int userId) {
14858        // If user is not running, the app didn't miss any broadcast
14859        if (!mUserManagerInternal.isUserRunning(userId)) {
14860            return;
14861        }
14862        final IActivityManager am = ActivityManager.getService();
14863        try {
14864            // Deliver LOCKED_BOOT_COMPLETED first
14865            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14866                    .setPackage(packageName);
14867            if (includeStopped) {
14868                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14869            }
14870            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14871            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14872                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14873
14874            // Deliver BOOT_COMPLETED only if user is unlocked
14875            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14876                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14877                if (includeStopped) {
14878                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14879                }
14880                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14881                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14882            }
14883        } catch (RemoteException e) {
14884            throw e.rethrowFromSystemServer();
14885        }
14886    }
14887
14888    @Override
14889    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14890            int userId) {
14891        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14892        PackageSetting pkgSetting;
14893        final int callingUid = Binder.getCallingUid();
14894        enforceCrossUserPermission(callingUid, userId,
14895                true /* requireFullPermission */, true /* checkShell */,
14896                "setApplicationHiddenSetting for user " + userId);
14897
14898        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14899            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14900            return false;
14901        }
14902
14903        long callingId = Binder.clearCallingIdentity();
14904        try {
14905            boolean sendAdded = false;
14906            boolean sendRemoved = false;
14907            // writer
14908            synchronized (mPackages) {
14909                pkgSetting = mSettings.mPackages.get(packageName);
14910                if (pkgSetting == null) {
14911                    return false;
14912                }
14913                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14914                    return false;
14915                }
14916                // Do not allow "android" is being disabled
14917                if ("android".equals(packageName)) {
14918                    Slog.w(TAG, "Cannot hide package: android");
14919                    return false;
14920                }
14921                // Cannot hide static shared libs as they are considered
14922                // a part of the using app (emulating static linking). Also
14923                // static libs are installed always on internal storage.
14924                PackageParser.Package pkg = mPackages.get(packageName);
14925                if (pkg != null && pkg.staticSharedLibName != null) {
14926                    Slog.w(TAG, "Cannot hide package: " + packageName
14927                            + " providing static shared library: "
14928                            + pkg.staticSharedLibName);
14929                    return false;
14930                }
14931                // Only allow protected packages to hide themselves.
14932                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14933                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14934                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14935                    return false;
14936                }
14937
14938                if (pkgSetting.getHidden(userId) != hidden) {
14939                    pkgSetting.setHidden(hidden, userId);
14940                    mSettings.writePackageRestrictionsLPr(userId);
14941                    if (hidden) {
14942                        sendRemoved = true;
14943                    } else {
14944                        sendAdded = true;
14945                    }
14946                }
14947            }
14948            if (sendAdded) {
14949                sendPackageAddedForUser(packageName, pkgSetting, userId);
14950                return true;
14951            }
14952            if (sendRemoved) {
14953                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14954                        "hiding pkg");
14955                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14956                return true;
14957            }
14958        } finally {
14959            Binder.restoreCallingIdentity(callingId);
14960        }
14961        return false;
14962    }
14963
14964    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14965            int userId) {
14966        final PackageRemovedInfo info = new PackageRemovedInfo(this);
14967        info.removedPackage = packageName;
14968        info.installerPackageName = pkgSetting.installerPackageName;
14969        info.removedUsers = new int[] {userId};
14970        info.broadcastUsers = new int[] {userId};
14971        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14972        info.sendPackageRemovedBroadcasts(true /*killApp*/);
14973    }
14974
14975    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14976        if (pkgList.length > 0) {
14977            Bundle extras = new Bundle(1);
14978            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14979
14980            sendPackageBroadcast(
14981                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14982                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
14983                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14984                    new int[] {userId});
14985        }
14986    }
14987
14988    /**
14989     * Returns true if application is not found or there was an error. Otherwise it returns
14990     * the hidden state of the package for the given user.
14991     */
14992    @Override
14993    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14994        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14995        final int callingUid = Binder.getCallingUid();
14996        enforceCrossUserPermission(callingUid, userId,
14997                true /* requireFullPermission */, false /* checkShell */,
14998                "getApplicationHidden for user " + userId);
14999        PackageSetting ps;
15000        long callingId = Binder.clearCallingIdentity();
15001        try {
15002            // writer
15003            synchronized (mPackages) {
15004                ps = mSettings.mPackages.get(packageName);
15005                if (ps == null) {
15006                    return true;
15007                }
15008                if (filterAppAccessLPr(ps, callingUid, userId)) {
15009                    return true;
15010                }
15011                return ps.getHidden(userId);
15012            }
15013        } finally {
15014            Binder.restoreCallingIdentity(callingId);
15015        }
15016    }
15017
15018    /**
15019     * @hide
15020     */
15021    @Override
15022    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
15023            int installReason) {
15024        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
15025                null);
15026        PackageSetting pkgSetting;
15027        final int callingUid = Binder.getCallingUid();
15028        enforceCrossUserPermission(callingUid, userId,
15029                true /* requireFullPermission */, true /* checkShell */,
15030                "installExistingPackage for user " + userId);
15031        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
15032            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
15033        }
15034
15035        long callingId = Binder.clearCallingIdentity();
15036        try {
15037            boolean installed = false;
15038            final boolean instantApp =
15039                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15040            final boolean fullApp =
15041                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
15042
15043            // writer
15044            synchronized (mPackages) {
15045                pkgSetting = mSettings.mPackages.get(packageName);
15046                if (pkgSetting == null) {
15047                    return PackageManager.INSTALL_FAILED_INVALID_URI;
15048                }
15049                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
15050                    // only allow the existing package to be used if it's installed as a full
15051                    // application for at least one user
15052                    boolean installAllowed = false;
15053                    for (int checkUserId : sUserManager.getUserIds()) {
15054                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
15055                        if (installAllowed) {
15056                            break;
15057                        }
15058                    }
15059                    if (!installAllowed) {
15060                        return PackageManager.INSTALL_FAILED_INVALID_URI;
15061                    }
15062                }
15063                if (!pkgSetting.getInstalled(userId)) {
15064                    pkgSetting.setInstalled(true, userId);
15065                    pkgSetting.setHidden(false, userId);
15066                    pkgSetting.setInstallReason(installReason, userId);
15067                    mSettings.writePackageRestrictionsLPr(userId);
15068                    mSettings.writeKernelMappingLPr(pkgSetting);
15069                    installed = true;
15070                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
15071                    // upgrade app from instant to full; we don't allow app downgrade
15072                    installed = true;
15073                }
15074                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
15075            }
15076
15077            if (installed) {
15078                if (pkgSetting.pkg != null) {
15079                    synchronized (mInstallLock) {
15080                        // We don't need to freeze for a brand new install
15081                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
15082                    }
15083                }
15084                sendPackageAddedForUser(packageName, pkgSetting, userId);
15085                synchronized (mPackages) {
15086                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
15087                }
15088            }
15089        } finally {
15090            Binder.restoreCallingIdentity(callingId);
15091        }
15092
15093        return PackageManager.INSTALL_SUCCEEDED;
15094    }
15095
15096    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
15097            boolean instantApp, boolean fullApp) {
15098        // no state specified; do nothing
15099        if (!instantApp && !fullApp) {
15100            return;
15101        }
15102        if (userId != UserHandle.USER_ALL) {
15103            if (instantApp && !pkgSetting.getInstantApp(userId)) {
15104                pkgSetting.setInstantApp(true /*instantApp*/, userId);
15105            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
15106                pkgSetting.setInstantApp(false /*instantApp*/, userId);
15107            }
15108        } else {
15109            for (int currentUserId : sUserManager.getUserIds()) {
15110                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
15111                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
15112                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
15113                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
15114                }
15115            }
15116        }
15117    }
15118
15119    boolean isUserRestricted(int userId, String restrictionKey) {
15120        Bundle restrictions = sUserManager.getUserRestrictions(userId);
15121        if (restrictions.getBoolean(restrictionKey, false)) {
15122            Log.w(TAG, "User is restricted: " + restrictionKey);
15123            return true;
15124        }
15125        return false;
15126    }
15127
15128    @Override
15129    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
15130            int userId) {
15131        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
15132        final int callingUid = Binder.getCallingUid();
15133        enforceCrossUserPermission(callingUid, userId,
15134                true /* requireFullPermission */, true /* checkShell */,
15135                "setPackagesSuspended for user " + userId);
15136
15137        if (ArrayUtils.isEmpty(packageNames)) {
15138            return packageNames;
15139        }
15140
15141        // List of package names for whom the suspended state has changed.
15142        List<String> changedPackages = new ArrayList<>(packageNames.length);
15143        // List of package names for whom the suspended state is not set as requested in this
15144        // method.
15145        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
15146        long callingId = Binder.clearCallingIdentity();
15147        try {
15148            for (int i = 0; i < packageNames.length; i++) {
15149                String packageName = packageNames[i];
15150                boolean changed = false;
15151                final int appId;
15152                synchronized (mPackages) {
15153                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
15154                    if (pkgSetting == null
15155                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
15156                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
15157                                + "\". Skipping suspending/un-suspending.");
15158                        unactionedPackages.add(packageName);
15159                        continue;
15160                    }
15161                    appId = pkgSetting.appId;
15162                    if (pkgSetting.getSuspended(userId) != suspended) {
15163                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
15164                            unactionedPackages.add(packageName);
15165                            continue;
15166                        }
15167                        pkgSetting.setSuspended(suspended, userId);
15168                        mSettings.writePackageRestrictionsLPr(userId);
15169                        changed = true;
15170                        changedPackages.add(packageName);
15171                    }
15172                }
15173
15174                if (changed && suspended) {
15175                    killApplication(packageName, UserHandle.getUid(userId, appId),
15176                            "suspending package");
15177                }
15178            }
15179        } finally {
15180            Binder.restoreCallingIdentity(callingId);
15181        }
15182
15183        if (!changedPackages.isEmpty()) {
15184            sendPackagesSuspendedForUser(changedPackages.toArray(
15185                    new String[changedPackages.size()]), userId, suspended);
15186        }
15187
15188        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
15189    }
15190
15191    @Override
15192    public boolean isPackageSuspendedForUser(String packageName, int userId) {
15193        final int callingUid = Binder.getCallingUid();
15194        enforceCrossUserPermission(callingUid, userId,
15195                true /* requireFullPermission */, false /* checkShell */,
15196                "isPackageSuspendedForUser for user " + userId);
15197        synchronized (mPackages) {
15198            final PackageSetting ps = mSettings.mPackages.get(packageName);
15199            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
15200                throw new IllegalArgumentException("Unknown target package: " + packageName);
15201            }
15202            return ps.getSuspended(userId);
15203        }
15204    }
15205
15206    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
15207        if (isPackageDeviceAdmin(packageName, userId)) {
15208            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15209                    + "\": has an active device admin");
15210            return false;
15211        }
15212
15213        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
15214        if (packageName.equals(activeLauncherPackageName)) {
15215            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15216                    + "\": contains the active launcher");
15217            return false;
15218        }
15219
15220        if (packageName.equals(mRequiredInstallerPackage)) {
15221            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15222                    + "\": required for package installation");
15223            return false;
15224        }
15225
15226        if (packageName.equals(mRequiredUninstallerPackage)) {
15227            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15228                    + "\": required for package uninstallation");
15229            return false;
15230        }
15231
15232        if (packageName.equals(mRequiredVerifierPackage)) {
15233            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15234                    + "\": required for package verification");
15235            return false;
15236        }
15237
15238        if (packageName.equals(getDefaultDialerPackageName(userId))) {
15239            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15240                    + "\": is the default dialer");
15241            return false;
15242        }
15243
15244        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
15245            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15246                    + "\": protected package");
15247            return false;
15248        }
15249
15250        // Cannot suspend static shared libs as they are considered
15251        // a part of the using app (emulating static linking). Also
15252        // static libs are installed always on internal storage.
15253        PackageParser.Package pkg = mPackages.get(packageName);
15254        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
15255            Slog.w(TAG, "Cannot suspend package: " + packageName
15256                    + " providing static shared library: "
15257                    + pkg.staticSharedLibName);
15258            return false;
15259        }
15260
15261        return true;
15262    }
15263
15264    private String getActiveLauncherPackageName(int userId) {
15265        Intent intent = new Intent(Intent.ACTION_MAIN);
15266        intent.addCategory(Intent.CATEGORY_HOME);
15267        ResolveInfo resolveInfo = resolveIntent(
15268                intent,
15269                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
15270                PackageManager.MATCH_DEFAULT_ONLY,
15271                userId);
15272
15273        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
15274    }
15275
15276    private String getDefaultDialerPackageName(int userId) {
15277        synchronized (mPackages) {
15278            return mSettings.getDefaultDialerPackageNameLPw(userId);
15279        }
15280    }
15281
15282    @Override
15283    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
15284        mContext.enforceCallingOrSelfPermission(
15285                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15286                "Only package verification agents can verify applications");
15287
15288        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
15289        final PackageVerificationResponse response = new PackageVerificationResponse(
15290                verificationCode, Binder.getCallingUid());
15291        msg.arg1 = id;
15292        msg.obj = response;
15293        mHandler.sendMessage(msg);
15294    }
15295
15296    @Override
15297    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
15298            long millisecondsToDelay) {
15299        mContext.enforceCallingOrSelfPermission(
15300                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15301                "Only package verification agents can extend verification timeouts");
15302
15303        final PackageVerificationState state = mPendingVerification.get(id);
15304        final PackageVerificationResponse response = new PackageVerificationResponse(
15305                verificationCodeAtTimeout, Binder.getCallingUid());
15306
15307        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
15308            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
15309        }
15310        if (millisecondsToDelay < 0) {
15311            millisecondsToDelay = 0;
15312        }
15313        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
15314                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
15315            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
15316        }
15317
15318        if ((state != null) && !state.timeoutExtended()) {
15319            state.extendTimeout();
15320
15321            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
15322            msg.arg1 = id;
15323            msg.obj = response;
15324            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
15325        }
15326    }
15327
15328    private void broadcastPackageVerified(int verificationId, Uri packageUri,
15329            int verificationCode, UserHandle user) {
15330        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
15331        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
15332        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15333        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15334        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
15335
15336        mContext.sendBroadcastAsUser(intent, user,
15337                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
15338    }
15339
15340    private ComponentName matchComponentForVerifier(String packageName,
15341            List<ResolveInfo> receivers) {
15342        ActivityInfo targetReceiver = null;
15343
15344        final int NR = receivers.size();
15345        for (int i = 0; i < NR; i++) {
15346            final ResolveInfo info = receivers.get(i);
15347            if (info.activityInfo == null) {
15348                continue;
15349            }
15350
15351            if (packageName.equals(info.activityInfo.packageName)) {
15352                targetReceiver = info.activityInfo;
15353                break;
15354            }
15355        }
15356
15357        if (targetReceiver == null) {
15358            return null;
15359        }
15360
15361        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
15362    }
15363
15364    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
15365            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
15366        if (pkgInfo.verifiers.length == 0) {
15367            return null;
15368        }
15369
15370        final int N = pkgInfo.verifiers.length;
15371        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
15372        for (int i = 0; i < N; i++) {
15373            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
15374
15375            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
15376                    receivers);
15377            if (comp == null) {
15378                continue;
15379            }
15380
15381            final int verifierUid = getUidForVerifier(verifierInfo);
15382            if (verifierUid == -1) {
15383                continue;
15384            }
15385
15386            if (DEBUG_VERIFY) {
15387                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
15388                        + " with the correct signature");
15389            }
15390            sufficientVerifiers.add(comp);
15391            verificationState.addSufficientVerifier(verifierUid);
15392        }
15393
15394        return sufficientVerifiers;
15395    }
15396
15397    private int getUidForVerifier(VerifierInfo verifierInfo) {
15398        synchronized (mPackages) {
15399            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
15400            if (pkg == null) {
15401                return -1;
15402            } else if (pkg.mSignatures.length != 1) {
15403                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15404                        + " has more than one signature; ignoring");
15405                return -1;
15406            }
15407
15408            /*
15409             * If the public key of the package's signature does not match
15410             * our expected public key, then this is a different package and
15411             * we should skip.
15412             */
15413
15414            final byte[] expectedPublicKey;
15415            try {
15416                final Signature verifierSig = pkg.mSignatures[0];
15417                final PublicKey publicKey = verifierSig.getPublicKey();
15418                expectedPublicKey = publicKey.getEncoded();
15419            } catch (CertificateException e) {
15420                return -1;
15421            }
15422
15423            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
15424
15425            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
15426                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15427                        + " does not have the expected public key; ignoring");
15428                return -1;
15429            }
15430
15431            return pkg.applicationInfo.uid;
15432        }
15433    }
15434
15435    @Override
15436    public void finishPackageInstall(int token, boolean didLaunch) {
15437        enforceSystemOrRoot("Only the system is allowed to finish installs");
15438
15439        if (DEBUG_INSTALL) {
15440            Slog.v(TAG, "BM finishing package install for " + token);
15441        }
15442        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15443
15444        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
15445        mHandler.sendMessage(msg);
15446    }
15447
15448    /**
15449     * Get the verification agent timeout.  Used for both the APK verifier and the
15450     * intent filter verifier.
15451     *
15452     * @return verification timeout in milliseconds
15453     */
15454    private long getVerificationTimeout() {
15455        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
15456                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
15457                DEFAULT_VERIFICATION_TIMEOUT);
15458    }
15459
15460    /**
15461     * Get the default verification agent response code.
15462     *
15463     * @return default verification response code
15464     */
15465    private int getDefaultVerificationResponse(UserHandle user) {
15466        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
15467            return PackageManager.VERIFICATION_REJECT;
15468        }
15469        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15470                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
15471                DEFAULT_VERIFICATION_RESPONSE);
15472    }
15473
15474    /**
15475     * Check whether or not package verification has been enabled.
15476     *
15477     * @return true if verification should be performed
15478     */
15479    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
15480        if (!DEFAULT_VERIFY_ENABLE) {
15481            return false;
15482        }
15483
15484        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
15485
15486        // Check if installing from ADB
15487        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
15488            // Do not run verification in a test harness environment
15489            if (ActivityManager.isRunningInTestHarness()) {
15490                return false;
15491            }
15492            if (ensureVerifyAppsEnabled) {
15493                return true;
15494            }
15495            // Check if the developer does not want package verification for ADB installs
15496            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15497                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
15498                return false;
15499            }
15500        } else {
15501            // only when not installed from ADB, skip verification for instant apps when
15502            // the installer and verifier are the same.
15503            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
15504                if (mInstantAppInstallerActivity != null
15505                        && mInstantAppInstallerActivity.packageName.equals(
15506                                mRequiredVerifierPackage)) {
15507                    try {
15508                        mContext.getSystemService(AppOpsManager.class)
15509                                .checkPackage(installerUid, mRequiredVerifierPackage);
15510                        if (DEBUG_VERIFY) {
15511                            Slog.i(TAG, "disable verification for instant app");
15512                        }
15513                        return false;
15514                    } catch (SecurityException ignore) { }
15515                }
15516            }
15517        }
15518
15519        if (ensureVerifyAppsEnabled) {
15520            return true;
15521        }
15522
15523        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15524                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
15525    }
15526
15527    @Override
15528    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
15529            throws RemoteException {
15530        mContext.enforceCallingOrSelfPermission(
15531                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
15532                "Only intentfilter verification agents can verify applications");
15533
15534        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
15535        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
15536                Binder.getCallingUid(), verificationCode, failedDomains);
15537        msg.arg1 = id;
15538        msg.obj = response;
15539        mHandler.sendMessage(msg);
15540    }
15541
15542    @Override
15543    public int getIntentVerificationStatus(String packageName, int userId) {
15544        final int callingUid = Binder.getCallingUid();
15545        if (UserHandle.getUserId(callingUid) != userId) {
15546            mContext.enforceCallingOrSelfPermission(
15547                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15548                    "getIntentVerificationStatus" + userId);
15549        }
15550        if (getInstantAppPackageName(callingUid) != null) {
15551            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15552        }
15553        synchronized (mPackages) {
15554            final PackageSetting ps = mSettings.mPackages.get(packageName);
15555            if (ps == null
15556                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15557                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15558            }
15559            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
15560        }
15561    }
15562
15563    @Override
15564    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
15565        mContext.enforceCallingOrSelfPermission(
15566                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15567
15568        boolean result = false;
15569        synchronized (mPackages) {
15570            final PackageSetting ps = mSettings.mPackages.get(packageName);
15571            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15572                return false;
15573            }
15574            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
15575        }
15576        if (result) {
15577            scheduleWritePackageRestrictionsLocked(userId);
15578        }
15579        return result;
15580    }
15581
15582    @Override
15583    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
15584            String packageName) {
15585        final int callingUid = Binder.getCallingUid();
15586        if (getInstantAppPackageName(callingUid) != null) {
15587            return ParceledListSlice.emptyList();
15588        }
15589        synchronized (mPackages) {
15590            final PackageSetting ps = mSettings.mPackages.get(packageName);
15591            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15592                return ParceledListSlice.emptyList();
15593            }
15594            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
15595        }
15596    }
15597
15598    @Override
15599    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
15600        if (TextUtils.isEmpty(packageName)) {
15601            return ParceledListSlice.emptyList();
15602        }
15603        final int callingUid = Binder.getCallingUid();
15604        final int callingUserId = UserHandle.getUserId(callingUid);
15605        synchronized (mPackages) {
15606            PackageParser.Package pkg = mPackages.get(packageName);
15607            if (pkg == null || pkg.activities == null) {
15608                return ParceledListSlice.emptyList();
15609            }
15610            if (pkg.mExtras == null) {
15611                return ParceledListSlice.emptyList();
15612            }
15613            final PackageSetting ps = (PackageSetting) pkg.mExtras;
15614            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15615                return ParceledListSlice.emptyList();
15616            }
15617            final int count = pkg.activities.size();
15618            ArrayList<IntentFilter> result = new ArrayList<>();
15619            for (int n=0; n<count; n++) {
15620                PackageParser.Activity activity = pkg.activities.get(n);
15621                if (activity.intents != null && activity.intents.size() > 0) {
15622                    result.addAll(activity.intents);
15623                }
15624            }
15625            return new ParceledListSlice<>(result);
15626        }
15627    }
15628
15629    @Override
15630    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15631        mContext.enforceCallingOrSelfPermission(
15632                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15633        if (UserHandle.getCallingUserId() != userId) {
15634            mContext.enforceCallingOrSelfPermission(
15635                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15636        }
15637
15638        synchronized (mPackages) {
15639            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15640            if (packageName != null) {
15641                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
15642                        packageName, userId);
15643            }
15644            return result;
15645        }
15646    }
15647
15648    @Override
15649    public String getDefaultBrowserPackageName(int userId) {
15650        if (UserHandle.getCallingUserId() != userId) {
15651            mContext.enforceCallingOrSelfPermission(
15652                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15653        }
15654        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15655            return null;
15656        }
15657        synchronized (mPackages) {
15658            return mSettings.getDefaultBrowserPackageNameLPw(userId);
15659        }
15660    }
15661
15662    /**
15663     * Get the "allow unknown sources" setting.
15664     *
15665     * @return the current "allow unknown sources" setting
15666     */
15667    private int getUnknownSourcesSettings() {
15668        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15669                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15670                -1);
15671    }
15672
15673    @Override
15674    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15675        final int callingUid = Binder.getCallingUid();
15676        if (getInstantAppPackageName(callingUid) != null) {
15677            return;
15678        }
15679        // writer
15680        synchronized (mPackages) {
15681            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15682            if (targetPackageSetting == null
15683                    || filterAppAccessLPr(
15684                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15685                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15686            }
15687
15688            PackageSetting installerPackageSetting;
15689            if (installerPackageName != null) {
15690                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15691                if (installerPackageSetting == null) {
15692                    throw new IllegalArgumentException("Unknown installer package: "
15693                            + installerPackageName);
15694                }
15695            } else {
15696                installerPackageSetting = null;
15697            }
15698
15699            Signature[] callerSignature;
15700            Object obj = mSettings.getUserIdLPr(callingUid);
15701            if (obj != null) {
15702                if (obj instanceof SharedUserSetting) {
15703                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15704                } else if (obj instanceof PackageSetting) {
15705                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15706                } else {
15707                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15708                }
15709            } else {
15710                throw new SecurityException("Unknown calling UID: " + callingUid);
15711            }
15712
15713            // Verify: can't set installerPackageName to a package that is
15714            // not signed with the same cert as the caller.
15715            if (installerPackageSetting != null) {
15716                if (compareSignatures(callerSignature,
15717                        installerPackageSetting.signatures.mSignatures)
15718                        != PackageManager.SIGNATURE_MATCH) {
15719                    throw new SecurityException(
15720                            "Caller does not have same cert as new installer package "
15721                            + installerPackageName);
15722                }
15723            }
15724
15725            // Verify: if target already has an installer package, it must
15726            // be signed with the same cert as the caller.
15727            if (targetPackageSetting.installerPackageName != null) {
15728                PackageSetting setting = mSettings.mPackages.get(
15729                        targetPackageSetting.installerPackageName);
15730                // If the currently set package isn't valid, then it's always
15731                // okay to change it.
15732                if (setting != null) {
15733                    if (compareSignatures(callerSignature,
15734                            setting.signatures.mSignatures)
15735                            != PackageManager.SIGNATURE_MATCH) {
15736                        throw new SecurityException(
15737                                "Caller does not have same cert as old installer package "
15738                                + targetPackageSetting.installerPackageName);
15739                    }
15740                }
15741            }
15742
15743            // Okay!
15744            targetPackageSetting.installerPackageName = installerPackageName;
15745            if (installerPackageName != null) {
15746                mSettings.mInstallerPackages.add(installerPackageName);
15747            }
15748            scheduleWriteSettingsLocked();
15749        }
15750    }
15751
15752    @Override
15753    public void setApplicationCategoryHint(String packageName, int categoryHint,
15754            String callerPackageName) {
15755        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15756            throw new SecurityException("Instant applications don't have access to this method");
15757        }
15758        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15759                callerPackageName);
15760        synchronized (mPackages) {
15761            PackageSetting ps = mSettings.mPackages.get(packageName);
15762            if (ps == null) {
15763                throw new IllegalArgumentException("Unknown target package " + packageName);
15764            }
15765            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15766                throw new IllegalArgumentException("Unknown target package " + packageName);
15767            }
15768            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15769                throw new IllegalArgumentException("Calling package " + callerPackageName
15770                        + " is not installer for " + packageName);
15771            }
15772
15773            if (ps.categoryHint != categoryHint) {
15774                ps.categoryHint = categoryHint;
15775                scheduleWriteSettingsLocked();
15776            }
15777        }
15778    }
15779
15780    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15781        // Queue up an async operation since the package installation may take a little while.
15782        mHandler.post(new Runnable() {
15783            public void run() {
15784                mHandler.removeCallbacks(this);
15785                 // Result object to be returned
15786                PackageInstalledInfo res = new PackageInstalledInfo();
15787                res.setReturnCode(currentStatus);
15788                res.uid = -1;
15789                res.pkg = null;
15790                res.removedInfo = null;
15791                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15792                    args.doPreInstall(res.returnCode);
15793                    synchronized (mInstallLock) {
15794                        installPackageTracedLI(args, res);
15795                    }
15796                    args.doPostInstall(res.returnCode, res.uid);
15797                }
15798
15799                // A restore should be performed at this point if (a) the install
15800                // succeeded, (b) the operation is not an update, and (c) the new
15801                // package has not opted out of backup participation.
15802                final boolean update = res.removedInfo != null
15803                        && res.removedInfo.removedPackage != null;
15804                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15805                boolean doRestore = !update
15806                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15807
15808                // Set up the post-install work request bookkeeping.  This will be used
15809                // and cleaned up by the post-install event handling regardless of whether
15810                // there's a restore pass performed.  Token values are >= 1.
15811                int token;
15812                if (mNextInstallToken < 0) mNextInstallToken = 1;
15813                token = mNextInstallToken++;
15814
15815                PostInstallData data = new PostInstallData(args, res);
15816                mRunningInstalls.put(token, data);
15817                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15818
15819                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15820                    // Pass responsibility to the Backup Manager.  It will perform a
15821                    // restore if appropriate, then pass responsibility back to the
15822                    // Package Manager to run the post-install observer callbacks
15823                    // and broadcasts.
15824                    IBackupManager bm = IBackupManager.Stub.asInterface(
15825                            ServiceManager.getService(Context.BACKUP_SERVICE));
15826                    if (bm != null) {
15827                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15828                                + " to BM for possible restore");
15829                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15830                        try {
15831                            // TODO: http://b/22388012
15832                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15833                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15834                            } else {
15835                                doRestore = false;
15836                            }
15837                        } catch (RemoteException e) {
15838                            // can't happen; the backup manager is local
15839                        } catch (Exception e) {
15840                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15841                            doRestore = false;
15842                        }
15843                    } else {
15844                        Slog.e(TAG, "Backup Manager not found!");
15845                        doRestore = false;
15846                    }
15847                }
15848
15849                if (!doRestore) {
15850                    // No restore possible, or the Backup Manager was mysteriously not
15851                    // available -- just fire the post-install work request directly.
15852                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15853
15854                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15855
15856                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15857                    mHandler.sendMessage(msg);
15858                }
15859            }
15860        });
15861    }
15862
15863    /**
15864     * Callback from PackageSettings whenever an app is first transitioned out of the
15865     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15866     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15867     * here whether the app is the target of an ongoing install, and only send the
15868     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15869     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15870     * handling.
15871     */
15872    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15873        // Serialize this with the rest of the install-process message chain.  In the
15874        // restore-at-install case, this Runnable will necessarily run before the
15875        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15876        // are coherent.  In the non-restore case, the app has already completed install
15877        // and been launched through some other means, so it is not in a problematic
15878        // state for observers to see the FIRST_LAUNCH signal.
15879        mHandler.post(new Runnable() {
15880            @Override
15881            public void run() {
15882                for (int i = 0; i < mRunningInstalls.size(); i++) {
15883                    final PostInstallData data = mRunningInstalls.valueAt(i);
15884                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15885                        continue;
15886                    }
15887                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15888                        // right package; but is it for the right user?
15889                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15890                            if (userId == data.res.newUsers[uIndex]) {
15891                                if (DEBUG_BACKUP) {
15892                                    Slog.i(TAG, "Package " + pkgName
15893                                            + " being restored so deferring FIRST_LAUNCH");
15894                                }
15895                                return;
15896                            }
15897                        }
15898                    }
15899                }
15900                // didn't find it, so not being restored
15901                if (DEBUG_BACKUP) {
15902                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15903                }
15904                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15905            }
15906        });
15907    }
15908
15909    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15910        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15911                installerPkg, null, userIds);
15912    }
15913
15914    private abstract class HandlerParams {
15915        private static final int MAX_RETRIES = 4;
15916
15917        /**
15918         * Number of times startCopy() has been attempted and had a non-fatal
15919         * error.
15920         */
15921        private int mRetries = 0;
15922
15923        /** User handle for the user requesting the information or installation. */
15924        private final UserHandle mUser;
15925        String traceMethod;
15926        int traceCookie;
15927
15928        HandlerParams(UserHandle user) {
15929            mUser = user;
15930        }
15931
15932        UserHandle getUser() {
15933            return mUser;
15934        }
15935
15936        HandlerParams setTraceMethod(String traceMethod) {
15937            this.traceMethod = traceMethod;
15938            return this;
15939        }
15940
15941        HandlerParams setTraceCookie(int traceCookie) {
15942            this.traceCookie = traceCookie;
15943            return this;
15944        }
15945
15946        final boolean startCopy() {
15947            boolean res;
15948            try {
15949                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15950
15951                if (++mRetries > MAX_RETRIES) {
15952                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15953                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15954                    handleServiceError();
15955                    return false;
15956                } else {
15957                    handleStartCopy();
15958                    res = true;
15959                }
15960            } catch (RemoteException e) {
15961                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15962                mHandler.sendEmptyMessage(MCS_RECONNECT);
15963                res = false;
15964            }
15965            handleReturnCode();
15966            return res;
15967        }
15968
15969        final void serviceError() {
15970            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15971            handleServiceError();
15972            handleReturnCode();
15973        }
15974
15975        abstract void handleStartCopy() throws RemoteException;
15976        abstract void handleServiceError();
15977        abstract void handleReturnCode();
15978    }
15979
15980    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15981        for (File path : paths) {
15982            try {
15983                mcs.clearDirectory(path.getAbsolutePath());
15984            } catch (RemoteException e) {
15985            }
15986        }
15987    }
15988
15989    static class OriginInfo {
15990        /**
15991         * Location where install is coming from, before it has been
15992         * copied/renamed into place. This could be a single monolithic APK
15993         * file, or a cluster directory. This location may be untrusted.
15994         */
15995        final File file;
15996        final String cid;
15997
15998        /**
15999         * Flag indicating that {@link #file} or {@link #cid} has already been
16000         * staged, meaning downstream users don't need to defensively copy the
16001         * contents.
16002         */
16003        final boolean staged;
16004
16005        /**
16006         * Flag indicating that {@link #file} or {@link #cid} is an already
16007         * installed app that is being moved.
16008         */
16009        final boolean existing;
16010
16011        final String resolvedPath;
16012        final File resolvedFile;
16013
16014        static OriginInfo fromNothing() {
16015            return new OriginInfo(null, null, false, false);
16016        }
16017
16018        static OriginInfo fromUntrustedFile(File file) {
16019            return new OriginInfo(file, null, false, false);
16020        }
16021
16022        static OriginInfo fromExistingFile(File file) {
16023            return new OriginInfo(file, null, false, true);
16024        }
16025
16026        static OriginInfo fromStagedFile(File file) {
16027            return new OriginInfo(file, null, true, false);
16028        }
16029
16030        static OriginInfo fromStagedContainer(String cid) {
16031            return new OriginInfo(null, cid, true, false);
16032        }
16033
16034        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
16035            this.file = file;
16036            this.cid = cid;
16037            this.staged = staged;
16038            this.existing = existing;
16039
16040            if (cid != null) {
16041                resolvedPath = PackageHelper.getSdDir(cid);
16042                resolvedFile = new File(resolvedPath);
16043            } else if (file != null) {
16044                resolvedPath = file.getAbsolutePath();
16045                resolvedFile = file;
16046            } else {
16047                resolvedPath = null;
16048                resolvedFile = null;
16049            }
16050        }
16051    }
16052
16053    static class MoveInfo {
16054        final int moveId;
16055        final String fromUuid;
16056        final String toUuid;
16057        final String packageName;
16058        final String dataAppName;
16059        final int appId;
16060        final String seinfo;
16061        final int targetSdkVersion;
16062
16063        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
16064                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
16065            this.moveId = moveId;
16066            this.fromUuid = fromUuid;
16067            this.toUuid = toUuid;
16068            this.packageName = packageName;
16069            this.dataAppName = dataAppName;
16070            this.appId = appId;
16071            this.seinfo = seinfo;
16072            this.targetSdkVersion = targetSdkVersion;
16073        }
16074    }
16075
16076    static class VerificationInfo {
16077        /** A constant used to indicate that a uid value is not present. */
16078        public static final int NO_UID = -1;
16079
16080        /** URI referencing where the package was downloaded from. */
16081        final Uri originatingUri;
16082
16083        /** HTTP referrer URI associated with the originatingURI. */
16084        final Uri referrer;
16085
16086        /** UID of the application that the install request originated from. */
16087        final int originatingUid;
16088
16089        /** UID of application requesting the install */
16090        final int installerUid;
16091
16092        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
16093            this.originatingUri = originatingUri;
16094            this.referrer = referrer;
16095            this.originatingUid = originatingUid;
16096            this.installerUid = installerUid;
16097        }
16098    }
16099
16100    class InstallParams extends HandlerParams {
16101        final OriginInfo origin;
16102        final MoveInfo move;
16103        final IPackageInstallObserver2 observer;
16104        int installFlags;
16105        final String installerPackageName;
16106        final String volumeUuid;
16107        private InstallArgs mArgs;
16108        private int mRet;
16109        final String packageAbiOverride;
16110        final String[] grantedRuntimePermissions;
16111        final VerificationInfo verificationInfo;
16112        final Certificate[][] certificates;
16113        final int installReason;
16114
16115        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16116                int installFlags, String installerPackageName, String volumeUuid,
16117                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
16118                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
16119            super(user);
16120            this.origin = origin;
16121            this.move = move;
16122            this.observer = observer;
16123            this.installFlags = installFlags;
16124            this.installerPackageName = installerPackageName;
16125            this.volumeUuid = volumeUuid;
16126            this.verificationInfo = verificationInfo;
16127            this.packageAbiOverride = packageAbiOverride;
16128            this.grantedRuntimePermissions = grantedPermissions;
16129            this.certificates = certificates;
16130            this.installReason = installReason;
16131        }
16132
16133        @Override
16134        public String toString() {
16135            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
16136                    + " file=" + origin.file + " cid=" + origin.cid + "}";
16137        }
16138
16139        private int installLocationPolicy(PackageInfoLite pkgLite) {
16140            String packageName = pkgLite.packageName;
16141            int installLocation = pkgLite.installLocation;
16142            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16143            // reader
16144            synchronized (mPackages) {
16145                // Currently installed package which the new package is attempting to replace or
16146                // null if no such package is installed.
16147                PackageParser.Package installedPkg = mPackages.get(packageName);
16148                // Package which currently owns the data which the new package will own if installed.
16149                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
16150                // will be null whereas dataOwnerPkg will contain information about the package
16151                // which was uninstalled while keeping its data.
16152                PackageParser.Package dataOwnerPkg = installedPkg;
16153                if (dataOwnerPkg  == null) {
16154                    PackageSetting ps = mSettings.mPackages.get(packageName);
16155                    if (ps != null) {
16156                        dataOwnerPkg = ps.pkg;
16157                    }
16158                }
16159
16160                if (dataOwnerPkg != null) {
16161                    // If installed, the package will get access to data left on the device by its
16162                    // predecessor. As a security measure, this is permited only if this is not a
16163                    // version downgrade or if the predecessor package is marked as debuggable and
16164                    // a downgrade is explicitly requested.
16165                    //
16166                    // On debuggable platform builds, downgrades are permitted even for
16167                    // non-debuggable packages to make testing easier. Debuggable platform builds do
16168                    // not offer security guarantees and thus it's OK to disable some security
16169                    // mechanisms to make debugging/testing easier on those builds. However, even on
16170                    // debuggable builds downgrades of packages are permitted only if requested via
16171                    // installFlags. This is because we aim to keep the behavior of debuggable
16172                    // platform builds as close as possible to the behavior of non-debuggable
16173                    // platform builds.
16174                    final boolean downgradeRequested =
16175                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
16176                    final boolean packageDebuggable =
16177                                (dataOwnerPkg.applicationInfo.flags
16178                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
16179                    final boolean downgradePermitted =
16180                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
16181                    if (!downgradePermitted) {
16182                        try {
16183                            checkDowngrade(dataOwnerPkg, pkgLite);
16184                        } catch (PackageManagerException e) {
16185                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
16186                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
16187                        }
16188                    }
16189                }
16190
16191                if (installedPkg != null) {
16192                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16193                        // Check for updated system application.
16194                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16195                            if (onSd) {
16196                                Slog.w(TAG, "Cannot install update to system app on sdcard");
16197                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
16198                            }
16199                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16200                        } else {
16201                            if (onSd) {
16202                                // Install flag overrides everything.
16203                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16204                            }
16205                            // If current upgrade specifies particular preference
16206                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
16207                                // Application explicitly specified internal.
16208                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16209                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
16210                                // App explictly prefers external. Let policy decide
16211                            } else {
16212                                // Prefer previous location
16213                                if (isExternal(installedPkg)) {
16214                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16215                                }
16216                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16217                            }
16218                        }
16219                    } else {
16220                        // Invalid install. Return error code
16221                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
16222                    }
16223                }
16224            }
16225            // All the special cases have been taken care of.
16226            // Return result based on recommended install location.
16227            if (onSd) {
16228                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16229            }
16230            return pkgLite.recommendedInstallLocation;
16231        }
16232
16233        /*
16234         * Invoke remote method to get package information and install
16235         * location values. Override install location based on default
16236         * policy if needed and then create install arguments based
16237         * on the install location.
16238         */
16239        public void handleStartCopy() throws RemoteException {
16240            int ret = PackageManager.INSTALL_SUCCEEDED;
16241
16242            // If we're already staged, we've firmly committed to an install location
16243            if (origin.staged) {
16244                if (origin.file != null) {
16245                    installFlags |= PackageManager.INSTALL_INTERNAL;
16246                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
16247                } else if (origin.cid != null) {
16248                    installFlags |= PackageManager.INSTALL_EXTERNAL;
16249                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
16250                } else {
16251                    throw new IllegalStateException("Invalid stage location");
16252                }
16253            }
16254
16255            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16256            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
16257            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16258            PackageInfoLite pkgLite = null;
16259
16260            if (onInt && onSd) {
16261                // Check if both bits are set.
16262                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
16263                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16264            } else if (onSd && ephemeral) {
16265                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
16266                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16267            } else {
16268                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
16269                        packageAbiOverride);
16270
16271                if (DEBUG_EPHEMERAL && ephemeral) {
16272                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
16273                }
16274
16275                /*
16276                 * If we have too little free space, try to free cache
16277                 * before giving up.
16278                 */
16279                if (!origin.staged && pkgLite.recommendedInstallLocation
16280                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
16281                    // TODO: focus freeing disk space on the target device
16282                    final StorageManager storage = StorageManager.from(mContext);
16283                    final long lowThreshold = storage.getStorageLowBytes(
16284                            Environment.getDataDirectory());
16285
16286                    final long sizeBytes = mContainerService.calculateInstalledSize(
16287                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
16288
16289                    try {
16290                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
16291                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
16292                                installFlags, packageAbiOverride);
16293                    } catch (InstallerException e) {
16294                        Slog.w(TAG, "Failed to free cache", e);
16295                    }
16296
16297                    /*
16298                     * The cache free must have deleted the file we
16299                     * downloaded to install.
16300                     *
16301                     * TODO: fix the "freeCache" call to not delete
16302                     *       the file we care about.
16303                     */
16304                    if (pkgLite.recommendedInstallLocation
16305                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
16306                        pkgLite.recommendedInstallLocation
16307                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
16308                    }
16309                }
16310            }
16311
16312            if (ret == PackageManager.INSTALL_SUCCEEDED) {
16313                int loc = pkgLite.recommendedInstallLocation;
16314                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
16315                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16316                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
16317                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
16318                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
16319                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16320                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
16321                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
16322                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
16323                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
16324                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
16325                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
16326                } else {
16327                    // Override with defaults if needed.
16328                    loc = installLocationPolicy(pkgLite);
16329                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
16330                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
16331                    } else if (!onSd && !onInt) {
16332                        // Override install location with flags
16333                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
16334                            // Set the flag to install on external media.
16335                            installFlags |= PackageManager.INSTALL_EXTERNAL;
16336                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
16337                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
16338                            if (DEBUG_EPHEMERAL) {
16339                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
16340                            }
16341                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
16342                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
16343                                    |PackageManager.INSTALL_INTERNAL);
16344                        } else {
16345                            // Make sure the flag for installing on external
16346                            // media is unset
16347                            installFlags |= PackageManager.INSTALL_INTERNAL;
16348                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
16349                        }
16350                    }
16351                }
16352            }
16353
16354            final InstallArgs args = createInstallArgs(this);
16355            mArgs = args;
16356
16357            if (ret == PackageManager.INSTALL_SUCCEEDED) {
16358                // TODO: http://b/22976637
16359                // Apps installed for "all" users use the device owner to verify the app
16360                UserHandle verifierUser = getUser();
16361                if (verifierUser == UserHandle.ALL) {
16362                    verifierUser = UserHandle.SYSTEM;
16363                }
16364
16365                /*
16366                 * Determine if we have any installed package verifiers. If we
16367                 * do, then we'll defer to them to verify the packages.
16368                 */
16369                final int requiredUid = mRequiredVerifierPackage == null ? -1
16370                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
16371                                verifierUser.getIdentifier());
16372                final int installerUid =
16373                        verificationInfo == null ? -1 : verificationInfo.installerUid;
16374                if (!origin.existing && requiredUid != -1
16375                        && isVerificationEnabled(
16376                                verifierUser.getIdentifier(), installFlags, installerUid)) {
16377                    final Intent verification = new Intent(
16378                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
16379                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
16380                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
16381                            PACKAGE_MIME_TYPE);
16382                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
16383
16384                    // Query all live verifiers based on current user state
16385                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
16386                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
16387                            false /*allowDynamicSplits*/);
16388
16389                    if (DEBUG_VERIFY) {
16390                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
16391                                + verification.toString() + " with " + pkgLite.verifiers.length
16392                                + " optional verifiers");
16393                    }
16394
16395                    final int verificationId = mPendingVerificationToken++;
16396
16397                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
16398
16399                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
16400                            installerPackageName);
16401
16402                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
16403                            installFlags);
16404
16405                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
16406                            pkgLite.packageName);
16407
16408                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
16409                            pkgLite.versionCode);
16410
16411                    if (verificationInfo != null) {
16412                        if (verificationInfo.originatingUri != null) {
16413                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
16414                                    verificationInfo.originatingUri);
16415                        }
16416                        if (verificationInfo.referrer != null) {
16417                            verification.putExtra(Intent.EXTRA_REFERRER,
16418                                    verificationInfo.referrer);
16419                        }
16420                        if (verificationInfo.originatingUid >= 0) {
16421                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
16422                                    verificationInfo.originatingUid);
16423                        }
16424                        if (verificationInfo.installerUid >= 0) {
16425                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
16426                                    verificationInfo.installerUid);
16427                        }
16428                    }
16429
16430                    final PackageVerificationState verificationState = new PackageVerificationState(
16431                            requiredUid, args);
16432
16433                    mPendingVerification.append(verificationId, verificationState);
16434
16435                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
16436                            receivers, verificationState);
16437
16438                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
16439                    final long idleDuration = getVerificationTimeout();
16440
16441                    /*
16442                     * If any sufficient verifiers were listed in the package
16443                     * manifest, attempt to ask them.
16444                     */
16445                    if (sufficientVerifiers != null) {
16446                        final int N = sufficientVerifiers.size();
16447                        if (N == 0) {
16448                            Slog.i(TAG, "Additional verifiers required, but none installed.");
16449                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
16450                        } else {
16451                            for (int i = 0; i < N; i++) {
16452                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
16453                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16454                                        verifierComponent.getPackageName(), idleDuration,
16455                                        verifierUser.getIdentifier(), false, "package verifier");
16456
16457                                final Intent sufficientIntent = new Intent(verification);
16458                                sufficientIntent.setComponent(verifierComponent);
16459                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
16460                            }
16461                        }
16462                    }
16463
16464                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
16465                            mRequiredVerifierPackage, receivers);
16466                    if (ret == PackageManager.INSTALL_SUCCEEDED
16467                            && mRequiredVerifierPackage != null) {
16468                        Trace.asyncTraceBegin(
16469                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
16470                        /*
16471                         * Send the intent to the required verification agent,
16472                         * but only start the verification timeout after the
16473                         * target BroadcastReceivers have run.
16474                         */
16475                        verification.setComponent(requiredVerifierComponent);
16476                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16477                                mRequiredVerifierPackage, idleDuration,
16478                                verifierUser.getIdentifier(), false, "package verifier");
16479                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
16480                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16481                                new BroadcastReceiver() {
16482                                    @Override
16483                                    public void onReceive(Context context, Intent intent) {
16484                                        final Message msg = mHandler
16485                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
16486                                        msg.arg1 = verificationId;
16487                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
16488                                    }
16489                                }, null, 0, null, null);
16490
16491                        /*
16492                         * We don't want the copy to proceed until verification
16493                         * succeeds, so null out this field.
16494                         */
16495                        mArgs = null;
16496                    }
16497                } else {
16498                    /*
16499                     * No package verification is enabled, so immediately start
16500                     * the remote call to initiate copy using temporary file.
16501                     */
16502                    ret = args.copyApk(mContainerService, true);
16503                }
16504            }
16505
16506            mRet = ret;
16507        }
16508
16509        @Override
16510        void handleReturnCode() {
16511            // If mArgs is null, then MCS couldn't be reached. When it
16512            // reconnects, it will try again to install. At that point, this
16513            // will succeed.
16514            if (mArgs != null) {
16515                processPendingInstall(mArgs, mRet);
16516            }
16517        }
16518
16519        @Override
16520        void handleServiceError() {
16521            mArgs = createInstallArgs(this);
16522            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16523        }
16524
16525        public boolean isForwardLocked() {
16526            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16527        }
16528    }
16529
16530    /**
16531     * Used during creation of InstallArgs
16532     *
16533     * @param installFlags package installation flags
16534     * @return true if should be installed on external storage
16535     */
16536    private static boolean installOnExternalAsec(int installFlags) {
16537        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
16538            return false;
16539        }
16540        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
16541            return true;
16542        }
16543        return false;
16544    }
16545
16546    /**
16547     * Used during creation of InstallArgs
16548     *
16549     * @param installFlags package installation flags
16550     * @return true if should be installed as forward locked
16551     */
16552    private static boolean installForwardLocked(int installFlags) {
16553        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16554    }
16555
16556    private InstallArgs createInstallArgs(InstallParams params) {
16557        if (params.move != null) {
16558            return new MoveInstallArgs(params);
16559        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
16560            return new AsecInstallArgs(params);
16561        } else {
16562            return new FileInstallArgs(params);
16563        }
16564    }
16565
16566    /**
16567     * Create args that describe an existing installed package. Typically used
16568     * when cleaning up old installs, or used as a move source.
16569     */
16570    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
16571            String resourcePath, String[] instructionSets) {
16572        final boolean isInAsec;
16573        if (installOnExternalAsec(installFlags)) {
16574            /* Apps on SD card are always in ASEC containers. */
16575            isInAsec = true;
16576        } else if (installForwardLocked(installFlags)
16577                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
16578            /*
16579             * Forward-locked apps are only in ASEC containers if they're the
16580             * new style
16581             */
16582            isInAsec = true;
16583        } else {
16584            isInAsec = false;
16585        }
16586
16587        if (isInAsec) {
16588            return new AsecInstallArgs(codePath, instructionSets,
16589                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
16590        } else {
16591            return new FileInstallArgs(codePath, resourcePath, instructionSets);
16592        }
16593    }
16594
16595    static abstract class InstallArgs {
16596        /** @see InstallParams#origin */
16597        final OriginInfo origin;
16598        /** @see InstallParams#move */
16599        final MoveInfo move;
16600
16601        final IPackageInstallObserver2 observer;
16602        // Always refers to PackageManager flags only
16603        final int installFlags;
16604        final String installerPackageName;
16605        final String volumeUuid;
16606        final UserHandle user;
16607        final String abiOverride;
16608        final String[] installGrantPermissions;
16609        /** If non-null, drop an async trace when the install completes */
16610        final String traceMethod;
16611        final int traceCookie;
16612        final Certificate[][] certificates;
16613        final int installReason;
16614
16615        // The list of instruction sets supported by this app. This is currently
16616        // only used during the rmdex() phase to clean up resources. We can get rid of this
16617        // if we move dex files under the common app path.
16618        /* nullable */ String[] instructionSets;
16619
16620        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16621                int installFlags, String installerPackageName, String volumeUuid,
16622                UserHandle user, String[] instructionSets,
16623                String abiOverride, String[] installGrantPermissions,
16624                String traceMethod, int traceCookie, Certificate[][] certificates,
16625                int installReason) {
16626            this.origin = origin;
16627            this.move = move;
16628            this.installFlags = installFlags;
16629            this.observer = observer;
16630            this.installerPackageName = installerPackageName;
16631            this.volumeUuid = volumeUuid;
16632            this.user = user;
16633            this.instructionSets = instructionSets;
16634            this.abiOverride = abiOverride;
16635            this.installGrantPermissions = installGrantPermissions;
16636            this.traceMethod = traceMethod;
16637            this.traceCookie = traceCookie;
16638            this.certificates = certificates;
16639            this.installReason = installReason;
16640        }
16641
16642        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16643        abstract int doPreInstall(int status);
16644
16645        /**
16646         * Rename package into final resting place. All paths on the given
16647         * scanned package should be updated to reflect the rename.
16648         */
16649        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16650        abstract int doPostInstall(int status, int uid);
16651
16652        /** @see PackageSettingBase#codePathString */
16653        abstract String getCodePath();
16654        /** @see PackageSettingBase#resourcePathString */
16655        abstract String getResourcePath();
16656
16657        // Need installer lock especially for dex file removal.
16658        abstract void cleanUpResourcesLI();
16659        abstract boolean doPostDeleteLI(boolean delete);
16660
16661        /**
16662         * Called before the source arguments are copied. This is used mostly
16663         * for MoveParams when it needs to read the source file to put it in the
16664         * destination.
16665         */
16666        int doPreCopy() {
16667            return PackageManager.INSTALL_SUCCEEDED;
16668        }
16669
16670        /**
16671         * Called after the source arguments are copied. This is used mostly for
16672         * MoveParams when it needs to read the source file to put it in the
16673         * destination.
16674         */
16675        int doPostCopy(int uid) {
16676            return PackageManager.INSTALL_SUCCEEDED;
16677        }
16678
16679        protected boolean isFwdLocked() {
16680            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16681        }
16682
16683        protected boolean isExternalAsec() {
16684            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16685        }
16686
16687        protected boolean isEphemeral() {
16688            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16689        }
16690
16691        UserHandle getUser() {
16692            return user;
16693        }
16694    }
16695
16696    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16697        if (!allCodePaths.isEmpty()) {
16698            if (instructionSets == null) {
16699                throw new IllegalStateException("instructionSet == null");
16700            }
16701            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16702            for (String codePath : allCodePaths) {
16703                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16704                    try {
16705                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
16706                    } catch (InstallerException ignored) {
16707                    }
16708                }
16709            }
16710        }
16711    }
16712
16713    /**
16714     * Logic to handle installation of non-ASEC applications, including copying
16715     * and renaming logic.
16716     */
16717    class FileInstallArgs extends InstallArgs {
16718        private File codeFile;
16719        private File resourceFile;
16720
16721        // Example topology:
16722        // /data/app/com.example/base.apk
16723        // /data/app/com.example/split_foo.apk
16724        // /data/app/com.example/lib/arm/libfoo.so
16725        // /data/app/com.example/lib/arm64/libfoo.so
16726        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16727
16728        /** New install */
16729        FileInstallArgs(InstallParams params) {
16730            super(params.origin, params.move, params.observer, params.installFlags,
16731                    params.installerPackageName, params.volumeUuid,
16732                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16733                    params.grantedRuntimePermissions,
16734                    params.traceMethod, params.traceCookie, params.certificates,
16735                    params.installReason);
16736            if (isFwdLocked()) {
16737                throw new IllegalArgumentException("Forward locking only supported in ASEC");
16738            }
16739        }
16740
16741        /** Existing install */
16742        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16743            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16744                    null, null, null, 0, null /*certificates*/,
16745                    PackageManager.INSTALL_REASON_UNKNOWN);
16746            this.codeFile = (codePath != null) ? new File(codePath) : null;
16747            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16748        }
16749
16750        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16751            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16752            try {
16753                return doCopyApk(imcs, temp);
16754            } finally {
16755                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16756            }
16757        }
16758
16759        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16760            if (origin.staged) {
16761                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16762                codeFile = origin.file;
16763                resourceFile = origin.file;
16764                return PackageManager.INSTALL_SUCCEEDED;
16765            }
16766
16767            try {
16768                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16769                final File tempDir =
16770                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16771                codeFile = tempDir;
16772                resourceFile = tempDir;
16773            } catch (IOException e) {
16774                Slog.w(TAG, "Failed to create copy file: " + e);
16775                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16776            }
16777
16778            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16779                @Override
16780                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16781                    if (!FileUtils.isValidExtFilename(name)) {
16782                        throw new IllegalArgumentException("Invalid filename: " + name);
16783                    }
16784                    try {
16785                        final File file = new File(codeFile, name);
16786                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16787                                O_RDWR | O_CREAT, 0644);
16788                        Os.chmod(file.getAbsolutePath(), 0644);
16789                        return new ParcelFileDescriptor(fd);
16790                    } catch (ErrnoException e) {
16791                        throw new RemoteException("Failed to open: " + e.getMessage());
16792                    }
16793                }
16794            };
16795
16796            int ret = PackageManager.INSTALL_SUCCEEDED;
16797            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16798            if (ret != PackageManager.INSTALL_SUCCEEDED) {
16799                Slog.e(TAG, "Failed to copy package");
16800                return ret;
16801            }
16802
16803            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16804            NativeLibraryHelper.Handle handle = null;
16805            try {
16806                handle = NativeLibraryHelper.Handle.create(codeFile);
16807                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16808                        abiOverride);
16809            } catch (IOException e) {
16810                Slog.e(TAG, "Copying native libraries failed", e);
16811                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16812            } finally {
16813                IoUtils.closeQuietly(handle);
16814            }
16815
16816            return ret;
16817        }
16818
16819        int doPreInstall(int status) {
16820            if (status != PackageManager.INSTALL_SUCCEEDED) {
16821                cleanUp();
16822            }
16823            return status;
16824        }
16825
16826        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16827            if (status != PackageManager.INSTALL_SUCCEEDED) {
16828                cleanUp();
16829                return false;
16830            }
16831
16832            final File targetDir = codeFile.getParentFile();
16833            final File beforeCodeFile = codeFile;
16834            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16835
16836            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16837            try {
16838                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16839            } catch (ErrnoException e) {
16840                Slog.w(TAG, "Failed to rename", e);
16841                return false;
16842            }
16843
16844            if (!SELinux.restoreconRecursive(afterCodeFile)) {
16845                Slog.w(TAG, "Failed to restorecon");
16846                return false;
16847            }
16848
16849            // Reflect the rename internally
16850            codeFile = afterCodeFile;
16851            resourceFile = afterCodeFile;
16852
16853            // Reflect the rename in scanned details
16854            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16855            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16856                    afterCodeFile, pkg.baseCodePath));
16857            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16858                    afterCodeFile, pkg.splitCodePaths));
16859
16860            // Reflect the rename in app info
16861            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16862            pkg.setApplicationInfoCodePath(pkg.codePath);
16863            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16864            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16865            pkg.setApplicationInfoResourcePath(pkg.codePath);
16866            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16867            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16868
16869            return true;
16870        }
16871
16872        int doPostInstall(int status, int uid) {
16873            if (status != PackageManager.INSTALL_SUCCEEDED) {
16874                cleanUp();
16875            }
16876            return status;
16877        }
16878
16879        @Override
16880        String getCodePath() {
16881            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16882        }
16883
16884        @Override
16885        String getResourcePath() {
16886            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16887        }
16888
16889        private boolean cleanUp() {
16890            if (codeFile == null || !codeFile.exists()) {
16891                return false;
16892            }
16893
16894            removeCodePathLI(codeFile);
16895
16896            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16897                resourceFile.delete();
16898            }
16899
16900            return true;
16901        }
16902
16903        void cleanUpResourcesLI() {
16904            // Try enumerating all code paths before deleting
16905            List<String> allCodePaths = Collections.EMPTY_LIST;
16906            if (codeFile != null && codeFile.exists()) {
16907                try {
16908                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16909                    allCodePaths = pkg.getAllCodePaths();
16910                } catch (PackageParserException e) {
16911                    // Ignored; we tried our best
16912                }
16913            }
16914
16915            cleanUp();
16916            removeDexFiles(allCodePaths, instructionSets);
16917        }
16918
16919        boolean doPostDeleteLI(boolean delete) {
16920            // XXX err, shouldn't we respect the delete flag?
16921            cleanUpResourcesLI();
16922            return true;
16923        }
16924    }
16925
16926    private boolean isAsecExternal(String cid) {
16927        final String asecPath = PackageHelper.getSdFilesystem(cid);
16928        return !asecPath.startsWith(mAsecInternalPath);
16929    }
16930
16931    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16932            PackageManagerException {
16933        if (copyRet < 0) {
16934            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16935                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16936                throw new PackageManagerException(copyRet, message);
16937            }
16938        }
16939    }
16940
16941    /**
16942     * Extract the StorageManagerService "container ID" from the full code path of an
16943     * .apk.
16944     */
16945    static String cidFromCodePath(String fullCodePath) {
16946        int eidx = fullCodePath.lastIndexOf("/");
16947        String subStr1 = fullCodePath.substring(0, eidx);
16948        int sidx = subStr1.lastIndexOf("/");
16949        return subStr1.substring(sidx+1, eidx);
16950    }
16951
16952    /**
16953     * Logic to handle installation of ASEC applications, including copying and
16954     * renaming logic.
16955     */
16956    class AsecInstallArgs extends InstallArgs {
16957        static final String RES_FILE_NAME = "pkg.apk";
16958        static final String PUBLIC_RES_FILE_NAME = "res.zip";
16959
16960        String cid;
16961        String packagePath;
16962        String resourcePath;
16963
16964        /** New install */
16965        AsecInstallArgs(InstallParams params) {
16966            super(params.origin, params.move, params.observer, params.installFlags,
16967                    params.installerPackageName, params.volumeUuid,
16968                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16969                    params.grantedRuntimePermissions,
16970                    params.traceMethod, params.traceCookie, params.certificates,
16971                    params.installReason);
16972        }
16973
16974        /** Existing install */
16975        AsecInstallArgs(String fullCodePath, String[] instructionSets,
16976                        boolean isExternal, boolean isForwardLocked) {
16977            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
16978                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16979                    instructionSets, null, null, null, 0, null /*certificates*/,
16980                    PackageManager.INSTALL_REASON_UNKNOWN);
16981            // Hackily pretend we're still looking at a full code path
16982            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
16983                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
16984            }
16985
16986            // Extract cid from fullCodePath
16987            int eidx = fullCodePath.lastIndexOf("/");
16988            String subStr1 = fullCodePath.substring(0, eidx);
16989            int sidx = subStr1.lastIndexOf("/");
16990            cid = subStr1.substring(sidx+1, eidx);
16991            setMountPath(subStr1);
16992        }
16993
16994        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
16995            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
16996                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16997                    instructionSets, null, null, null, 0, null /*certificates*/,
16998                    PackageManager.INSTALL_REASON_UNKNOWN);
16999            this.cid = cid;
17000            setMountPath(PackageHelper.getSdDir(cid));
17001        }
17002
17003        void createCopyFile() {
17004            cid = mInstallerService.allocateExternalStageCidLegacy();
17005        }
17006
17007        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
17008            if (origin.staged && origin.cid != null) {
17009                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
17010                cid = origin.cid;
17011                setMountPath(PackageHelper.getSdDir(cid));
17012                return PackageManager.INSTALL_SUCCEEDED;
17013            }
17014
17015            if (temp) {
17016                createCopyFile();
17017            } else {
17018                /*
17019                 * Pre-emptively destroy the container since it's destroyed if
17020                 * copying fails due to it existing anyway.
17021                 */
17022                PackageHelper.destroySdDir(cid);
17023            }
17024
17025            final String newMountPath = imcs.copyPackageToContainer(
17026                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
17027                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
17028
17029            if (newMountPath != null) {
17030                setMountPath(newMountPath);
17031                return PackageManager.INSTALL_SUCCEEDED;
17032            } else {
17033                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17034            }
17035        }
17036
17037        @Override
17038        String getCodePath() {
17039            return packagePath;
17040        }
17041
17042        @Override
17043        String getResourcePath() {
17044            return resourcePath;
17045        }
17046
17047        int doPreInstall(int status) {
17048            if (status != PackageManager.INSTALL_SUCCEEDED) {
17049                // Destroy container
17050                PackageHelper.destroySdDir(cid);
17051            } else {
17052                boolean mounted = PackageHelper.isContainerMounted(cid);
17053                if (!mounted) {
17054                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
17055                            Process.SYSTEM_UID);
17056                    if (newMountPath != null) {
17057                        setMountPath(newMountPath);
17058                    } else {
17059                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17060                    }
17061                }
17062            }
17063            return status;
17064        }
17065
17066        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
17067            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
17068            String newMountPath = null;
17069            if (PackageHelper.isContainerMounted(cid)) {
17070                // Unmount the container
17071                if (!PackageHelper.unMountSdDir(cid)) {
17072                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
17073                    return false;
17074                }
17075            }
17076            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
17077                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
17078                        " which might be stale. Will try to clean up.");
17079                // Clean up the stale container and proceed to recreate.
17080                if (!PackageHelper.destroySdDir(newCacheId)) {
17081                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
17082                    return false;
17083                }
17084                // Successfully cleaned up stale container. Try to rename again.
17085                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
17086                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
17087                            + " inspite of cleaning it up.");
17088                    return false;
17089                }
17090            }
17091            if (!PackageHelper.isContainerMounted(newCacheId)) {
17092                Slog.w(TAG, "Mounting container " + newCacheId);
17093                newMountPath = PackageHelper.mountSdDir(newCacheId,
17094                        getEncryptKey(), Process.SYSTEM_UID);
17095            } else {
17096                newMountPath = PackageHelper.getSdDir(newCacheId);
17097            }
17098            if (newMountPath == null) {
17099                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
17100                return false;
17101            }
17102            Log.i(TAG, "Succesfully renamed " + cid +
17103                    " to " + newCacheId +
17104                    " at new path: " + newMountPath);
17105            cid = newCacheId;
17106
17107            final File beforeCodeFile = new File(packagePath);
17108            setMountPath(newMountPath);
17109            final File afterCodeFile = new File(packagePath);
17110
17111            // Reflect the rename in scanned details
17112            pkg.setCodePath(afterCodeFile.getAbsolutePath());
17113            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
17114                    afterCodeFile, pkg.baseCodePath));
17115            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
17116                    afterCodeFile, pkg.splitCodePaths));
17117
17118            // Reflect the rename in app info
17119            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
17120            pkg.setApplicationInfoCodePath(pkg.codePath);
17121            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
17122            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
17123            pkg.setApplicationInfoResourcePath(pkg.codePath);
17124            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
17125            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
17126
17127            return true;
17128        }
17129
17130        private void setMountPath(String mountPath) {
17131            final File mountFile = new File(mountPath);
17132
17133            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
17134            if (monolithicFile.exists()) {
17135                packagePath = monolithicFile.getAbsolutePath();
17136                if (isFwdLocked()) {
17137                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
17138                } else {
17139                    resourcePath = packagePath;
17140                }
17141            } else {
17142                packagePath = mountFile.getAbsolutePath();
17143                resourcePath = packagePath;
17144            }
17145        }
17146
17147        int doPostInstall(int status, int uid) {
17148            if (status != PackageManager.INSTALL_SUCCEEDED) {
17149                cleanUp();
17150            } else {
17151                final int groupOwner;
17152                final String protectedFile;
17153                if (isFwdLocked()) {
17154                    groupOwner = UserHandle.getSharedAppGid(uid);
17155                    protectedFile = RES_FILE_NAME;
17156                } else {
17157                    groupOwner = -1;
17158                    protectedFile = null;
17159                }
17160
17161                if (uid < Process.FIRST_APPLICATION_UID
17162                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
17163                    Slog.e(TAG, "Failed to finalize " + cid);
17164                    PackageHelper.destroySdDir(cid);
17165                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17166                }
17167
17168                boolean mounted = PackageHelper.isContainerMounted(cid);
17169                if (!mounted) {
17170                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
17171                }
17172            }
17173            return status;
17174        }
17175
17176        private void cleanUp() {
17177            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
17178
17179            // Destroy secure container
17180            PackageHelper.destroySdDir(cid);
17181        }
17182
17183        private List<String> getAllCodePaths() {
17184            final File codeFile = new File(getCodePath());
17185            if (codeFile != null && codeFile.exists()) {
17186                try {
17187                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
17188                    return pkg.getAllCodePaths();
17189                } catch (PackageParserException e) {
17190                    // Ignored; we tried our best
17191                }
17192            }
17193            return Collections.EMPTY_LIST;
17194        }
17195
17196        void cleanUpResourcesLI() {
17197            // Enumerate all code paths before deleting
17198            cleanUpResourcesLI(getAllCodePaths());
17199        }
17200
17201        private void cleanUpResourcesLI(List<String> allCodePaths) {
17202            cleanUp();
17203            removeDexFiles(allCodePaths, instructionSets);
17204        }
17205
17206        String getPackageName() {
17207            return getAsecPackageName(cid);
17208        }
17209
17210        boolean doPostDeleteLI(boolean delete) {
17211            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
17212            final List<String> allCodePaths = getAllCodePaths();
17213            boolean mounted = PackageHelper.isContainerMounted(cid);
17214            if (mounted) {
17215                // Unmount first
17216                if (PackageHelper.unMountSdDir(cid)) {
17217                    mounted = false;
17218                }
17219            }
17220            if (!mounted && delete) {
17221                cleanUpResourcesLI(allCodePaths);
17222            }
17223            return !mounted;
17224        }
17225
17226        @Override
17227        int doPreCopy() {
17228            if (isFwdLocked()) {
17229                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
17230                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
17231                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17232                }
17233            }
17234
17235            return PackageManager.INSTALL_SUCCEEDED;
17236        }
17237
17238        @Override
17239        int doPostCopy(int uid) {
17240            if (isFwdLocked()) {
17241                if (uid < Process.FIRST_APPLICATION_UID
17242                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
17243                                RES_FILE_NAME)) {
17244                    Slog.e(TAG, "Failed to finalize " + cid);
17245                    PackageHelper.destroySdDir(cid);
17246                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17247                }
17248            }
17249
17250            return PackageManager.INSTALL_SUCCEEDED;
17251        }
17252    }
17253
17254    /**
17255     * Logic to handle movement of existing installed applications.
17256     */
17257    class MoveInstallArgs extends InstallArgs {
17258        private File codeFile;
17259        private File resourceFile;
17260
17261        /** New install */
17262        MoveInstallArgs(InstallParams params) {
17263            super(params.origin, params.move, params.observer, params.installFlags,
17264                    params.installerPackageName, params.volumeUuid,
17265                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
17266                    params.grantedRuntimePermissions,
17267                    params.traceMethod, params.traceCookie, params.certificates,
17268                    params.installReason);
17269        }
17270
17271        int copyApk(IMediaContainerService imcs, boolean temp) {
17272            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
17273                    + move.fromUuid + " to " + move.toUuid);
17274            synchronized (mInstaller) {
17275                try {
17276                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
17277                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
17278                } catch (InstallerException e) {
17279                    Slog.w(TAG, "Failed to move app", e);
17280                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
17281                }
17282            }
17283
17284            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
17285            resourceFile = codeFile;
17286            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
17287
17288            return PackageManager.INSTALL_SUCCEEDED;
17289        }
17290
17291        int doPreInstall(int status) {
17292            if (status != PackageManager.INSTALL_SUCCEEDED) {
17293                cleanUp(move.toUuid);
17294            }
17295            return status;
17296        }
17297
17298        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
17299            if (status != PackageManager.INSTALL_SUCCEEDED) {
17300                cleanUp(move.toUuid);
17301                return false;
17302            }
17303
17304            // Reflect the move in app info
17305            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
17306            pkg.setApplicationInfoCodePath(pkg.codePath);
17307            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
17308            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
17309            pkg.setApplicationInfoResourcePath(pkg.codePath);
17310            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
17311            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
17312
17313            return true;
17314        }
17315
17316        int doPostInstall(int status, int uid) {
17317            if (status == PackageManager.INSTALL_SUCCEEDED) {
17318                cleanUp(move.fromUuid);
17319            } else {
17320                cleanUp(move.toUuid);
17321            }
17322            return status;
17323        }
17324
17325        @Override
17326        String getCodePath() {
17327            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
17328        }
17329
17330        @Override
17331        String getResourcePath() {
17332            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
17333        }
17334
17335        private boolean cleanUp(String volumeUuid) {
17336            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
17337                    move.dataAppName);
17338            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
17339            final int[] userIds = sUserManager.getUserIds();
17340            synchronized (mInstallLock) {
17341                // Clean up both app data and code
17342                // All package moves are frozen until finished
17343                for (int userId : userIds) {
17344                    try {
17345                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
17346                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
17347                    } catch (InstallerException e) {
17348                        Slog.w(TAG, String.valueOf(e));
17349                    }
17350                }
17351                removeCodePathLI(codeFile);
17352            }
17353            return true;
17354        }
17355
17356        void cleanUpResourcesLI() {
17357            throw new UnsupportedOperationException();
17358        }
17359
17360        boolean doPostDeleteLI(boolean delete) {
17361            throw new UnsupportedOperationException();
17362        }
17363    }
17364
17365    static String getAsecPackageName(String packageCid) {
17366        int idx = packageCid.lastIndexOf("-");
17367        if (idx == -1) {
17368            return packageCid;
17369        }
17370        return packageCid.substring(0, idx);
17371    }
17372
17373    // Utility method used to create code paths based on package name and available index.
17374    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
17375        String idxStr = "";
17376        int idx = 1;
17377        // Fall back to default value of idx=1 if prefix is not
17378        // part of oldCodePath
17379        if (oldCodePath != null) {
17380            String subStr = oldCodePath;
17381            // Drop the suffix right away
17382            if (suffix != null && subStr.endsWith(suffix)) {
17383                subStr = subStr.substring(0, subStr.length() - suffix.length());
17384            }
17385            // If oldCodePath already contains prefix find out the
17386            // ending index to either increment or decrement.
17387            int sidx = subStr.lastIndexOf(prefix);
17388            if (sidx != -1) {
17389                subStr = subStr.substring(sidx + prefix.length());
17390                if (subStr != null) {
17391                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
17392                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
17393                    }
17394                    try {
17395                        idx = Integer.parseInt(subStr);
17396                        if (idx <= 1) {
17397                            idx++;
17398                        } else {
17399                            idx--;
17400                        }
17401                    } catch(NumberFormatException e) {
17402                    }
17403                }
17404            }
17405        }
17406        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
17407        return prefix + idxStr;
17408    }
17409
17410    private File getNextCodePath(File targetDir, String packageName) {
17411        File result;
17412        SecureRandom random = new SecureRandom();
17413        byte[] bytes = new byte[16];
17414        do {
17415            random.nextBytes(bytes);
17416            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
17417            result = new File(targetDir, packageName + "-" + suffix);
17418        } while (result.exists());
17419        return result;
17420    }
17421
17422    // Utility method that returns the relative package path with respect
17423    // to the installation directory. Like say for /data/data/com.test-1.apk
17424    // string com.test-1 is returned.
17425    static String deriveCodePathName(String codePath) {
17426        if (codePath == null) {
17427            return null;
17428        }
17429        final File codeFile = new File(codePath);
17430        final String name = codeFile.getName();
17431        if (codeFile.isDirectory()) {
17432            return name;
17433        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
17434            final int lastDot = name.lastIndexOf('.');
17435            return name.substring(0, lastDot);
17436        } else {
17437            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
17438            return null;
17439        }
17440    }
17441
17442    static class PackageInstalledInfo {
17443        String name;
17444        int uid;
17445        // The set of users that originally had this package installed.
17446        int[] origUsers;
17447        // The set of users that now have this package installed.
17448        int[] newUsers;
17449        PackageParser.Package pkg;
17450        int returnCode;
17451        String returnMsg;
17452        String installerPackageName;
17453        PackageRemovedInfo removedInfo;
17454        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
17455
17456        public void setError(int code, String msg) {
17457            setReturnCode(code);
17458            setReturnMessage(msg);
17459            Slog.w(TAG, msg);
17460        }
17461
17462        public void setError(String msg, PackageParserException e) {
17463            setReturnCode(e.error);
17464            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17465            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17466            for (int i = 0; i < childCount; i++) {
17467                addedChildPackages.valueAt(i).setError(msg, e);
17468            }
17469            Slog.w(TAG, msg, e);
17470        }
17471
17472        public void setError(String msg, PackageManagerException e) {
17473            returnCode = e.error;
17474            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17475            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17476            for (int i = 0; i < childCount; i++) {
17477                addedChildPackages.valueAt(i).setError(msg, e);
17478            }
17479            Slog.w(TAG, msg, e);
17480        }
17481
17482        public void setReturnCode(int returnCode) {
17483            this.returnCode = returnCode;
17484            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17485            for (int i = 0; i < childCount; i++) {
17486                addedChildPackages.valueAt(i).returnCode = returnCode;
17487            }
17488        }
17489
17490        private void setReturnMessage(String returnMsg) {
17491            this.returnMsg = returnMsg;
17492            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17493            for (int i = 0; i < childCount; i++) {
17494                addedChildPackages.valueAt(i).returnMsg = returnMsg;
17495            }
17496        }
17497
17498        // In some error cases we want to convey more info back to the observer
17499        String origPackage;
17500        String origPermission;
17501    }
17502
17503    /*
17504     * Install a non-existing package.
17505     */
17506    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
17507            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
17508            PackageInstalledInfo res, int installReason) {
17509        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
17510
17511        // Remember this for later, in case we need to rollback this install
17512        String pkgName = pkg.packageName;
17513
17514        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
17515
17516        synchronized(mPackages) {
17517            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
17518            if (renamedPackage != null) {
17519                // A package with the same name is already installed, though
17520                // it has been renamed to an older name.  The package we
17521                // are trying to install should be installed as an update to
17522                // the existing one, but that has not been requested, so bail.
17523                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17524                        + " without first uninstalling package running as "
17525                        + renamedPackage);
17526                return;
17527            }
17528            if (mPackages.containsKey(pkgName)) {
17529                // Don't allow installation over an existing package with the same name.
17530                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17531                        + " without first uninstalling.");
17532                return;
17533            }
17534        }
17535
17536        try {
17537            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
17538                    System.currentTimeMillis(), user);
17539
17540            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
17541
17542            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17543                prepareAppDataAfterInstallLIF(newPackage);
17544
17545            } else {
17546                // Remove package from internal structures, but keep around any
17547                // data that might have already existed
17548                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
17549                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
17550            }
17551        } catch (PackageManagerException e) {
17552            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17553        }
17554
17555        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17556    }
17557
17558    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
17559        // Can't rotate keys during boot or if sharedUser.
17560        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
17561                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
17562            return false;
17563        }
17564        // app is using upgradeKeySets; make sure all are valid
17565        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17566        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
17567        for (int i = 0; i < upgradeKeySets.length; i++) {
17568            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
17569                Slog.wtf(TAG, "Package "
17570                         + (oldPs.name != null ? oldPs.name : "<null>")
17571                         + " contains upgrade-key-set reference to unknown key-set: "
17572                         + upgradeKeySets[i]
17573                         + " reverting to signatures check.");
17574                return false;
17575            }
17576        }
17577        return true;
17578    }
17579
17580    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
17581        // Upgrade keysets are being used.  Determine if new package has a superset of the
17582        // required keys.
17583        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
17584        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17585        for (int i = 0; i < upgradeKeySets.length; i++) {
17586            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
17587            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
17588                return true;
17589            }
17590        }
17591        return false;
17592    }
17593
17594    private static void updateDigest(MessageDigest digest, File file) throws IOException {
17595        try (DigestInputStream digestStream =
17596                new DigestInputStream(new FileInputStream(file), digest)) {
17597            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
17598        }
17599    }
17600
17601    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
17602            UserHandle user, String installerPackageName, PackageInstalledInfo res,
17603            int installReason) {
17604        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17605
17606        final PackageParser.Package oldPackage;
17607        final PackageSetting ps;
17608        final String pkgName = pkg.packageName;
17609        final int[] allUsers;
17610        final int[] installedUsers;
17611
17612        synchronized(mPackages) {
17613            oldPackage = mPackages.get(pkgName);
17614            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
17615
17616            // don't allow upgrade to target a release SDK from a pre-release SDK
17617            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
17618                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17619            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
17620                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17621            if (oldTargetsPreRelease
17622                    && !newTargetsPreRelease
17623                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
17624                Slog.w(TAG, "Can't install package targeting released sdk");
17625                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
17626                return;
17627            }
17628
17629            ps = mSettings.mPackages.get(pkgName);
17630
17631            // verify signatures are valid
17632            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17633                if (!checkUpgradeKeySetLP(ps, pkg)) {
17634                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17635                            "New package not signed by keys specified by upgrade-keysets: "
17636                                    + pkgName);
17637                    return;
17638                }
17639            } else {
17640                // default to original signature matching
17641                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17642                        != PackageManager.SIGNATURE_MATCH) {
17643                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17644                            "New package has a different signature: " + pkgName);
17645                    return;
17646                }
17647            }
17648
17649            // don't allow a system upgrade unless the upgrade hash matches
17650            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17651                byte[] digestBytes = null;
17652                try {
17653                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17654                    updateDigest(digest, new File(pkg.baseCodePath));
17655                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17656                        for (String path : pkg.splitCodePaths) {
17657                            updateDigest(digest, new File(path));
17658                        }
17659                    }
17660                    digestBytes = digest.digest();
17661                } catch (NoSuchAlgorithmException | IOException e) {
17662                    res.setError(INSTALL_FAILED_INVALID_APK,
17663                            "Could not compute hash: " + pkgName);
17664                    return;
17665                }
17666                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17667                    res.setError(INSTALL_FAILED_INVALID_APK,
17668                            "New package fails restrict-update check: " + pkgName);
17669                    return;
17670                }
17671                // retain upgrade restriction
17672                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17673            }
17674
17675            // Check for shared user id changes
17676            String invalidPackageName =
17677                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17678            if (invalidPackageName != null) {
17679                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17680                        "Package " + invalidPackageName + " tried to change user "
17681                                + oldPackage.mSharedUserId);
17682                return;
17683            }
17684
17685            // In case of rollback, remember per-user/profile install state
17686            allUsers = sUserManager.getUserIds();
17687            installedUsers = ps.queryInstalledUsers(allUsers, true);
17688
17689            // don't allow an upgrade from full to ephemeral
17690            if (isInstantApp) {
17691                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17692                    for (int currentUser : allUsers) {
17693                        if (!ps.getInstantApp(currentUser)) {
17694                            // can't downgrade from full to instant
17695                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17696                                    + " for user: " + currentUser);
17697                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17698                            return;
17699                        }
17700                    }
17701                } else if (!ps.getInstantApp(user.getIdentifier())) {
17702                    // can't downgrade from full to instant
17703                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17704                            + " for user: " + user.getIdentifier());
17705                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17706                    return;
17707                }
17708            }
17709        }
17710
17711        // Update what is removed
17712        res.removedInfo = new PackageRemovedInfo(this);
17713        res.removedInfo.uid = oldPackage.applicationInfo.uid;
17714        res.removedInfo.removedPackage = oldPackage.packageName;
17715        res.removedInfo.installerPackageName = ps.installerPackageName;
17716        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17717        res.removedInfo.isUpdate = true;
17718        res.removedInfo.origUsers = installedUsers;
17719        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17720        for (int i = 0; i < installedUsers.length; i++) {
17721            final int userId = installedUsers[i];
17722            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17723        }
17724
17725        final int childCount = (oldPackage.childPackages != null)
17726                ? oldPackage.childPackages.size() : 0;
17727        for (int i = 0; i < childCount; i++) {
17728            boolean childPackageUpdated = false;
17729            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17730            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17731            if (res.addedChildPackages != null) {
17732                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17733                if (childRes != null) {
17734                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17735                    childRes.removedInfo.removedPackage = childPkg.packageName;
17736                    if (childPs != null) {
17737                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17738                    }
17739                    childRes.removedInfo.isUpdate = true;
17740                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17741                    childPackageUpdated = true;
17742                }
17743            }
17744            if (!childPackageUpdated) {
17745                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17746                childRemovedRes.removedPackage = childPkg.packageName;
17747                if (childPs != null) {
17748                    childRemovedRes.installerPackageName = childPs.installerPackageName;
17749                }
17750                childRemovedRes.isUpdate = false;
17751                childRemovedRes.dataRemoved = true;
17752                synchronized (mPackages) {
17753                    if (childPs != null) {
17754                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17755                    }
17756                }
17757                if (res.removedInfo.removedChildPackages == null) {
17758                    res.removedInfo.removedChildPackages = new ArrayMap<>();
17759                }
17760                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17761            }
17762        }
17763
17764        boolean sysPkg = (isSystemApp(oldPackage));
17765        if (sysPkg) {
17766            // Set the system/privileged flags as needed
17767            final boolean privileged =
17768                    (oldPackage.applicationInfo.privateFlags
17769                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17770            final int systemPolicyFlags = policyFlags
17771                    | PackageParser.PARSE_IS_SYSTEM
17772                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
17773
17774            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17775                    user, allUsers, installerPackageName, res, installReason);
17776        } else {
17777            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17778                    user, allUsers, installerPackageName, res, installReason);
17779        }
17780    }
17781
17782    @Override
17783    public List<String> getPreviousCodePaths(String packageName) {
17784        final int callingUid = Binder.getCallingUid();
17785        final List<String> result = new ArrayList<>();
17786        if (getInstantAppPackageName(callingUid) != null) {
17787            return result;
17788        }
17789        final PackageSetting ps = mSettings.mPackages.get(packageName);
17790        if (ps != null
17791                && ps.oldCodePaths != null
17792                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17793            result.addAll(ps.oldCodePaths);
17794        }
17795        return result;
17796    }
17797
17798    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17799            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17800            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17801            int installReason) {
17802        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17803                + deletedPackage);
17804
17805        String pkgName = deletedPackage.packageName;
17806        boolean deletedPkg = true;
17807        boolean addedPkg = false;
17808        boolean updatedSettings = false;
17809        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17810        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17811                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17812
17813        final long origUpdateTime = (pkg.mExtras != null)
17814                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17815
17816        // First delete the existing package while retaining the data directory
17817        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17818                res.removedInfo, true, pkg)) {
17819            // If the existing package wasn't successfully deleted
17820            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17821            deletedPkg = false;
17822        } else {
17823            // Successfully deleted the old package; proceed with replace.
17824
17825            // If deleted package lived in a container, give users a chance to
17826            // relinquish resources before killing.
17827            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17828                if (DEBUG_INSTALL) {
17829                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17830                }
17831                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17832                final ArrayList<String> pkgList = new ArrayList<String>(1);
17833                pkgList.add(deletedPackage.applicationInfo.packageName);
17834                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17835            }
17836
17837            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17838                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17839            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17840
17841            try {
17842                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17843                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17844                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17845                        installReason);
17846
17847                // Update the in-memory copy of the previous code paths.
17848                PackageSetting ps = mSettings.mPackages.get(pkgName);
17849                if (!killApp) {
17850                    if (ps.oldCodePaths == null) {
17851                        ps.oldCodePaths = new ArraySet<>();
17852                    }
17853                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17854                    if (deletedPackage.splitCodePaths != null) {
17855                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17856                    }
17857                } else {
17858                    ps.oldCodePaths = null;
17859                }
17860                if (ps.childPackageNames != null) {
17861                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17862                        final String childPkgName = ps.childPackageNames.get(i);
17863                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17864                        childPs.oldCodePaths = ps.oldCodePaths;
17865                    }
17866                }
17867                // set instant app status, but, only if it's explicitly specified
17868                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17869                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17870                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17871                prepareAppDataAfterInstallLIF(newPackage);
17872                addedPkg = true;
17873                mDexManager.notifyPackageUpdated(newPackage.packageName,
17874                        newPackage.baseCodePath, newPackage.splitCodePaths);
17875            } catch (PackageManagerException e) {
17876                res.setError("Package couldn't be installed in " + pkg.codePath, e);
17877            }
17878        }
17879
17880        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17881            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17882
17883            // Revert all internal state mutations and added folders for the failed install
17884            if (addedPkg) {
17885                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17886                        res.removedInfo, true, null);
17887            }
17888
17889            // Restore the old package
17890            if (deletedPkg) {
17891                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17892                File restoreFile = new File(deletedPackage.codePath);
17893                // Parse old package
17894                boolean oldExternal = isExternal(deletedPackage);
17895                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
17896                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17897                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17898                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17899                try {
17900                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17901                            null);
17902                } catch (PackageManagerException e) {
17903                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17904                            + e.getMessage());
17905                    return;
17906                }
17907
17908                synchronized (mPackages) {
17909                    // Ensure the installer package name up to date
17910                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17911
17912                    // Update permissions for restored package
17913                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17914
17915                    mSettings.writeLPr();
17916                }
17917
17918                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17919            }
17920        } else {
17921            synchronized (mPackages) {
17922                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17923                if (ps != null) {
17924                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17925                    if (res.removedInfo.removedChildPackages != null) {
17926                        final int childCount = res.removedInfo.removedChildPackages.size();
17927                        // Iterate in reverse as we may modify the collection
17928                        for (int i = childCount - 1; i >= 0; i--) {
17929                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17930                            if (res.addedChildPackages.containsKey(childPackageName)) {
17931                                res.removedInfo.removedChildPackages.removeAt(i);
17932                            } else {
17933                                PackageRemovedInfo childInfo = res.removedInfo
17934                                        .removedChildPackages.valueAt(i);
17935                                childInfo.removedForAllUsers = mPackages.get(
17936                                        childInfo.removedPackage) == null;
17937                            }
17938                        }
17939                    }
17940                }
17941            }
17942        }
17943    }
17944
17945    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
17946            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17947            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17948            int installReason) {
17949        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
17950                + ", old=" + deletedPackage);
17951
17952        final boolean disabledSystem;
17953
17954        // Remove existing system package
17955        removePackageLI(deletedPackage, true);
17956
17957        synchronized (mPackages) {
17958            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
17959        }
17960        if (!disabledSystem) {
17961            // We didn't need to disable the .apk as a current system package,
17962            // which means we are replacing another update that is already
17963            // installed.  We need to make sure to delete the older one's .apk.
17964            res.removedInfo.args = createInstallArgsForExisting(0,
17965                    deletedPackage.applicationInfo.getCodePath(),
17966                    deletedPackage.applicationInfo.getResourcePath(),
17967                    getAppDexInstructionSets(deletedPackage.applicationInfo));
17968        } else {
17969            res.removedInfo.args = null;
17970        }
17971
17972        // Successfully disabled the old package. Now proceed with re-installation
17973        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17974                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17975        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17976
17977        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17978        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
17979                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
17980
17981        PackageParser.Package newPackage = null;
17982        try {
17983            // Add the package to the internal data structures
17984            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
17985
17986            // Set the update and install times
17987            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
17988            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
17989                    System.currentTimeMillis());
17990
17991            // Update the package dynamic state if succeeded
17992            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17993                // Now that the install succeeded make sure we remove data
17994                // directories for any child package the update removed.
17995                final int deletedChildCount = (deletedPackage.childPackages != null)
17996                        ? deletedPackage.childPackages.size() : 0;
17997                final int newChildCount = (newPackage.childPackages != null)
17998                        ? newPackage.childPackages.size() : 0;
17999                for (int i = 0; i < deletedChildCount; i++) {
18000                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
18001                    boolean childPackageDeleted = true;
18002                    for (int j = 0; j < newChildCount; j++) {
18003                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
18004                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
18005                            childPackageDeleted = false;
18006                            break;
18007                        }
18008                    }
18009                    if (childPackageDeleted) {
18010                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
18011                                deletedChildPkg.packageName);
18012                        if (ps != null && res.removedInfo.removedChildPackages != null) {
18013                            PackageRemovedInfo removedChildRes = res.removedInfo
18014                                    .removedChildPackages.get(deletedChildPkg.packageName);
18015                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
18016                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
18017                        }
18018                    }
18019                }
18020
18021                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
18022                        installReason);
18023                prepareAppDataAfterInstallLIF(newPackage);
18024
18025                mDexManager.notifyPackageUpdated(newPackage.packageName,
18026                            newPackage.baseCodePath, newPackage.splitCodePaths);
18027            }
18028        } catch (PackageManagerException e) {
18029            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
18030            res.setError("Package couldn't be installed in " + pkg.codePath, e);
18031        }
18032
18033        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
18034            // Re installation failed. Restore old information
18035            // Remove new pkg information
18036            if (newPackage != null) {
18037                removeInstalledPackageLI(newPackage, true);
18038            }
18039            // Add back the old system package
18040            try {
18041                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
18042            } catch (PackageManagerException e) {
18043                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
18044            }
18045
18046            synchronized (mPackages) {
18047                if (disabledSystem) {
18048                    enableSystemPackageLPw(deletedPackage);
18049                }
18050
18051                // Ensure the installer package name up to date
18052                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
18053
18054                // Update permissions for restored package
18055                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
18056
18057                mSettings.writeLPr();
18058            }
18059
18060            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
18061                    + " after failed upgrade");
18062        }
18063    }
18064
18065    /**
18066     * Checks whether the parent or any of the child packages have a change shared
18067     * user. For a package to be a valid update the shred users of the parent and
18068     * the children should match. We may later support changing child shared users.
18069     * @param oldPkg The updated package.
18070     * @param newPkg The update package.
18071     * @return The shared user that change between the versions.
18072     */
18073    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
18074            PackageParser.Package newPkg) {
18075        // Check parent shared user
18076        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
18077            return newPkg.packageName;
18078        }
18079        // Check child shared users
18080        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
18081        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
18082        for (int i = 0; i < newChildCount; i++) {
18083            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
18084            // If this child was present, did it have the same shared user?
18085            for (int j = 0; j < oldChildCount; j++) {
18086                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
18087                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
18088                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
18089                    return newChildPkg.packageName;
18090                }
18091            }
18092        }
18093        return null;
18094    }
18095
18096    private void removeNativeBinariesLI(PackageSetting ps) {
18097        // Remove the lib path for the parent package
18098        if (ps != null) {
18099            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
18100            // Remove the lib path for the child packages
18101            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18102            for (int i = 0; i < childCount; i++) {
18103                PackageSetting childPs = null;
18104                synchronized (mPackages) {
18105                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18106                }
18107                if (childPs != null) {
18108                    NativeLibraryHelper.removeNativeBinariesLI(childPs
18109                            .legacyNativeLibraryPathString);
18110                }
18111            }
18112        }
18113    }
18114
18115    private void enableSystemPackageLPw(PackageParser.Package pkg) {
18116        // Enable the parent package
18117        mSettings.enableSystemPackageLPw(pkg.packageName);
18118        // Enable the child packages
18119        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18120        for (int i = 0; i < childCount; i++) {
18121            PackageParser.Package childPkg = pkg.childPackages.get(i);
18122            mSettings.enableSystemPackageLPw(childPkg.packageName);
18123        }
18124    }
18125
18126    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
18127            PackageParser.Package newPkg) {
18128        // Disable the parent package (parent always replaced)
18129        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
18130        // Disable the child packages
18131        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
18132        for (int i = 0; i < childCount; i++) {
18133            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
18134            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
18135            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
18136        }
18137        return disabled;
18138    }
18139
18140    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
18141            String installerPackageName) {
18142        // Enable the parent package
18143        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
18144        // Enable the child packages
18145        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18146        for (int i = 0; i < childCount; i++) {
18147            PackageParser.Package childPkg = pkg.childPackages.get(i);
18148            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
18149        }
18150    }
18151
18152    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
18153        // Collect all used permissions in the UID
18154        ArraySet<String> usedPermissions = new ArraySet<>();
18155        final int packageCount = su.packages.size();
18156        for (int i = 0; i < packageCount; i++) {
18157            PackageSetting ps = su.packages.valueAt(i);
18158            if (ps.pkg == null) {
18159                continue;
18160            }
18161            final int requestedPermCount = ps.pkg.requestedPermissions.size();
18162            for (int j = 0; j < requestedPermCount; j++) {
18163                String permission = ps.pkg.requestedPermissions.get(j);
18164                BasePermission bp = mSettings.mPermissions.get(permission);
18165                if (bp != null) {
18166                    usedPermissions.add(permission);
18167                }
18168            }
18169        }
18170
18171        PermissionsState permissionsState = su.getPermissionsState();
18172        // Prune install permissions
18173        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
18174        final int installPermCount = installPermStates.size();
18175        for (int i = installPermCount - 1; i >= 0;  i--) {
18176            PermissionState permissionState = installPermStates.get(i);
18177            if (!usedPermissions.contains(permissionState.getName())) {
18178                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
18179                if (bp != null) {
18180                    permissionsState.revokeInstallPermission(bp);
18181                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
18182                            PackageManager.MASK_PERMISSION_FLAGS, 0);
18183                }
18184            }
18185        }
18186
18187        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
18188
18189        // Prune runtime permissions
18190        for (int userId : allUserIds) {
18191            List<PermissionState> runtimePermStates = permissionsState
18192                    .getRuntimePermissionStates(userId);
18193            final int runtimePermCount = runtimePermStates.size();
18194            for (int i = runtimePermCount - 1; i >= 0; i--) {
18195                PermissionState permissionState = runtimePermStates.get(i);
18196                if (!usedPermissions.contains(permissionState.getName())) {
18197                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
18198                    if (bp != null) {
18199                        permissionsState.revokeRuntimePermission(bp, userId);
18200                        permissionsState.updatePermissionFlags(bp, userId,
18201                                PackageManager.MASK_PERMISSION_FLAGS, 0);
18202                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
18203                                runtimePermissionChangedUserIds, userId);
18204                    }
18205                }
18206            }
18207        }
18208
18209        return runtimePermissionChangedUserIds;
18210    }
18211
18212    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
18213            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
18214        // Update the parent package setting
18215        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
18216                res, user, installReason);
18217        // Update the child packages setting
18218        final int childCount = (newPackage.childPackages != null)
18219                ? newPackage.childPackages.size() : 0;
18220        for (int i = 0; i < childCount; i++) {
18221            PackageParser.Package childPackage = newPackage.childPackages.get(i);
18222            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
18223            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
18224                    childRes.origUsers, childRes, user, installReason);
18225        }
18226    }
18227
18228    private void updateSettingsInternalLI(PackageParser.Package newPackage,
18229            String installerPackageName, int[] allUsers, int[] installedForUsers,
18230            PackageInstalledInfo res, UserHandle user, int installReason) {
18231        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
18232
18233        String pkgName = newPackage.packageName;
18234        synchronized (mPackages) {
18235            //write settings. the installStatus will be incomplete at this stage.
18236            //note that the new package setting would have already been
18237            //added to mPackages. It hasn't been persisted yet.
18238            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
18239            // TODO: Remove this write? It's also written at the end of this method
18240            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
18241            mSettings.writeLPr();
18242            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18243        }
18244
18245        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
18246        synchronized (mPackages) {
18247            updatePermissionsLPw(newPackage.packageName, newPackage,
18248                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
18249                            ? UPDATE_PERMISSIONS_ALL : 0));
18250            // For system-bundled packages, we assume that installing an upgraded version
18251            // of the package implies that the user actually wants to run that new code,
18252            // so we enable the package.
18253            PackageSetting ps = mSettings.mPackages.get(pkgName);
18254            final int userId = user.getIdentifier();
18255            if (ps != null) {
18256                if (isSystemApp(newPackage)) {
18257                    if (DEBUG_INSTALL) {
18258                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
18259                    }
18260                    // Enable system package for requested users
18261                    if (res.origUsers != null) {
18262                        for (int origUserId : res.origUsers) {
18263                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
18264                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
18265                                        origUserId, installerPackageName);
18266                            }
18267                        }
18268                    }
18269                    // Also convey the prior install/uninstall state
18270                    if (allUsers != null && installedForUsers != null) {
18271                        for (int currentUserId : allUsers) {
18272                            final boolean installed = ArrayUtils.contains(
18273                                    installedForUsers, currentUserId);
18274                            if (DEBUG_INSTALL) {
18275                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
18276                            }
18277                            ps.setInstalled(installed, currentUserId);
18278                        }
18279                        // these install state changes will be persisted in the
18280                        // upcoming call to mSettings.writeLPr().
18281                    }
18282                }
18283                // It's implied that when a user requests installation, they want the app to be
18284                // installed and enabled.
18285                if (userId != UserHandle.USER_ALL) {
18286                    ps.setInstalled(true, userId);
18287                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
18288                }
18289
18290                // When replacing an existing package, preserve the original install reason for all
18291                // users that had the package installed before.
18292                final Set<Integer> previousUserIds = new ArraySet<>();
18293                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
18294                    final int installReasonCount = res.removedInfo.installReasons.size();
18295                    for (int i = 0; i < installReasonCount; i++) {
18296                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
18297                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
18298                        ps.setInstallReason(previousInstallReason, previousUserId);
18299                        previousUserIds.add(previousUserId);
18300                    }
18301                }
18302
18303                // Set install reason for users that are having the package newly installed.
18304                if (userId == UserHandle.USER_ALL) {
18305                    for (int currentUserId : sUserManager.getUserIds()) {
18306                        if (!previousUserIds.contains(currentUserId)) {
18307                            ps.setInstallReason(installReason, currentUserId);
18308                        }
18309                    }
18310                } else if (!previousUserIds.contains(userId)) {
18311                    ps.setInstallReason(installReason, userId);
18312                }
18313                mSettings.writeKernelMappingLPr(ps);
18314            }
18315            res.name = pkgName;
18316            res.uid = newPackage.applicationInfo.uid;
18317            res.pkg = newPackage;
18318            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
18319            mSettings.setInstallerPackageName(pkgName, installerPackageName);
18320            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18321            //to update install status
18322            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
18323            mSettings.writeLPr();
18324            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18325        }
18326
18327        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18328    }
18329
18330    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
18331        try {
18332            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
18333            installPackageLI(args, res);
18334        } finally {
18335            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18336        }
18337    }
18338
18339    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
18340        final int installFlags = args.installFlags;
18341        final String installerPackageName = args.installerPackageName;
18342        final String volumeUuid = args.volumeUuid;
18343        final File tmpPackageFile = new File(args.getCodePath());
18344        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
18345        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
18346                || (args.volumeUuid != null));
18347        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
18348        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
18349        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
18350        final boolean virtualPreload =
18351                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
18352        boolean replace = false;
18353        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
18354        if (args.move != null) {
18355            // moving a complete application; perform an initial scan on the new install location
18356            scanFlags |= SCAN_INITIAL;
18357        }
18358        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
18359            scanFlags |= SCAN_DONT_KILL_APP;
18360        }
18361        if (instantApp) {
18362            scanFlags |= SCAN_AS_INSTANT_APP;
18363        }
18364        if (fullApp) {
18365            scanFlags |= SCAN_AS_FULL_APP;
18366        }
18367        if (virtualPreload) {
18368            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
18369        }
18370
18371        // Result object to be returned
18372        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18373        res.installerPackageName = installerPackageName;
18374
18375        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
18376
18377        // Sanity check
18378        if (instantApp && (forwardLocked || onExternal)) {
18379            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
18380                    + " external=" + onExternal);
18381            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
18382            return;
18383        }
18384
18385        // Retrieve PackageSettings and parse package
18386        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
18387                | PackageParser.PARSE_ENFORCE_CODE
18388                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
18389                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
18390                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
18391                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
18392        PackageParser pp = new PackageParser();
18393        pp.setSeparateProcesses(mSeparateProcesses);
18394        pp.setDisplayMetrics(mMetrics);
18395        pp.setCallback(mPackageParserCallback);
18396
18397        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
18398        final PackageParser.Package pkg;
18399        try {
18400            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
18401        } catch (PackageParserException e) {
18402            res.setError("Failed parse during installPackageLI", e);
18403            return;
18404        } finally {
18405            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18406        }
18407
18408        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
18409        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
18410            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
18411            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18412                    "Instant app package must target O");
18413            return;
18414        }
18415        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
18416            Slog.w(TAG, "Instant app package " + pkg.packageName
18417                    + " does not target targetSandboxVersion 2");
18418            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18419                    "Instant app package must use targetSanboxVersion 2");
18420            return;
18421        }
18422
18423        if (pkg.applicationInfo.isStaticSharedLibrary()) {
18424            // Static shared libraries have synthetic package names
18425            renameStaticSharedLibraryPackage(pkg);
18426
18427            // No static shared libs on external storage
18428            if (onExternal) {
18429                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
18430                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18431                        "Packages declaring static-shared libs cannot be updated");
18432                return;
18433            }
18434        }
18435
18436        // If we are installing a clustered package add results for the children
18437        if (pkg.childPackages != null) {
18438            synchronized (mPackages) {
18439                final int childCount = pkg.childPackages.size();
18440                for (int i = 0; i < childCount; i++) {
18441                    PackageParser.Package childPkg = pkg.childPackages.get(i);
18442                    PackageInstalledInfo childRes = new PackageInstalledInfo();
18443                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18444                    childRes.pkg = childPkg;
18445                    childRes.name = childPkg.packageName;
18446                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18447                    if (childPs != null) {
18448                        childRes.origUsers = childPs.queryInstalledUsers(
18449                                sUserManager.getUserIds(), true);
18450                    }
18451                    if ((mPackages.containsKey(childPkg.packageName))) {
18452                        childRes.removedInfo = new PackageRemovedInfo(this);
18453                        childRes.removedInfo.removedPackage = childPkg.packageName;
18454                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
18455                    }
18456                    if (res.addedChildPackages == null) {
18457                        res.addedChildPackages = new ArrayMap<>();
18458                    }
18459                    res.addedChildPackages.put(childPkg.packageName, childRes);
18460                }
18461            }
18462        }
18463
18464        // If package doesn't declare API override, mark that we have an install
18465        // time CPU ABI override.
18466        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
18467            pkg.cpuAbiOverride = args.abiOverride;
18468        }
18469
18470        String pkgName = res.name = pkg.packageName;
18471        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
18472            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
18473                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
18474                return;
18475            }
18476        }
18477
18478        try {
18479            // either use what we've been given or parse directly from the APK
18480            if (args.certificates != null) {
18481                try {
18482                    PackageParser.populateCertificates(pkg, args.certificates);
18483                } catch (PackageParserException e) {
18484                    // there was something wrong with the certificates we were given;
18485                    // try to pull them from the APK
18486                    PackageParser.collectCertificates(pkg, parseFlags);
18487                }
18488            } else {
18489                PackageParser.collectCertificates(pkg, parseFlags);
18490            }
18491        } catch (PackageParserException e) {
18492            res.setError("Failed collect during installPackageLI", e);
18493            return;
18494        }
18495
18496        // Get rid of all references to package scan path via parser.
18497        pp = null;
18498        String oldCodePath = null;
18499        boolean systemApp = false;
18500        synchronized (mPackages) {
18501            // Check if installing already existing package
18502            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
18503                String oldName = mSettings.getRenamedPackageLPr(pkgName);
18504                if (pkg.mOriginalPackages != null
18505                        && pkg.mOriginalPackages.contains(oldName)
18506                        && mPackages.containsKey(oldName)) {
18507                    // This package is derived from an original package,
18508                    // and this device has been updating from that original
18509                    // name.  We must continue using the original name, so
18510                    // rename the new package here.
18511                    pkg.setPackageName(oldName);
18512                    pkgName = pkg.packageName;
18513                    replace = true;
18514                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
18515                            + oldName + " pkgName=" + pkgName);
18516                } else if (mPackages.containsKey(pkgName)) {
18517                    // This package, under its official name, already exists
18518                    // on the device; we should replace it.
18519                    replace = true;
18520                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
18521                }
18522
18523                // Child packages are installed through the parent package
18524                if (pkg.parentPackage != null) {
18525                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18526                            "Package " + pkg.packageName + " is child of package "
18527                                    + pkg.parentPackage.parentPackage + ". Child packages "
18528                                    + "can be updated only through the parent package.");
18529                    return;
18530                }
18531
18532                if (replace) {
18533                    // Prevent apps opting out from runtime permissions
18534                    PackageParser.Package oldPackage = mPackages.get(pkgName);
18535                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
18536                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
18537                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
18538                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
18539                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
18540                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
18541                                        + " doesn't support runtime permissions but the old"
18542                                        + " target SDK " + oldTargetSdk + " does.");
18543                        return;
18544                    }
18545                    // Prevent apps from downgrading their targetSandbox.
18546                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
18547                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
18548                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
18549                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18550                                "Package " + pkg.packageName + " new target sandbox "
18551                                + newTargetSandbox + " is incompatible with the previous value of"
18552                                + oldTargetSandbox + ".");
18553                        return;
18554                    }
18555
18556                    // Prevent installing of child packages
18557                    if (oldPackage.parentPackage != null) {
18558                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18559                                "Package " + pkg.packageName + " is child of package "
18560                                        + oldPackage.parentPackage + ". Child packages "
18561                                        + "can be updated only through the parent package.");
18562                        return;
18563                    }
18564                }
18565            }
18566
18567            PackageSetting ps = mSettings.mPackages.get(pkgName);
18568            if (ps != null) {
18569                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
18570
18571                // Static shared libs have same package with different versions where
18572                // we internally use a synthetic package name to allow multiple versions
18573                // of the same package, therefore we need to compare signatures against
18574                // the package setting for the latest library version.
18575                PackageSetting signatureCheckPs = ps;
18576                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18577                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
18578                    if (libraryEntry != null) {
18579                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
18580                    }
18581                }
18582
18583                // Quick sanity check that we're signed correctly if updating;
18584                // we'll check this again later when scanning, but we want to
18585                // bail early here before tripping over redefined permissions.
18586                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
18587                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
18588                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
18589                                + pkg.packageName + " upgrade keys do not match the "
18590                                + "previously installed version");
18591                        return;
18592                    }
18593                } else {
18594                    try {
18595                        verifySignaturesLP(signatureCheckPs, pkg);
18596                    } catch (PackageManagerException e) {
18597                        res.setError(e.error, e.getMessage());
18598                        return;
18599                    }
18600                }
18601
18602                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
18603                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
18604                    systemApp = (ps.pkg.applicationInfo.flags &
18605                            ApplicationInfo.FLAG_SYSTEM) != 0;
18606                }
18607                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18608            }
18609
18610            int N = pkg.permissions.size();
18611            for (int i = N-1; i >= 0; i--) {
18612                PackageParser.Permission perm = pkg.permissions.get(i);
18613                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
18614
18615                // Don't allow anyone but the system to define ephemeral permissions.
18616                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
18617                        && !systemApp) {
18618                    Slog.w(TAG, "Non-System package " + pkg.packageName
18619                            + " attempting to delcare ephemeral permission "
18620                            + perm.info.name + "; Removing ephemeral.");
18621                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
18622                }
18623                // Check whether the newly-scanned package wants to define an already-defined perm
18624                if (bp != null) {
18625                    // If the defining package is signed with our cert, it's okay.  This
18626                    // also includes the "updating the same package" case, of course.
18627                    // "updating same package" could also involve key-rotation.
18628                    final boolean sigsOk;
18629                    if (bp.sourcePackage.equals(pkg.packageName)
18630                            && (bp.packageSetting instanceof PackageSetting)
18631                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
18632                                    scanFlags))) {
18633                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
18634                    } else {
18635                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
18636                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18637                    }
18638                    if (!sigsOk) {
18639                        // If the owning package is the system itself, we log but allow
18640                        // install to proceed; we fail the install on all other permission
18641                        // redefinitions.
18642                        if (!bp.sourcePackage.equals("android")) {
18643                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18644                                    + pkg.packageName + " attempting to redeclare permission "
18645                                    + perm.info.name + " already owned by " + bp.sourcePackage);
18646                            res.origPermission = perm.info.name;
18647                            res.origPackage = bp.sourcePackage;
18648                            return;
18649                        } else {
18650                            Slog.w(TAG, "Package " + pkg.packageName
18651                                    + " attempting to redeclare system permission "
18652                                    + perm.info.name + "; ignoring new declaration");
18653                            pkg.permissions.remove(i);
18654                        }
18655                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18656                        // Prevent apps to change protection level to dangerous from any other
18657                        // type as this would allow a privilege escalation where an app adds a
18658                        // normal/signature permission in other app's group and later redefines
18659                        // it as dangerous leading to the group auto-grant.
18660                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18661                                == PermissionInfo.PROTECTION_DANGEROUS) {
18662                            if (bp != null && !bp.isRuntime()) {
18663                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18664                                        + "non-runtime permission " + perm.info.name
18665                                        + " to runtime; keeping old protection level");
18666                                perm.info.protectionLevel = bp.protectionLevel;
18667                            }
18668                        }
18669                    }
18670                }
18671            }
18672        }
18673
18674        if (systemApp) {
18675            if (onExternal) {
18676                // Abort update; system app can't be replaced with app on sdcard
18677                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18678                        "Cannot install updates to system apps on sdcard");
18679                return;
18680            } else if (instantApp) {
18681                // Abort update; system app can't be replaced with an instant app
18682                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18683                        "Cannot update a system app with an instant app");
18684                return;
18685            }
18686        }
18687
18688        if (args.move != null) {
18689            // We did an in-place move, so dex is ready to roll
18690            scanFlags |= SCAN_NO_DEX;
18691            scanFlags |= SCAN_MOVE;
18692
18693            synchronized (mPackages) {
18694                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18695                if (ps == null) {
18696                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18697                            "Missing settings for moved package " + pkgName);
18698                }
18699
18700                // We moved the entire application as-is, so bring over the
18701                // previously derived ABI information.
18702                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18703                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18704            }
18705
18706        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18707            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18708            scanFlags |= SCAN_NO_DEX;
18709
18710            try {
18711                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18712                    args.abiOverride : pkg.cpuAbiOverride);
18713                final boolean extractNativeLibs = !pkg.isLibrary();
18714                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18715                        extractNativeLibs, mAppLib32InstallDir);
18716            } catch (PackageManagerException pme) {
18717                Slog.e(TAG, "Error deriving application ABI", pme);
18718                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18719                return;
18720            }
18721
18722            // Shared libraries for the package need to be updated.
18723            synchronized (mPackages) {
18724                try {
18725                    updateSharedLibrariesLPr(pkg, null);
18726                } catch (PackageManagerException e) {
18727                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18728                }
18729            }
18730        }
18731
18732        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18733            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18734            return;
18735        }
18736
18737        // Verify if we need to dexopt the app.
18738        //
18739        // NOTE: it is *important* to call dexopt after doRename which will sync the
18740        // package data from PackageParser.Package and its corresponding ApplicationInfo.
18741        //
18742        // We only need to dexopt if the package meets ALL of the following conditions:
18743        //   1) it is not forward locked.
18744        //   2) it is not on on an external ASEC container.
18745        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
18746        //
18747        // Note that we do not dexopt instant apps by default. dexopt can take some time to
18748        // complete, so we skip this step during installation. Instead, we'll take extra time
18749        // the first time the instant app starts. It's preferred to do it this way to provide
18750        // continuous progress to the useur instead of mysteriously blocking somewhere in the
18751        // middle of running an instant app. The default behaviour can be overridden
18752        // via gservices.
18753        final boolean performDexopt = !forwardLocked
18754            && !pkg.applicationInfo.isExternalAsec()
18755            && (!instantApp || Global.getInt(mContext.getContentResolver(),
18756                    Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
18757
18758        if (performDexopt) {
18759            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18760            // Do not run PackageDexOptimizer through the local performDexOpt
18761            // method because `pkg` may not be in `mPackages` yet.
18762            //
18763            // Also, don't fail application installs if the dexopt step fails.
18764            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
18765                REASON_INSTALL,
18766                DexoptOptions.DEXOPT_BOOT_COMPLETE);
18767            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18768                null /* instructionSets */,
18769                getOrCreateCompilerPackageStats(pkg),
18770                mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
18771                dexoptOptions);
18772            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18773        }
18774
18775        // Notify BackgroundDexOptService that the package has been changed.
18776        // If this is an update of a package which used to fail to compile,
18777        // BackgroundDexOptService will remove it from its blacklist.
18778        // TODO: Layering violation
18779        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18780
18781        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18782
18783        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18784                "installPackageLI")) {
18785            if (replace) {
18786                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18787                    // Static libs have a synthetic package name containing the version
18788                    // and cannot be updated as an update would get a new package name,
18789                    // unless this is the exact same version code which is useful for
18790                    // development.
18791                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18792                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18793                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18794                                + "static-shared libs cannot be updated");
18795                        return;
18796                    }
18797                }
18798                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18799                        installerPackageName, res, args.installReason);
18800            } else {
18801                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18802                        args.user, installerPackageName, volumeUuid, res, args.installReason);
18803            }
18804        }
18805
18806        synchronized (mPackages) {
18807            final PackageSetting ps = mSettings.mPackages.get(pkgName);
18808            if (ps != null) {
18809                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18810                ps.setUpdateAvailable(false /*updateAvailable*/);
18811            }
18812
18813            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18814            for (int i = 0; i < childCount; i++) {
18815                PackageParser.Package childPkg = pkg.childPackages.get(i);
18816                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18817                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18818                if (childPs != null) {
18819                    childRes.newUsers = childPs.queryInstalledUsers(
18820                            sUserManager.getUserIds(), true);
18821                }
18822            }
18823
18824            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18825                updateSequenceNumberLP(ps, res.newUsers);
18826                updateInstantAppInstallerLocked(pkgName);
18827            }
18828        }
18829    }
18830
18831    private void startIntentFilterVerifications(int userId, boolean replacing,
18832            PackageParser.Package pkg) {
18833        if (mIntentFilterVerifierComponent == null) {
18834            Slog.w(TAG, "No IntentFilter verification will not be done as "
18835                    + "there is no IntentFilterVerifier available!");
18836            return;
18837        }
18838
18839        final int verifierUid = getPackageUid(
18840                mIntentFilterVerifierComponent.getPackageName(),
18841                MATCH_DEBUG_TRIAGED_MISSING,
18842                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18843
18844        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18845        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18846        mHandler.sendMessage(msg);
18847
18848        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18849        for (int i = 0; i < childCount; i++) {
18850            PackageParser.Package childPkg = pkg.childPackages.get(i);
18851            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18852            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18853            mHandler.sendMessage(msg);
18854        }
18855    }
18856
18857    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18858            PackageParser.Package pkg) {
18859        int size = pkg.activities.size();
18860        if (size == 0) {
18861            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18862                    "No activity, so no need to verify any IntentFilter!");
18863            return;
18864        }
18865
18866        final boolean hasDomainURLs = hasDomainURLs(pkg);
18867        if (!hasDomainURLs) {
18868            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18869                    "No domain URLs, so no need to verify any IntentFilter!");
18870            return;
18871        }
18872
18873        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18874                + " if any IntentFilter from the " + size
18875                + " Activities needs verification ...");
18876
18877        int count = 0;
18878        final String packageName = pkg.packageName;
18879
18880        synchronized (mPackages) {
18881            // If this is a new install and we see that we've already run verification for this
18882            // package, we have nothing to do: it means the state was restored from backup.
18883            if (!replacing) {
18884                IntentFilterVerificationInfo ivi =
18885                        mSettings.getIntentFilterVerificationLPr(packageName);
18886                if (ivi != null) {
18887                    if (DEBUG_DOMAIN_VERIFICATION) {
18888                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
18889                                + ivi.getStatusString());
18890                    }
18891                    return;
18892                }
18893            }
18894
18895            // If any filters need to be verified, then all need to be.
18896            boolean needToVerify = false;
18897            for (PackageParser.Activity a : pkg.activities) {
18898                for (ActivityIntentInfo filter : a.intents) {
18899                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18900                        if (DEBUG_DOMAIN_VERIFICATION) {
18901                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18902                        }
18903                        needToVerify = true;
18904                        break;
18905                    }
18906                }
18907            }
18908
18909            if (needToVerify) {
18910                final int verificationId = mIntentFilterVerificationToken++;
18911                for (PackageParser.Activity a : pkg.activities) {
18912                    for (ActivityIntentInfo filter : a.intents) {
18913                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
18914                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18915                                    "Verification needed for IntentFilter:" + filter.toString());
18916                            mIntentFilterVerifier.addOneIntentFilterVerification(
18917                                    verifierUid, userId, verificationId, filter, packageName);
18918                            count++;
18919                        }
18920                    }
18921                }
18922            }
18923        }
18924
18925        if (count > 0) {
18926            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
18927                    + " IntentFilter verification" + (count > 1 ? "s" : "")
18928                    +  " for userId:" + userId);
18929            mIntentFilterVerifier.startVerifications(userId);
18930        } else {
18931            if (DEBUG_DOMAIN_VERIFICATION) {
18932                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
18933            }
18934        }
18935    }
18936
18937    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
18938        final ComponentName cn  = filter.activity.getComponentName();
18939        final String packageName = cn.getPackageName();
18940
18941        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
18942                packageName);
18943        if (ivi == null) {
18944            return true;
18945        }
18946        int status = ivi.getStatus();
18947        switch (status) {
18948            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
18949            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
18950                return true;
18951
18952            default:
18953                // Nothing to do
18954                return false;
18955        }
18956    }
18957
18958    private static boolean isMultiArch(ApplicationInfo info) {
18959        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
18960    }
18961
18962    private static boolean isExternal(PackageParser.Package pkg) {
18963        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18964    }
18965
18966    private static boolean isExternal(PackageSetting ps) {
18967        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18968    }
18969
18970    private static boolean isSystemApp(PackageParser.Package pkg) {
18971        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
18972    }
18973
18974    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
18975        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
18976    }
18977
18978    private static boolean hasDomainURLs(PackageParser.Package pkg) {
18979        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
18980    }
18981
18982    private static boolean isSystemApp(PackageSetting ps) {
18983        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
18984    }
18985
18986    private static boolean isUpdatedSystemApp(PackageSetting ps) {
18987        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
18988    }
18989
18990    private int packageFlagsToInstallFlags(PackageSetting ps) {
18991        int installFlags = 0;
18992        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
18993            // This existing package was an external ASEC install when we have
18994            // the external flag without a UUID
18995            installFlags |= PackageManager.INSTALL_EXTERNAL;
18996        }
18997        if (ps.isForwardLocked()) {
18998            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
18999        }
19000        return installFlags;
19001    }
19002
19003    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
19004        if (isExternal(pkg)) {
19005            if (TextUtils.isEmpty(pkg.volumeUuid)) {
19006                return StorageManager.UUID_PRIMARY_PHYSICAL;
19007            } else {
19008                return pkg.volumeUuid;
19009            }
19010        } else {
19011            return StorageManager.UUID_PRIVATE_INTERNAL;
19012        }
19013    }
19014
19015    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
19016        if (isExternal(pkg)) {
19017            if (TextUtils.isEmpty(pkg.volumeUuid)) {
19018                return mSettings.getExternalVersion();
19019            } else {
19020                return mSettings.findOrCreateVersion(pkg.volumeUuid);
19021            }
19022        } else {
19023            return mSettings.getInternalVersion();
19024        }
19025    }
19026
19027    private void deleteTempPackageFiles() {
19028        final FilenameFilter filter = new FilenameFilter() {
19029            public boolean accept(File dir, String name) {
19030                return name.startsWith("vmdl") && name.endsWith(".tmp");
19031            }
19032        };
19033        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
19034            file.delete();
19035        }
19036    }
19037
19038    @Override
19039    public void deletePackageAsUser(String packageName, int versionCode,
19040            IPackageDeleteObserver observer, int userId, int flags) {
19041        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
19042                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
19043    }
19044
19045    @Override
19046    public void deletePackageVersioned(VersionedPackage versionedPackage,
19047            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
19048        final int callingUid = Binder.getCallingUid();
19049        mContext.enforceCallingOrSelfPermission(
19050                android.Manifest.permission.DELETE_PACKAGES, null);
19051        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
19052        Preconditions.checkNotNull(versionedPackage);
19053        Preconditions.checkNotNull(observer);
19054        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
19055                PackageManager.VERSION_CODE_HIGHEST,
19056                Integer.MAX_VALUE, "versionCode must be >= -1");
19057
19058        final String packageName = versionedPackage.getPackageName();
19059        final int versionCode = versionedPackage.getVersionCode();
19060        final String internalPackageName;
19061        synchronized (mPackages) {
19062            // Normalize package name to handle renamed packages and static libs
19063            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
19064                    versionedPackage.getVersionCode());
19065        }
19066
19067        final int uid = Binder.getCallingUid();
19068        if (!isOrphaned(internalPackageName)
19069                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
19070            try {
19071                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
19072                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
19073                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
19074                observer.onUserActionRequired(intent);
19075            } catch (RemoteException re) {
19076            }
19077            return;
19078        }
19079        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
19080        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
19081        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
19082            mContext.enforceCallingOrSelfPermission(
19083                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
19084                    "deletePackage for user " + userId);
19085        }
19086
19087        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
19088            try {
19089                observer.onPackageDeleted(packageName,
19090                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
19091            } catch (RemoteException re) {
19092            }
19093            return;
19094        }
19095
19096        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
19097            try {
19098                observer.onPackageDeleted(packageName,
19099                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
19100            } catch (RemoteException re) {
19101            }
19102            return;
19103        }
19104
19105        if (DEBUG_REMOVE) {
19106            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
19107                    + " deleteAllUsers: " + deleteAllUsers + " version="
19108                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
19109                    ? "VERSION_CODE_HIGHEST" : versionCode));
19110        }
19111        // Queue up an async operation since the package deletion may take a little while.
19112        mHandler.post(new Runnable() {
19113            public void run() {
19114                mHandler.removeCallbacks(this);
19115                int returnCode;
19116                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
19117                boolean doDeletePackage = true;
19118                if (ps != null) {
19119                    final boolean targetIsInstantApp =
19120                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19121                    doDeletePackage = !targetIsInstantApp
19122                            || canViewInstantApps;
19123                }
19124                if (doDeletePackage) {
19125                    if (!deleteAllUsers) {
19126                        returnCode = deletePackageX(internalPackageName, versionCode,
19127                                userId, deleteFlags);
19128                    } else {
19129                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
19130                                internalPackageName, users);
19131                        // If nobody is blocking uninstall, proceed with delete for all users
19132                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
19133                            returnCode = deletePackageX(internalPackageName, versionCode,
19134                                    userId, deleteFlags);
19135                        } else {
19136                            // Otherwise uninstall individually for users with blockUninstalls=false
19137                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
19138                            for (int userId : users) {
19139                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
19140                                    returnCode = deletePackageX(internalPackageName, versionCode,
19141                                            userId, userFlags);
19142                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
19143                                        Slog.w(TAG, "Package delete failed for user " + userId
19144                                                + ", returnCode " + returnCode);
19145                                    }
19146                                }
19147                            }
19148                            // The app has only been marked uninstalled for certain users.
19149                            // We still need to report that delete was blocked
19150                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
19151                        }
19152                    }
19153                } else {
19154                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19155                }
19156                try {
19157                    observer.onPackageDeleted(packageName, returnCode, null);
19158                } catch (RemoteException e) {
19159                    Log.i(TAG, "Observer no longer exists.");
19160                } //end catch
19161            } //end run
19162        });
19163    }
19164
19165    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
19166        if (pkg.staticSharedLibName != null) {
19167            return pkg.manifestPackageName;
19168        }
19169        return pkg.packageName;
19170    }
19171
19172    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
19173        // Handle renamed packages
19174        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
19175        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
19176
19177        // Is this a static library?
19178        SparseArray<SharedLibraryEntry> versionedLib =
19179                mStaticLibsByDeclaringPackage.get(packageName);
19180        if (versionedLib == null || versionedLib.size() <= 0) {
19181            return packageName;
19182        }
19183
19184        // Figure out which lib versions the caller can see
19185        SparseIntArray versionsCallerCanSee = null;
19186        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
19187        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
19188                && callingAppId != Process.ROOT_UID) {
19189            versionsCallerCanSee = new SparseIntArray();
19190            String libName = versionedLib.valueAt(0).info.getName();
19191            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
19192            if (uidPackages != null) {
19193                for (String uidPackage : uidPackages) {
19194                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
19195                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
19196                    if (libIdx >= 0) {
19197                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
19198                        versionsCallerCanSee.append(libVersion, libVersion);
19199                    }
19200                }
19201            }
19202        }
19203
19204        // Caller can see nothing - done
19205        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
19206            return packageName;
19207        }
19208
19209        // Find the version the caller can see and the app version code
19210        SharedLibraryEntry highestVersion = null;
19211        final int versionCount = versionedLib.size();
19212        for (int i = 0; i < versionCount; i++) {
19213            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
19214            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
19215                    libEntry.info.getVersion()) < 0) {
19216                continue;
19217            }
19218            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
19219            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
19220                if (libVersionCode == versionCode) {
19221                    return libEntry.apk;
19222                }
19223            } else if (highestVersion == null) {
19224                highestVersion = libEntry;
19225            } else if (libVersionCode  > highestVersion.info
19226                    .getDeclaringPackage().getVersionCode()) {
19227                highestVersion = libEntry;
19228            }
19229        }
19230
19231        if (highestVersion != null) {
19232            return highestVersion.apk;
19233        }
19234
19235        return packageName;
19236    }
19237
19238    boolean isCallerVerifier(int callingUid) {
19239        final int callingUserId = UserHandle.getUserId(callingUid);
19240        return mRequiredVerifierPackage != null &&
19241                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
19242    }
19243
19244    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
19245        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
19246              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19247            return true;
19248        }
19249        final int callingUserId = UserHandle.getUserId(callingUid);
19250        // If the caller installed the pkgName, then allow it to silently uninstall.
19251        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
19252            return true;
19253        }
19254
19255        // Allow package verifier to silently uninstall.
19256        if (mRequiredVerifierPackage != null &&
19257                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
19258            return true;
19259        }
19260
19261        // Allow package uninstaller to silently uninstall.
19262        if (mRequiredUninstallerPackage != null &&
19263                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
19264            return true;
19265        }
19266
19267        // Allow storage manager to silently uninstall.
19268        if (mStorageManagerPackage != null &&
19269                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
19270            return true;
19271        }
19272
19273        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
19274        // uninstall for device owner provisioning.
19275        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
19276                == PERMISSION_GRANTED) {
19277            return true;
19278        }
19279
19280        return false;
19281    }
19282
19283    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
19284        int[] result = EMPTY_INT_ARRAY;
19285        for (int userId : userIds) {
19286            if (getBlockUninstallForUser(packageName, userId)) {
19287                result = ArrayUtils.appendInt(result, userId);
19288            }
19289        }
19290        return result;
19291    }
19292
19293    @Override
19294    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
19295        final int callingUid = Binder.getCallingUid();
19296        if (getInstantAppPackageName(callingUid) != null
19297                && !isCallerSameApp(packageName, callingUid)) {
19298            return false;
19299        }
19300        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
19301    }
19302
19303    private boolean isPackageDeviceAdmin(String packageName, int userId) {
19304        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
19305                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
19306        try {
19307            if (dpm != null) {
19308                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
19309                        /* callingUserOnly =*/ false);
19310                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
19311                        : deviceOwnerComponentName.getPackageName();
19312                // Does the package contains the device owner?
19313                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
19314                // this check is probably not needed, since DO should be registered as a device
19315                // admin on some user too. (Original bug for this: b/17657954)
19316                if (packageName.equals(deviceOwnerPackageName)) {
19317                    return true;
19318                }
19319                // Does it contain a device admin for any user?
19320                int[] users;
19321                if (userId == UserHandle.USER_ALL) {
19322                    users = sUserManager.getUserIds();
19323                } else {
19324                    users = new int[]{userId};
19325                }
19326                for (int i = 0; i < users.length; ++i) {
19327                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
19328                        return true;
19329                    }
19330                }
19331            }
19332        } catch (RemoteException e) {
19333        }
19334        return false;
19335    }
19336
19337    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
19338        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
19339    }
19340
19341    /**
19342     *  This method is an internal method that could be get invoked either
19343     *  to delete an installed package or to clean up a failed installation.
19344     *  After deleting an installed package, a broadcast is sent to notify any
19345     *  listeners that the package has been removed. For cleaning up a failed
19346     *  installation, the broadcast is not necessary since the package's
19347     *  installation wouldn't have sent the initial broadcast either
19348     *  The key steps in deleting a package are
19349     *  deleting the package information in internal structures like mPackages,
19350     *  deleting the packages base directories through installd
19351     *  updating mSettings to reflect current status
19352     *  persisting settings for later use
19353     *  sending a broadcast if necessary
19354     */
19355    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
19356        final PackageRemovedInfo info = new PackageRemovedInfo(this);
19357        final boolean res;
19358
19359        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
19360                ? UserHandle.USER_ALL : userId;
19361
19362        if (isPackageDeviceAdmin(packageName, removeUser)) {
19363            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
19364            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
19365        }
19366
19367        PackageSetting uninstalledPs = null;
19368        PackageParser.Package pkg = null;
19369
19370        // for the uninstall-updates case and restricted profiles, remember the per-
19371        // user handle installed state
19372        int[] allUsers;
19373        synchronized (mPackages) {
19374            uninstalledPs = mSettings.mPackages.get(packageName);
19375            if (uninstalledPs == null) {
19376                Slog.w(TAG, "Not removing non-existent package " + packageName);
19377                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19378            }
19379
19380            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
19381                    && uninstalledPs.versionCode != versionCode) {
19382                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
19383                        + uninstalledPs.versionCode + " != " + versionCode);
19384                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19385            }
19386
19387            // Static shared libs can be declared by any package, so let us not
19388            // allow removing a package if it provides a lib others depend on.
19389            pkg = mPackages.get(packageName);
19390
19391            allUsers = sUserManager.getUserIds();
19392
19393            if (pkg != null && pkg.staticSharedLibName != null) {
19394                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
19395                        pkg.staticSharedLibVersion);
19396                if (libEntry != null) {
19397                    for (int currUserId : allUsers) {
19398                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
19399                            continue;
19400                        }
19401                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
19402                                libEntry.info, 0, currUserId);
19403                        if (!ArrayUtils.isEmpty(libClientPackages)) {
19404                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
19405                                    + " hosting lib " + libEntry.info.getName() + " version "
19406                                    + libEntry.info.getVersion() + " used by " + libClientPackages
19407                                    + " for user " + currUserId);
19408                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
19409                        }
19410                    }
19411                }
19412            }
19413
19414            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
19415        }
19416
19417        final int freezeUser;
19418        if (isUpdatedSystemApp(uninstalledPs)
19419                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
19420            // We're downgrading a system app, which will apply to all users, so
19421            // freeze them all during the downgrade
19422            freezeUser = UserHandle.USER_ALL;
19423        } else {
19424            freezeUser = removeUser;
19425        }
19426
19427        synchronized (mInstallLock) {
19428            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
19429            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
19430                    deleteFlags, "deletePackageX")) {
19431                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
19432                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
19433            }
19434            synchronized (mPackages) {
19435                if (res) {
19436                    if (pkg != null) {
19437                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
19438                    }
19439                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
19440                    updateInstantAppInstallerLocked(packageName);
19441                }
19442            }
19443        }
19444
19445        if (res) {
19446            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
19447            info.sendPackageRemovedBroadcasts(killApp);
19448            info.sendSystemPackageUpdatedBroadcasts();
19449            info.sendSystemPackageAppearedBroadcasts();
19450        }
19451        // Force a gc here.
19452        Runtime.getRuntime().gc();
19453        // Delete the resources here after sending the broadcast to let
19454        // other processes clean up before deleting resources.
19455        if (info.args != null) {
19456            synchronized (mInstallLock) {
19457                info.args.doPostDeleteLI(true);
19458            }
19459        }
19460
19461        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19462    }
19463
19464    static class PackageRemovedInfo {
19465        final PackageSender packageSender;
19466        String removedPackage;
19467        String installerPackageName;
19468        int uid = -1;
19469        int removedAppId = -1;
19470        int[] origUsers;
19471        int[] removedUsers = null;
19472        int[] broadcastUsers = null;
19473        SparseArray<Integer> installReasons;
19474        boolean isRemovedPackageSystemUpdate = false;
19475        boolean isUpdate;
19476        boolean dataRemoved;
19477        boolean removedForAllUsers;
19478        boolean isStaticSharedLib;
19479        // Clean up resources deleted packages.
19480        InstallArgs args = null;
19481        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
19482        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
19483
19484        PackageRemovedInfo(PackageSender packageSender) {
19485            this.packageSender = packageSender;
19486        }
19487
19488        void sendPackageRemovedBroadcasts(boolean killApp) {
19489            sendPackageRemovedBroadcastInternal(killApp);
19490            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
19491            for (int i = 0; i < childCount; i++) {
19492                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19493                childInfo.sendPackageRemovedBroadcastInternal(killApp);
19494            }
19495        }
19496
19497        void sendSystemPackageUpdatedBroadcasts() {
19498            if (isRemovedPackageSystemUpdate) {
19499                sendSystemPackageUpdatedBroadcastsInternal();
19500                final int childCount = (removedChildPackages != null)
19501                        ? removedChildPackages.size() : 0;
19502                for (int i = 0; i < childCount; i++) {
19503                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19504                    if (childInfo.isRemovedPackageSystemUpdate) {
19505                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
19506                    }
19507                }
19508            }
19509        }
19510
19511        void sendSystemPackageAppearedBroadcasts() {
19512            final int packageCount = (appearedChildPackages != null)
19513                    ? appearedChildPackages.size() : 0;
19514            for (int i = 0; i < packageCount; i++) {
19515                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
19516                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
19517                    true /*sendBootCompleted*/, false /*startReceiver*/,
19518                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
19519            }
19520        }
19521
19522        private void sendSystemPackageUpdatedBroadcastsInternal() {
19523            Bundle extras = new Bundle(2);
19524            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
19525            extras.putBoolean(Intent.EXTRA_REPLACING, true);
19526            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19527                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19528            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19529                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19530            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
19531                null, null, 0, removedPackage, null, null);
19532            if (installerPackageName != null) {
19533                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19534                        removedPackage, extras, 0 /*flags*/,
19535                        installerPackageName, null, null);
19536                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19537                        removedPackage, extras, 0 /*flags*/,
19538                        installerPackageName, null, null);
19539            }
19540        }
19541
19542        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
19543            // Don't send static shared library removal broadcasts as these
19544            // libs are visible only the the apps that depend on them an one
19545            // cannot remove the library if it has a dependency.
19546            if (isStaticSharedLib) {
19547                return;
19548            }
19549            Bundle extras = new Bundle(2);
19550            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
19551            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
19552            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
19553            if (isUpdate || isRemovedPackageSystemUpdate) {
19554                extras.putBoolean(Intent.EXTRA_REPLACING, true);
19555            }
19556            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
19557            if (removedPackage != null) {
19558                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19559                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
19560                if (installerPackageName != null) {
19561                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19562                            removedPackage, extras, 0 /*flags*/,
19563                            installerPackageName, null, broadcastUsers);
19564                }
19565                if (dataRemoved && !isRemovedPackageSystemUpdate) {
19566                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
19567                        removedPackage, extras,
19568                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19569                        null, null, broadcastUsers);
19570                }
19571            }
19572            if (removedAppId >= 0) {
19573                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
19574                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19575                    null, null, broadcastUsers);
19576            }
19577        }
19578
19579        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
19580            removedUsers = userIds;
19581            if (removedUsers == null) {
19582                broadcastUsers = null;
19583                return;
19584            }
19585
19586            broadcastUsers = EMPTY_INT_ARRAY;
19587            for (int i = userIds.length - 1; i >= 0; --i) {
19588                final int userId = userIds[i];
19589                if (deletedPackageSetting.getInstantApp(userId)) {
19590                    continue;
19591                }
19592                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
19593            }
19594        }
19595    }
19596
19597    /*
19598     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
19599     * flag is not set, the data directory is removed as well.
19600     * make sure this flag is set for partially installed apps. If not its meaningless to
19601     * delete a partially installed application.
19602     */
19603    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
19604            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
19605        String packageName = ps.name;
19606        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
19607        // Retrieve object to delete permissions for shared user later on
19608        final PackageParser.Package deletedPkg;
19609        final PackageSetting deletedPs;
19610        // reader
19611        synchronized (mPackages) {
19612            deletedPkg = mPackages.get(packageName);
19613            deletedPs = mSettings.mPackages.get(packageName);
19614            if (outInfo != null) {
19615                outInfo.removedPackage = packageName;
19616                outInfo.installerPackageName = ps.installerPackageName;
19617                outInfo.isStaticSharedLib = deletedPkg != null
19618                        && deletedPkg.staticSharedLibName != null;
19619                outInfo.populateUsers(deletedPs == null ? null
19620                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
19621            }
19622        }
19623
19624        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
19625
19626        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
19627            final PackageParser.Package resolvedPkg;
19628            if (deletedPkg != null) {
19629                resolvedPkg = deletedPkg;
19630            } else {
19631                // We don't have a parsed package when it lives on an ejected
19632                // adopted storage device, so fake something together
19633                resolvedPkg = new PackageParser.Package(ps.name);
19634                resolvedPkg.setVolumeUuid(ps.volumeUuid);
19635            }
19636            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
19637                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19638            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
19639            if (outInfo != null) {
19640                outInfo.dataRemoved = true;
19641            }
19642            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
19643        }
19644
19645        int removedAppId = -1;
19646
19647        // writer
19648        synchronized (mPackages) {
19649            boolean installedStateChanged = false;
19650            if (deletedPs != null) {
19651                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
19652                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
19653                    clearDefaultBrowserIfNeeded(packageName);
19654                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
19655                    removedAppId = mSettings.removePackageLPw(packageName);
19656                    if (outInfo != null) {
19657                        outInfo.removedAppId = removedAppId;
19658                    }
19659                    updatePermissionsLPw(deletedPs.name, null, 0);
19660                    if (deletedPs.sharedUser != null) {
19661                        // Remove permissions associated with package. Since runtime
19662                        // permissions are per user we have to kill the removed package
19663                        // or packages running under the shared user of the removed
19664                        // package if revoking the permissions requested only by the removed
19665                        // package is successful and this causes a change in gids.
19666                        for (int userId : UserManagerService.getInstance().getUserIds()) {
19667                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19668                                    userId);
19669                            if (userIdToKill == UserHandle.USER_ALL
19670                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
19671                                // If gids changed for this user, kill all affected packages.
19672                                mHandler.post(new Runnable() {
19673                                    @Override
19674                                    public void run() {
19675                                        // This has to happen with no lock held.
19676                                        killApplication(deletedPs.name, deletedPs.appId,
19677                                                KILL_APP_REASON_GIDS_CHANGED);
19678                                    }
19679                                });
19680                                break;
19681                            }
19682                        }
19683                    }
19684                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19685                }
19686                // make sure to preserve per-user disabled state if this removal was just
19687                // a downgrade of a system app to the factory package
19688                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19689                    if (DEBUG_REMOVE) {
19690                        Slog.d(TAG, "Propagating install state across downgrade");
19691                    }
19692                    for (int userId : allUserHandles) {
19693                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19694                        if (DEBUG_REMOVE) {
19695                            Slog.d(TAG, "    user " + userId + " => " + installed);
19696                        }
19697                        if (installed != ps.getInstalled(userId)) {
19698                            installedStateChanged = true;
19699                        }
19700                        ps.setInstalled(installed, userId);
19701                    }
19702                }
19703            }
19704            // can downgrade to reader
19705            if (writeSettings) {
19706                // Save settings now
19707                mSettings.writeLPr();
19708            }
19709            if (installedStateChanged) {
19710                mSettings.writeKernelMappingLPr(ps);
19711            }
19712        }
19713        if (removedAppId != -1) {
19714            // A user ID was deleted here. Go through all users and remove it
19715            // from KeyStore.
19716            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19717        }
19718    }
19719
19720    static boolean locationIsPrivileged(File path) {
19721        try {
19722            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19723                    .getCanonicalPath();
19724            return path.getCanonicalPath().startsWith(privilegedAppDir);
19725        } catch (IOException e) {
19726            Slog.e(TAG, "Unable to access code path " + path);
19727        }
19728        return false;
19729    }
19730
19731    /*
19732     * Tries to delete system package.
19733     */
19734    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19735            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19736            boolean writeSettings) {
19737        if (deletedPs.parentPackageName != null) {
19738            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19739            return false;
19740        }
19741
19742        final boolean applyUserRestrictions
19743                = (allUserHandles != null) && (outInfo.origUsers != null);
19744        final PackageSetting disabledPs;
19745        // Confirm if the system package has been updated
19746        // An updated system app can be deleted. This will also have to restore
19747        // the system pkg from system partition
19748        // reader
19749        synchronized (mPackages) {
19750            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19751        }
19752
19753        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19754                + " disabledPs=" + disabledPs);
19755
19756        if (disabledPs == null) {
19757            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19758            return false;
19759        } else if (DEBUG_REMOVE) {
19760            Slog.d(TAG, "Deleting system pkg from data partition");
19761        }
19762
19763        if (DEBUG_REMOVE) {
19764            if (applyUserRestrictions) {
19765                Slog.d(TAG, "Remembering install states:");
19766                for (int userId : allUserHandles) {
19767                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19768                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
19769                }
19770            }
19771        }
19772
19773        // Delete the updated package
19774        outInfo.isRemovedPackageSystemUpdate = true;
19775        if (outInfo.removedChildPackages != null) {
19776            final int childCount = (deletedPs.childPackageNames != null)
19777                    ? deletedPs.childPackageNames.size() : 0;
19778            for (int i = 0; i < childCount; i++) {
19779                String childPackageName = deletedPs.childPackageNames.get(i);
19780                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19781                        .contains(childPackageName)) {
19782                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19783                            childPackageName);
19784                    if (childInfo != null) {
19785                        childInfo.isRemovedPackageSystemUpdate = true;
19786                    }
19787                }
19788            }
19789        }
19790
19791        if (disabledPs.versionCode < deletedPs.versionCode) {
19792            // Delete data for downgrades
19793            flags &= ~PackageManager.DELETE_KEEP_DATA;
19794        } else {
19795            // Preserve data by setting flag
19796            flags |= PackageManager.DELETE_KEEP_DATA;
19797        }
19798
19799        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19800                outInfo, writeSettings, disabledPs.pkg);
19801        if (!ret) {
19802            return false;
19803        }
19804
19805        // writer
19806        synchronized (mPackages) {
19807            // NOTE: The system package always needs to be enabled; even if it's for
19808            // a compressed stub. If we don't, installing the system package fails
19809            // during scan [scanning checks the disabled packages]. We will reverse
19810            // this later, after we've "installed" the stub.
19811            // Reinstate the old system package
19812            enableSystemPackageLPw(disabledPs.pkg);
19813            // Remove any native libraries from the upgraded package.
19814            removeNativeBinariesLI(deletedPs);
19815        }
19816
19817        // Install the system package
19818        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19819        try {
19820            installPackageFromSystemLIF(disabledPs.codePath, false /*isPrivileged*/, allUserHandles,
19821                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
19822        } catch (PackageManagerException e) {
19823            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19824                    + e.getMessage());
19825            return false;
19826        } finally {
19827            if (disabledPs.pkg.isStub) {
19828                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
19829            }
19830        }
19831        return true;
19832    }
19833
19834    /**
19835     * Installs a package that's already on the system partition.
19836     */
19837    private PackageParser.Package installPackageFromSystemLIF(@NonNull File codePath,
19838            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
19839            @Nullable PermissionsState origPermissionState, boolean writeSettings)
19840                    throws PackageManagerException {
19841        int parseFlags = mDefParseFlags
19842                | PackageParser.PARSE_MUST_BE_APK
19843                | PackageParser.PARSE_IS_SYSTEM
19844                | PackageParser.PARSE_IS_SYSTEM_DIR;
19845        if (isPrivileged || locationIsPrivileged(codePath)) {
19846            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19847        }
19848
19849        final PackageParser.Package newPkg =
19850                scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/, 0 /*currentTime*/, null);
19851
19852        try {
19853            // update shared libraries for the newly re-installed system package
19854            updateSharedLibrariesLPr(newPkg, null);
19855        } catch (PackageManagerException e) {
19856            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19857        }
19858
19859        prepareAppDataAfterInstallLIF(newPkg);
19860
19861        // writer
19862        synchronized (mPackages) {
19863            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19864
19865            // Propagate the permissions state as we do not want to drop on the floor
19866            // runtime permissions. The update permissions method below will take
19867            // care of removing obsolete permissions and grant install permissions.
19868            if (origPermissionState != null) {
19869                ps.getPermissionsState().copyFrom(origPermissionState);
19870            }
19871            updatePermissionsLPw(newPkg.packageName, newPkg,
19872                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19873
19874            final boolean applyUserRestrictions
19875                    = (allUserHandles != null) && (origUserHandles != null);
19876            if (applyUserRestrictions) {
19877                boolean installedStateChanged = false;
19878                if (DEBUG_REMOVE) {
19879                    Slog.d(TAG, "Propagating install state across reinstall");
19880                }
19881                for (int userId : allUserHandles) {
19882                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
19883                    if (DEBUG_REMOVE) {
19884                        Slog.d(TAG, "    user " + userId + " => " + installed);
19885                    }
19886                    if (installed != ps.getInstalled(userId)) {
19887                        installedStateChanged = true;
19888                    }
19889                    ps.setInstalled(installed, userId);
19890
19891                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19892                }
19893                // Regardless of writeSettings we need to ensure that this restriction
19894                // state propagation is persisted
19895                mSettings.writeAllUsersPackageRestrictionsLPr();
19896                if (installedStateChanged) {
19897                    mSettings.writeKernelMappingLPr(ps);
19898                }
19899            }
19900            // can downgrade to reader here
19901            if (writeSettings) {
19902                mSettings.writeLPr();
19903            }
19904        }
19905        return newPkg;
19906    }
19907
19908    private boolean deleteInstalledPackageLIF(PackageSetting ps,
19909            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19910            PackageRemovedInfo outInfo, boolean writeSettings,
19911            PackageParser.Package replacingPackage) {
19912        synchronized (mPackages) {
19913            if (outInfo != null) {
19914                outInfo.uid = ps.appId;
19915            }
19916
19917            if (outInfo != null && outInfo.removedChildPackages != null) {
19918                final int childCount = (ps.childPackageNames != null)
19919                        ? ps.childPackageNames.size() : 0;
19920                for (int i = 0; i < childCount; i++) {
19921                    String childPackageName = ps.childPackageNames.get(i);
19922                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
19923                    if (childPs == null) {
19924                        return false;
19925                    }
19926                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19927                            childPackageName);
19928                    if (childInfo != null) {
19929                        childInfo.uid = childPs.appId;
19930                    }
19931                }
19932            }
19933        }
19934
19935        // Delete package data from internal structures and also remove data if flag is set
19936        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
19937
19938        // Delete the child packages data
19939        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
19940        for (int i = 0; i < childCount; i++) {
19941            PackageSetting childPs;
19942            synchronized (mPackages) {
19943                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
19944            }
19945            if (childPs != null) {
19946                PackageRemovedInfo childOutInfo = (outInfo != null
19947                        && outInfo.removedChildPackages != null)
19948                        ? outInfo.removedChildPackages.get(childPs.name) : null;
19949                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
19950                        && (replacingPackage != null
19951                        && !replacingPackage.hasChildPackage(childPs.name))
19952                        ? flags & ~DELETE_KEEP_DATA : flags;
19953                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
19954                        deleteFlags, writeSettings);
19955            }
19956        }
19957
19958        // Delete application code and resources only for parent packages
19959        if (ps.parentPackageName == null) {
19960            if (deleteCodeAndResources && (outInfo != null)) {
19961                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
19962                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
19963                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
19964            }
19965        }
19966
19967        return true;
19968    }
19969
19970    @Override
19971    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
19972            int userId) {
19973        mContext.enforceCallingOrSelfPermission(
19974                android.Manifest.permission.DELETE_PACKAGES, null);
19975        synchronized (mPackages) {
19976            // Cannot block uninstall of static shared libs as they are
19977            // considered a part of the using app (emulating static linking).
19978            // Also static libs are installed always on internal storage.
19979            PackageParser.Package pkg = mPackages.get(packageName);
19980            if (pkg != null && pkg.staticSharedLibName != null) {
19981                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
19982                        + " providing static shared library: " + pkg.staticSharedLibName);
19983                return false;
19984            }
19985            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
19986            mSettings.writePackageRestrictionsLPr(userId);
19987        }
19988        return true;
19989    }
19990
19991    @Override
19992    public boolean getBlockUninstallForUser(String packageName, int userId) {
19993        synchronized (mPackages) {
19994            final PackageSetting ps = mSettings.mPackages.get(packageName);
19995            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
19996                return false;
19997            }
19998            return mSettings.getBlockUninstallLPr(userId, packageName);
19999        }
20000    }
20001
20002    @Override
20003    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
20004        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
20005        synchronized (mPackages) {
20006            PackageSetting ps = mSettings.mPackages.get(packageName);
20007            if (ps == null) {
20008                Log.w(TAG, "Package doesn't exist: " + packageName);
20009                return false;
20010            }
20011            if (systemUserApp) {
20012                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
20013            } else {
20014                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
20015            }
20016            mSettings.writeLPr();
20017        }
20018        return true;
20019    }
20020
20021    /*
20022     * This method handles package deletion in general
20023     */
20024    private boolean deletePackageLIF(String packageName, UserHandle user,
20025            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
20026            PackageRemovedInfo outInfo, boolean writeSettings,
20027            PackageParser.Package replacingPackage) {
20028        if (packageName == null) {
20029            Slog.w(TAG, "Attempt to delete null packageName.");
20030            return false;
20031        }
20032
20033        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
20034
20035        PackageSetting ps;
20036        synchronized (mPackages) {
20037            ps = mSettings.mPackages.get(packageName);
20038            if (ps == null) {
20039                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
20040                return false;
20041            }
20042
20043            if (ps.parentPackageName != null && (!isSystemApp(ps)
20044                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
20045                if (DEBUG_REMOVE) {
20046                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
20047                            + ((user == null) ? UserHandle.USER_ALL : user));
20048                }
20049                final int removedUserId = (user != null) ? user.getIdentifier()
20050                        : UserHandle.USER_ALL;
20051                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
20052                    return false;
20053                }
20054                markPackageUninstalledForUserLPw(ps, user);
20055                scheduleWritePackageRestrictionsLocked(user);
20056                return true;
20057            }
20058        }
20059
20060        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
20061                && user.getIdentifier() != UserHandle.USER_ALL)) {
20062            // The caller is asking that the package only be deleted for a single
20063            // user.  To do this, we just mark its uninstalled state and delete
20064            // its data. If this is a system app, we only allow this to happen if
20065            // they have set the special DELETE_SYSTEM_APP which requests different
20066            // semantics than normal for uninstalling system apps.
20067            markPackageUninstalledForUserLPw(ps, user);
20068
20069            if (!isSystemApp(ps)) {
20070                // Do not uninstall the APK if an app should be cached
20071                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
20072                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
20073                    // Other user still have this package installed, so all
20074                    // we need to do is clear this user's data and save that
20075                    // it is uninstalled.
20076                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
20077                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
20078                        return false;
20079                    }
20080                    scheduleWritePackageRestrictionsLocked(user);
20081                    return true;
20082                } else {
20083                    // We need to set it back to 'installed' so the uninstall
20084                    // broadcasts will be sent correctly.
20085                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
20086                    ps.setInstalled(true, user.getIdentifier());
20087                    mSettings.writeKernelMappingLPr(ps);
20088                }
20089            } else {
20090                // This is a system app, so we assume that the
20091                // other users still have this package installed, so all
20092                // we need to do is clear this user's data and save that
20093                // it is uninstalled.
20094                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
20095                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
20096                    return false;
20097                }
20098                scheduleWritePackageRestrictionsLocked(user);
20099                return true;
20100            }
20101        }
20102
20103        // If we are deleting a composite package for all users, keep track
20104        // of result for each child.
20105        if (ps.childPackageNames != null && outInfo != null) {
20106            synchronized (mPackages) {
20107                final int childCount = ps.childPackageNames.size();
20108                outInfo.removedChildPackages = new ArrayMap<>(childCount);
20109                for (int i = 0; i < childCount; i++) {
20110                    String childPackageName = ps.childPackageNames.get(i);
20111                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
20112                    childInfo.removedPackage = childPackageName;
20113                    childInfo.installerPackageName = ps.installerPackageName;
20114                    outInfo.removedChildPackages.put(childPackageName, childInfo);
20115                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
20116                    if (childPs != null) {
20117                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
20118                    }
20119                }
20120            }
20121        }
20122
20123        boolean ret = false;
20124        if (isSystemApp(ps)) {
20125            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
20126            // When an updated system application is deleted we delete the existing resources
20127            // as well and fall back to existing code in system partition
20128            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
20129        } else {
20130            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
20131            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
20132                    outInfo, writeSettings, replacingPackage);
20133        }
20134
20135        // Take a note whether we deleted the package for all users
20136        if (outInfo != null) {
20137            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
20138            if (outInfo.removedChildPackages != null) {
20139                synchronized (mPackages) {
20140                    final int childCount = outInfo.removedChildPackages.size();
20141                    for (int i = 0; i < childCount; i++) {
20142                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
20143                        if (childInfo != null) {
20144                            childInfo.removedForAllUsers = mPackages.get(
20145                                    childInfo.removedPackage) == null;
20146                        }
20147                    }
20148                }
20149            }
20150            // If we uninstalled an update to a system app there may be some
20151            // child packages that appeared as they are declared in the system
20152            // app but were not declared in the update.
20153            if (isSystemApp(ps)) {
20154                synchronized (mPackages) {
20155                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
20156                    final int childCount = (updatedPs.childPackageNames != null)
20157                            ? updatedPs.childPackageNames.size() : 0;
20158                    for (int i = 0; i < childCount; i++) {
20159                        String childPackageName = updatedPs.childPackageNames.get(i);
20160                        if (outInfo.removedChildPackages == null
20161                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
20162                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
20163                            if (childPs == null) {
20164                                continue;
20165                            }
20166                            PackageInstalledInfo installRes = new PackageInstalledInfo();
20167                            installRes.name = childPackageName;
20168                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
20169                            installRes.pkg = mPackages.get(childPackageName);
20170                            installRes.uid = childPs.pkg.applicationInfo.uid;
20171                            if (outInfo.appearedChildPackages == null) {
20172                                outInfo.appearedChildPackages = new ArrayMap<>();
20173                            }
20174                            outInfo.appearedChildPackages.put(childPackageName, installRes);
20175                        }
20176                    }
20177                }
20178            }
20179        }
20180
20181        return ret;
20182    }
20183
20184    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
20185        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
20186                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
20187        for (int nextUserId : userIds) {
20188            if (DEBUG_REMOVE) {
20189                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
20190            }
20191            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
20192                    false /*installed*/,
20193                    true /*stopped*/,
20194                    true /*notLaunched*/,
20195                    false /*hidden*/,
20196                    false /*suspended*/,
20197                    false /*instantApp*/,
20198                    false /*virtualPreload*/,
20199                    null /*lastDisableAppCaller*/,
20200                    null /*enabledComponents*/,
20201                    null /*disabledComponents*/,
20202                    ps.readUserState(nextUserId).domainVerificationStatus,
20203                    0, PackageManager.INSTALL_REASON_UNKNOWN);
20204        }
20205        mSettings.writeKernelMappingLPr(ps);
20206    }
20207
20208    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
20209            PackageRemovedInfo outInfo) {
20210        final PackageParser.Package pkg;
20211        synchronized (mPackages) {
20212            pkg = mPackages.get(ps.name);
20213        }
20214
20215        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
20216                : new int[] {userId};
20217        for (int nextUserId : userIds) {
20218            if (DEBUG_REMOVE) {
20219                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
20220                        + nextUserId);
20221            }
20222
20223            destroyAppDataLIF(pkg, userId,
20224                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20225            destroyAppProfilesLIF(pkg, userId);
20226            clearDefaultBrowserIfNeededForUser(ps.name, userId);
20227            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
20228            schedulePackageCleaning(ps.name, nextUserId, false);
20229            synchronized (mPackages) {
20230                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
20231                    scheduleWritePackageRestrictionsLocked(nextUserId);
20232                }
20233                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
20234            }
20235        }
20236
20237        if (outInfo != null) {
20238            outInfo.removedPackage = ps.name;
20239            outInfo.installerPackageName = ps.installerPackageName;
20240            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
20241            outInfo.removedAppId = ps.appId;
20242            outInfo.removedUsers = userIds;
20243            outInfo.broadcastUsers = userIds;
20244        }
20245
20246        return true;
20247    }
20248
20249    private final class ClearStorageConnection implements ServiceConnection {
20250        IMediaContainerService mContainerService;
20251
20252        @Override
20253        public void onServiceConnected(ComponentName name, IBinder service) {
20254            synchronized (this) {
20255                mContainerService = IMediaContainerService.Stub
20256                        .asInterface(Binder.allowBlocking(service));
20257                notifyAll();
20258            }
20259        }
20260
20261        @Override
20262        public void onServiceDisconnected(ComponentName name) {
20263        }
20264    }
20265
20266    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
20267        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
20268
20269        final boolean mounted;
20270        if (Environment.isExternalStorageEmulated()) {
20271            mounted = true;
20272        } else {
20273            final String status = Environment.getExternalStorageState();
20274
20275            mounted = status.equals(Environment.MEDIA_MOUNTED)
20276                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
20277        }
20278
20279        if (!mounted) {
20280            return;
20281        }
20282
20283        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
20284        int[] users;
20285        if (userId == UserHandle.USER_ALL) {
20286            users = sUserManager.getUserIds();
20287        } else {
20288            users = new int[] { userId };
20289        }
20290        final ClearStorageConnection conn = new ClearStorageConnection();
20291        if (mContext.bindServiceAsUser(
20292                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
20293            try {
20294                for (int curUser : users) {
20295                    long timeout = SystemClock.uptimeMillis() + 5000;
20296                    synchronized (conn) {
20297                        long now;
20298                        while (conn.mContainerService == null &&
20299                                (now = SystemClock.uptimeMillis()) < timeout) {
20300                            try {
20301                                conn.wait(timeout - now);
20302                            } catch (InterruptedException e) {
20303                            }
20304                        }
20305                    }
20306                    if (conn.mContainerService == null) {
20307                        return;
20308                    }
20309
20310                    final UserEnvironment userEnv = new UserEnvironment(curUser);
20311                    clearDirectory(conn.mContainerService,
20312                            userEnv.buildExternalStorageAppCacheDirs(packageName));
20313                    if (allData) {
20314                        clearDirectory(conn.mContainerService,
20315                                userEnv.buildExternalStorageAppDataDirs(packageName));
20316                        clearDirectory(conn.mContainerService,
20317                                userEnv.buildExternalStorageAppMediaDirs(packageName));
20318                    }
20319                }
20320            } finally {
20321                mContext.unbindService(conn);
20322            }
20323        }
20324    }
20325
20326    @Override
20327    public void clearApplicationProfileData(String packageName) {
20328        enforceSystemOrRoot("Only the system can clear all profile data");
20329
20330        final PackageParser.Package pkg;
20331        synchronized (mPackages) {
20332            pkg = mPackages.get(packageName);
20333        }
20334
20335        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
20336            synchronized (mInstallLock) {
20337                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
20338            }
20339        }
20340    }
20341
20342    @Override
20343    public void clearApplicationUserData(final String packageName,
20344            final IPackageDataObserver observer, final int userId) {
20345        mContext.enforceCallingOrSelfPermission(
20346                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
20347
20348        final int callingUid = Binder.getCallingUid();
20349        enforceCrossUserPermission(callingUid, userId,
20350                true /* requireFullPermission */, false /* checkShell */, "clear application data");
20351
20352        final PackageSetting ps = mSettings.getPackageLPr(packageName);
20353        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
20354        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
20355            throw new SecurityException("Cannot clear data for a protected package: "
20356                    + packageName);
20357        }
20358        // Queue up an async operation since the package deletion may take a little while.
20359        mHandler.post(new Runnable() {
20360            public void run() {
20361                mHandler.removeCallbacks(this);
20362                final boolean succeeded;
20363                if (!filterApp) {
20364                    try (PackageFreezer freezer = freezePackage(packageName,
20365                            "clearApplicationUserData")) {
20366                        synchronized (mInstallLock) {
20367                            succeeded = clearApplicationUserDataLIF(packageName, userId);
20368                        }
20369                        clearExternalStorageDataSync(packageName, userId, true);
20370                        synchronized (mPackages) {
20371                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
20372                                    packageName, userId);
20373                        }
20374                    }
20375                    if (succeeded) {
20376                        // invoke DeviceStorageMonitor's update method to clear any notifications
20377                        DeviceStorageMonitorInternal dsm = LocalServices
20378                                .getService(DeviceStorageMonitorInternal.class);
20379                        if (dsm != null) {
20380                            dsm.checkMemory();
20381                        }
20382                    }
20383                } else {
20384                    succeeded = false;
20385                }
20386                if (observer != null) {
20387                    try {
20388                        observer.onRemoveCompleted(packageName, succeeded);
20389                    } catch (RemoteException e) {
20390                        Log.i(TAG, "Observer no longer exists.");
20391                    }
20392                } //end if observer
20393            } //end run
20394        });
20395    }
20396
20397    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
20398        if (packageName == null) {
20399            Slog.w(TAG, "Attempt to delete null packageName.");
20400            return false;
20401        }
20402
20403        // Try finding details about the requested package
20404        PackageParser.Package pkg;
20405        synchronized (mPackages) {
20406            pkg = mPackages.get(packageName);
20407            if (pkg == null) {
20408                final PackageSetting ps = mSettings.mPackages.get(packageName);
20409                if (ps != null) {
20410                    pkg = ps.pkg;
20411                }
20412            }
20413
20414            if (pkg == null) {
20415                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
20416                return false;
20417            }
20418
20419            PackageSetting ps = (PackageSetting) pkg.mExtras;
20420            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
20421        }
20422
20423        clearAppDataLIF(pkg, userId,
20424                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20425
20426        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20427        removeKeystoreDataIfNeeded(userId, appId);
20428
20429        UserManagerInternal umInternal = getUserManagerInternal();
20430        final int flags;
20431        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
20432            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
20433        } else if (umInternal.isUserRunning(userId)) {
20434            flags = StorageManager.FLAG_STORAGE_DE;
20435        } else {
20436            flags = 0;
20437        }
20438        prepareAppDataContentsLIF(pkg, userId, flags);
20439
20440        return true;
20441    }
20442
20443    /**
20444     * Reverts user permission state changes (permissions and flags) in
20445     * all packages for a given user.
20446     *
20447     * @param userId The device user for which to do a reset.
20448     */
20449    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
20450        final int packageCount = mPackages.size();
20451        for (int i = 0; i < packageCount; i++) {
20452            PackageParser.Package pkg = mPackages.valueAt(i);
20453            PackageSetting ps = (PackageSetting) pkg.mExtras;
20454            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
20455        }
20456    }
20457
20458    private void resetNetworkPolicies(int userId) {
20459        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
20460    }
20461
20462    /**
20463     * Reverts user permission state changes (permissions and flags).
20464     *
20465     * @param ps The package for which to reset.
20466     * @param userId The device user for which to do a reset.
20467     */
20468    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
20469            final PackageSetting ps, final int userId) {
20470        if (ps.pkg == null) {
20471            return;
20472        }
20473
20474        // These are flags that can change base on user actions.
20475        final int userSettableMask = FLAG_PERMISSION_USER_SET
20476                | FLAG_PERMISSION_USER_FIXED
20477                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
20478                | FLAG_PERMISSION_REVIEW_REQUIRED;
20479
20480        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
20481                | FLAG_PERMISSION_POLICY_FIXED;
20482
20483        boolean writeInstallPermissions = false;
20484        boolean writeRuntimePermissions = false;
20485
20486        final int permissionCount = ps.pkg.requestedPermissions.size();
20487        for (int i = 0; i < permissionCount; i++) {
20488            String permission = ps.pkg.requestedPermissions.get(i);
20489
20490            BasePermission bp = mSettings.mPermissions.get(permission);
20491            if (bp == null) {
20492                continue;
20493            }
20494
20495            // If shared user we just reset the state to which only this app contributed.
20496            if (ps.sharedUser != null) {
20497                boolean used = false;
20498                final int packageCount = ps.sharedUser.packages.size();
20499                for (int j = 0; j < packageCount; j++) {
20500                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
20501                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
20502                            && pkg.pkg.requestedPermissions.contains(permission)) {
20503                        used = true;
20504                        break;
20505                    }
20506                }
20507                if (used) {
20508                    continue;
20509                }
20510            }
20511
20512            PermissionsState permissionsState = ps.getPermissionsState();
20513
20514            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
20515
20516            // Always clear the user settable flags.
20517            final boolean hasInstallState = permissionsState.getInstallPermissionState(
20518                    bp.name) != null;
20519            // If permission review is enabled and this is a legacy app, mark the
20520            // permission as requiring a review as this is the initial state.
20521            int flags = 0;
20522            if (mPermissionReviewRequired
20523                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
20524                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
20525            }
20526            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
20527                if (hasInstallState) {
20528                    writeInstallPermissions = true;
20529                } else {
20530                    writeRuntimePermissions = true;
20531                }
20532            }
20533
20534            // Below is only runtime permission handling.
20535            if (!bp.isRuntime()) {
20536                continue;
20537            }
20538
20539            // Never clobber system or policy.
20540            if ((oldFlags & policyOrSystemFlags) != 0) {
20541                continue;
20542            }
20543
20544            // If this permission was granted by default, make sure it is.
20545            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
20546                if (permissionsState.grantRuntimePermission(bp, userId)
20547                        != PERMISSION_OPERATION_FAILURE) {
20548                    writeRuntimePermissions = true;
20549                }
20550            // If permission review is enabled the permissions for a legacy apps
20551            // are represented as constantly granted runtime ones, so don't revoke.
20552            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
20553                // Otherwise, reset the permission.
20554                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
20555                switch (revokeResult) {
20556                    case PERMISSION_OPERATION_SUCCESS:
20557                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
20558                        writeRuntimePermissions = true;
20559                        final int appId = ps.appId;
20560                        mHandler.post(new Runnable() {
20561                            @Override
20562                            public void run() {
20563                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
20564                            }
20565                        });
20566                    } break;
20567                }
20568            }
20569        }
20570
20571        // Synchronously write as we are taking permissions away.
20572        if (writeRuntimePermissions) {
20573            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
20574        }
20575
20576        // Synchronously write as we are taking permissions away.
20577        if (writeInstallPermissions) {
20578            mSettings.writeLPr();
20579        }
20580    }
20581
20582    /**
20583     * Remove entries from the keystore daemon. Will only remove it if the
20584     * {@code appId} is valid.
20585     */
20586    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
20587        if (appId < 0) {
20588            return;
20589        }
20590
20591        final KeyStore keyStore = KeyStore.getInstance();
20592        if (keyStore != null) {
20593            if (userId == UserHandle.USER_ALL) {
20594                for (final int individual : sUserManager.getUserIds()) {
20595                    keyStore.clearUid(UserHandle.getUid(individual, appId));
20596                }
20597            } else {
20598                keyStore.clearUid(UserHandle.getUid(userId, appId));
20599            }
20600        } else {
20601            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
20602        }
20603    }
20604
20605    @Override
20606    public void deleteApplicationCacheFiles(final String packageName,
20607            final IPackageDataObserver observer) {
20608        final int userId = UserHandle.getCallingUserId();
20609        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
20610    }
20611
20612    @Override
20613    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
20614            final IPackageDataObserver observer) {
20615        final int callingUid = Binder.getCallingUid();
20616        mContext.enforceCallingOrSelfPermission(
20617                android.Manifest.permission.DELETE_CACHE_FILES, null);
20618        enforceCrossUserPermission(callingUid, userId,
20619                /* requireFullPermission= */ true, /* checkShell= */ false,
20620                "delete application cache files");
20621        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
20622                android.Manifest.permission.ACCESS_INSTANT_APPS);
20623
20624        final PackageParser.Package pkg;
20625        synchronized (mPackages) {
20626            pkg = mPackages.get(packageName);
20627        }
20628
20629        // Queue up an async operation since the package deletion may take a little while.
20630        mHandler.post(new Runnable() {
20631            public void run() {
20632                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
20633                boolean doClearData = true;
20634                if (ps != null) {
20635                    final boolean targetIsInstantApp =
20636                            ps.getInstantApp(UserHandle.getUserId(callingUid));
20637                    doClearData = !targetIsInstantApp
20638                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
20639                }
20640                if (doClearData) {
20641                    synchronized (mInstallLock) {
20642                        final int flags = StorageManager.FLAG_STORAGE_DE
20643                                | StorageManager.FLAG_STORAGE_CE;
20644                        // We're only clearing cache files, so we don't care if the
20645                        // app is unfrozen and still able to run
20646                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
20647                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20648                    }
20649                    clearExternalStorageDataSync(packageName, userId, false);
20650                }
20651                if (observer != null) {
20652                    try {
20653                        observer.onRemoveCompleted(packageName, true);
20654                    } catch (RemoteException e) {
20655                        Log.i(TAG, "Observer no longer exists.");
20656                    }
20657                }
20658            }
20659        });
20660    }
20661
20662    @Override
20663    public void getPackageSizeInfo(final String packageName, int userHandle,
20664            final IPackageStatsObserver observer) {
20665        throw new UnsupportedOperationException(
20666                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
20667    }
20668
20669    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
20670        final PackageSetting ps;
20671        synchronized (mPackages) {
20672            ps = mSettings.mPackages.get(packageName);
20673            if (ps == null) {
20674                Slog.w(TAG, "Failed to find settings for " + packageName);
20675                return false;
20676            }
20677        }
20678
20679        final String[] packageNames = { packageName };
20680        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
20681        final String[] codePaths = { ps.codePathString };
20682
20683        try {
20684            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20685                    ps.appId, ceDataInodes, codePaths, stats);
20686
20687            // For now, ignore code size of packages on system partition
20688            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20689                stats.codeSize = 0;
20690            }
20691
20692            // External clients expect these to be tracked separately
20693            stats.dataSize -= stats.cacheSize;
20694
20695        } catch (InstallerException e) {
20696            Slog.w(TAG, String.valueOf(e));
20697            return false;
20698        }
20699
20700        return true;
20701    }
20702
20703    private int getUidTargetSdkVersionLockedLPr(int uid) {
20704        Object obj = mSettings.getUserIdLPr(uid);
20705        if (obj instanceof SharedUserSetting) {
20706            final SharedUserSetting sus = (SharedUserSetting) obj;
20707            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20708            final Iterator<PackageSetting> it = sus.packages.iterator();
20709            while (it.hasNext()) {
20710                final PackageSetting ps = it.next();
20711                if (ps.pkg != null) {
20712                    int v = ps.pkg.applicationInfo.targetSdkVersion;
20713                    if (v < vers) vers = v;
20714                }
20715            }
20716            return vers;
20717        } else if (obj instanceof PackageSetting) {
20718            final PackageSetting ps = (PackageSetting) obj;
20719            if (ps.pkg != null) {
20720                return ps.pkg.applicationInfo.targetSdkVersion;
20721            }
20722        }
20723        return Build.VERSION_CODES.CUR_DEVELOPMENT;
20724    }
20725
20726    @Override
20727    public void addPreferredActivity(IntentFilter filter, int match,
20728            ComponentName[] set, ComponentName activity, int userId) {
20729        addPreferredActivityInternal(filter, match, set, activity, true, userId,
20730                "Adding preferred");
20731    }
20732
20733    private void addPreferredActivityInternal(IntentFilter filter, int match,
20734            ComponentName[] set, ComponentName activity, boolean always, int userId,
20735            String opname) {
20736        // writer
20737        int callingUid = Binder.getCallingUid();
20738        enforceCrossUserPermission(callingUid, userId,
20739                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20740        if (filter.countActions() == 0) {
20741            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20742            return;
20743        }
20744        synchronized (mPackages) {
20745            if (mContext.checkCallingOrSelfPermission(
20746                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20747                    != PackageManager.PERMISSION_GRANTED) {
20748                if (getUidTargetSdkVersionLockedLPr(callingUid)
20749                        < Build.VERSION_CODES.FROYO) {
20750                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20751                            + callingUid);
20752                    return;
20753                }
20754                mContext.enforceCallingOrSelfPermission(
20755                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20756            }
20757
20758            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20759            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20760                    + userId + ":");
20761            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20762            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20763            scheduleWritePackageRestrictionsLocked(userId);
20764            postPreferredActivityChangedBroadcast(userId);
20765        }
20766    }
20767
20768    private void postPreferredActivityChangedBroadcast(int userId) {
20769        mHandler.post(() -> {
20770            final IActivityManager am = ActivityManager.getService();
20771            if (am == null) {
20772                return;
20773            }
20774
20775            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20776            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20777            try {
20778                am.broadcastIntent(null, intent, null, null,
20779                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
20780                        null, false, false, userId);
20781            } catch (RemoteException e) {
20782            }
20783        });
20784    }
20785
20786    @Override
20787    public void replacePreferredActivity(IntentFilter filter, int match,
20788            ComponentName[] set, ComponentName activity, int userId) {
20789        if (filter.countActions() != 1) {
20790            throw new IllegalArgumentException(
20791                    "replacePreferredActivity expects filter to have only 1 action.");
20792        }
20793        if (filter.countDataAuthorities() != 0
20794                || filter.countDataPaths() != 0
20795                || filter.countDataSchemes() > 1
20796                || filter.countDataTypes() != 0) {
20797            throw new IllegalArgumentException(
20798                    "replacePreferredActivity expects filter to have no data authorities, " +
20799                    "paths, or types; and at most one scheme.");
20800        }
20801
20802        final int callingUid = Binder.getCallingUid();
20803        enforceCrossUserPermission(callingUid, userId,
20804                true /* requireFullPermission */, false /* checkShell */,
20805                "replace preferred activity");
20806        synchronized (mPackages) {
20807            if (mContext.checkCallingOrSelfPermission(
20808                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20809                    != PackageManager.PERMISSION_GRANTED) {
20810                if (getUidTargetSdkVersionLockedLPr(callingUid)
20811                        < Build.VERSION_CODES.FROYO) {
20812                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20813                            + Binder.getCallingUid());
20814                    return;
20815                }
20816                mContext.enforceCallingOrSelfPermission(
20817                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20818            }
20819
20820            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20821            if (pir != null) {
20822                // Get all of the existing entries that exactly match this filter.
20823                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20824                if (existing != null && existing.size() == 1) {
20825                    PreferredActivity cur = existing.get(0);
20826                    if (DEBUG_PREFERRED) {
20827                        Slog.i(TAG, "Checking replace of preferred:");
20828                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20829                        if (!cur.mPref.mAlways) {
20830                            Slog.i(TAG, "  -- CUR; not mAlways!");
20831                        } else {
20832                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
20833                            Slog.i(TAG, "  -- CUR: mSet="
20834                                    + Arrays.toString(cur.mPref.mSetComponents));
20835                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
20836                            Slog.i(TAG, "  -- NEW: mMatch="
20837                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
20838                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
20839                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
20840                        }
20841                    }
20842                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20843                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20844                            && cur.mPref.sameSet(set)) {
20845                        // Setting the preferred activity to what it happens to be already
20846                        if (DEBUG_PREFERRED) {
20847                            Slog.i(TAG, "Replacing with same preferred activity "
20848                                    + cur.mPref.mShortComponent + " for user "
20849                                    + userId + ":");
20850                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20851                        }
20852                        return;
20853                    }
20854                }
20855
20856                if (existing != null) {
20857                    if (DEBUG_PREFERRED) {
20858                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
20859                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20860                    }
20861                    for (int i = 0; i < existing.size(); i++) {
20862                        PreferredActivity pa = existing.get(i);
20863                        if (DEBUG_PREFERRED) {
20864                            Slog.i(TAG, "Removing existing preferred activity "
20865                                    + pa.mPref.mComponent + ":");
20866                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
20867                        }
20868                        pir.removeFilter(pa);
20869                    }
20870                }
20871            }
20872            addPreferredActivityInternal(filter, match, set, activity, true, userId,
20873                    "Replacing preferred");
20874        }
20875    }
20876
20877    @Override
20878    public void clearPackagePreferredActivities(String packageName) {
20879        final int callingUid = Binder.getCallingUid();
20880        if (getInstantAppPackageName(callingUid) != null) {
20881            return;
20882        }
20883        // writer
20884        synchronized (mPackages) {
20885            PackageParser.Package pkg = mPackages.get(packageName);
20886            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20887                if (mContext.checkCallingOrSelfPermission(
20888                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20889                        != PackageManager.PERMISSION_GRANTED) {
20890                    if (getUidTargetSdkVersionLockedLPr(callingUid)
20891                            < Build.VERSION_CODES.FROYO) {
20892                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20893                                + callingUid);
20894                        return;
20895                    }
20896                    mContext.enforceCallingOrSelfPermission(
20897                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20898                }
20899            }
20900            final PackageSetting ps = mSettings.getPackageLPr(packageName);
20901            if (ps != null
20902                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20903                return;
20904            }
20905            int user = UserHandle.getCallingUserId();
20906            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20907                scheduleWritePackageRestrictionsLocked(user);
20908            }
20909        }
20910    }
20911
20912    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20913    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
20914        ArrayList<PreferredActivity> removed = null;
20915        boolean changed = false;
20916        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20917            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
20918            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20919            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
20920                continue;
20921            }
20922            Iterator<PreferredActivity> it = pir.filterIterator();
20923            while (it.hasNext()) {
20924                PreferredActivity pa = it.next();
20925                // Mark entry for removal only if it matches the package name
20926                // and the entry is of type "always".
20927                if (packageName == null ||
20928                        (pa.mPref.mComponent.getPackageName().equals(packageName)
20929                                && pa.mPref.mAlways)) {
20930                    if (removed == null) {
20931                        removed = new ArrayList<PreferredActivity>();
20932                    }
20933                    removed.add(pa);
20934                }
20935            }
20936            if (removed != null) {
20937                for (int j=0; j<removed.size(); j++) {
20938                    PreferredActivity pa = removed.get(j);
20939                    pir.removeFilter(pa);
20940                }
20941                changed = true;
20942            }
20943        }
20944        if (changed) {
20945            postPreferredActivityChangedBroadcast(userId);
20946        }
20947        return changed;
20948    }
20949
20950    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20951    private void clearIntentFilterVerificationsLPw(int userId) {
20952        final int packageCount = mPackages.size();
20953        for (int i = 0; i < packageCount; i++) {
20954            PackageParser.Package pkg = mPackages.valueAt(i);
20955            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
20956        }
20957    }
20958
20959    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20960    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
20961        if (userId == UserHandle.USER_ALL) {
20962            if (mSettings.removeIntentFilterVerificationLPw(packageName,
20963                    sUserManager.getUserIds())) {
20964                for (int oneUserId : sUserManager.getUserIds()) {
20965                    scheduleWritePackageRestrictionsLocked(oneUserId);
20966                }
20967            }
20968        } else {
20969            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
20970                scheduleWritePackageRestrictionsLocked(userId);
20971            }
20972        }
20973    }
20974
20975    /** Clears state for all users, and touches intent filter verification policy */
20976    void clearDefaultBrowserIfNeeded(String packageName) {
20977        for (int oneUserId : sUserManager.getUserIds()) {
20978            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
20979        }
20980    }
20981
20982    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
20983        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
20984        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
20985            if (packageName.equals(defaultBrowserPackageName)) {
20986                setDefaultBrowserPackageName(null, userId);
20987            }
20988        }
20989    }
20990
20991    @Override
20992    public void resetApplicationPreferences(int userId) {
20993        mContext.enforceCallingOrSelfPermission(
20994                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20995        final long identity = Binder.clearCallingIdentity();
20996        // writer
20997        try {
20998            synchronized (mPackages) {
20999                clearPackagePreferredActivitiesLPw(null, userId);
21000                mSettings.applyDefaultPreferredAppsLPw(this, userId);
21001                // TODO: We have to reset the default SMS and Phone. This requires
21002                // significant refactoring to keep all default apps in the package
21003                // manager (cleaner but more work) or have the services provide
21004                // callbacks to the package manager to request a default app reset.
21005                applyFactoryDefaultBrowserLPw(userId);
21006                clearIntentFilterVerificationsLPw(userId);
21007                primeDomainVerificationsLPw(userId);
21008                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
21009                scheduleWritePackageRestrictionsLocked(userId);
21010            }
21011            resetNetworkPolicies(userId);
21012        } finally {
21013            Binder.restoreCallingIdentity(identity);
21014        }
21015    }
21016
21017    @Override
21018    public int getPreferredActivities(List<IntentFilter> outFilters,
21019            List<ComponentName> outActivities, String packageName) {
21020        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21021            return 0;
21022        }
21023        int num = 0;
21024        final int userId = UserHandle.getCallingUserId();
21025        // reader
21026        synchronized (mPackages) {
21027            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
21028            if (pir != null) {
21029                final Iterator<PreferredActivity> it = pir.filterIterator();
21030                while (it.hasNext()) {
21031                    final PreferredActivity pa = it.next();
21032                    if (packageName == null
21033                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
21034                                    && pa.mPref.mAlways)) {
21035                        if (outFilters != null) {
21036                            outFilters.add(new IntentFilter(pa));
21037                        }
21038                        if (outActivities != null) {
21039                            outActivities.add(pa.mPref.mComponent);
21040                        }
21041                    }
21042                }
21043            }
21044        }
21045
21046        return num;
21047    }
21048
21049    @Override
21050    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
21051            int userId) {
21052        int callingUid = Binder.getCallingUid();
21053        if (callingUid != Process.SYSTEM_UID) {
21054            throw new SecurityException(
21055                    "addPersistentPreferredActivity can only be run by the system");
21056        }
21057        if (filter.countActions() == 0) {
21058            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
21059            return;
21060        }
21061        synchronized (mPackages) {
21062            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
21063                    ":");
21064            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
21065            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
21066                    new PersistentPreferredActivity(filter, activity));
21067            scheduleWritePackageRestrictionsLocked(userId);
21068            postPreferredActivityChangedBroadcast(userId);
21069        }
21070    }
21071
21072    @Override
21073    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
21074        int callingUid = Binder.getCallingUid();
21075        if (callingUid != Process.SYSTEM_UID) {
21076            throw new SecurityException(
21077                    "clearPackagePersistentPreferredActivities can only be run by the system");
21078        }
21079        ArrayList<PersistentPreferredActivity> removed = null;
21080        boolean changed = false;
21081        synchronized (mPackages) {
21082            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
21083                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
21084                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
21085                        .valueAt(i);
21086                if (userId != thisUserId) {
21087                    continue;
21088                }
21089                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
21090                while (it.hasNext()) {
21091                    PersistentPreferredActivity ppa = it.next();
21092                    // Mark entry for removal only if it matches the package name.
21093                    if (ppa.mComponent.getPackageName().equals(packageName)) {
21094                        if (removed == null) {
21095                            removed = new ArrayList<PersistentPreferredActivity>();
21096                        }
21097                        removed.add(ppa);
21098                    }
21099                }
21100                if (removed != null) {
21101                    for (int j=0; j<removed.size(); j++) {
21102                        PersistentPreferredActivity ppa = removed.get(j);
21103                        ppir.removeFilter(ppa);
21104                    }
21105                    changed = true;
21106                }
21107            }
21108
21109            if (changed) {
21110                scheduleWritePackageRestrictionsLocked(userId);
21111                postPreferredActivityChangedBroadcast(userId);
21112            }
21113        }
21114    }
21115
21116    /**
21117     * Common machinery for picking apart a restored XML blob and passing
21118     * it to a caller-supplied functor to be applied to the running system.
21119     */
21120    private void restoreFromXml(XmlPullParser parser, int userId,
21121            String expectedStartTag, BlobXmlRestorer functor)
21122            throws IOException, XmlPullParserException {
21123        int type;
21124        while ((type = parser.next()) != XmlPullParser.START_TAG
21125                && type != XmlPullParser.END_DOCUMENT) {
21126        }
21127        if (type != XmlPullParser.START_TAG) {
21128            // oops didn't find a start tag?!
21129            if (DEBUG_BACKUP) {
21130                Slog.e(TAG, "Didn't find start tag during restore");
21131            }
21132            return;
21133        }
21134Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
21135        // this is supposed to be TAG_PREFERRED_BACKUP
21136        if (!expectedStartTag.equals(parser.getName())) {
21137            if (DEBUG_BACKUP) {
21138                Slog.e(TAG, "Found unexpected tag " + parser.getName());
21139            }
21140            return;
21141        }
21142
21143        // skip interfering stuff, then we're aligned with the backing implementation
21144        while ((type = parser.next()) == XmlPullParser.TEXT) { }
21145Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
21146        functor.apply(parser, userId);
21147    }
21148
21149    private interface BlobXmlRestorer {
21150        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
21151    }
21152
21153    /**
21154     * Non-Binder method, support for the backup/restore mechanism: write the
21155     * full set of preferred activities in its canonical XML format.  Returns the
21156     * XML output as a byte array, or null if there is none.
21157     */
21158    @Override
21159    public byte[] getPreferredActivityBackup(int userId) {
21160        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21161            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
21162        }
21163
21164        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21165        try {
21166            final XmlSerializer serializer = new FastXmlSerializer();
21167            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21168            serializer.startDocument(null, true);
21169            serializer.startTag(null, TAG_PREFERRED_BACKUP);
21170
21171            synchronized (mPackages) {
21172                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
21173            }
21174
21175            serializer.endTag(null, TAG_PREFERRED_BACKUP);
21176            serializer.endDocument();
21177            serializer.flush();
21178        } catch (Exception e) {
21179            if (DEBUG_BACKUP) {
21180                Slog.e(TAG, "Unable to write preferred activities for backup", e);
21181            }
21182            return null;
21183        }
21184
21185        return dataStream.toByteArray();
21186    }
21187
21188    @Override
21189    public void restorePreferredActivities(byte[] backup, int userId) {
21190        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21191            throw new SecurityException("Only the system may call restorePreferredActivities()");
21192        }
21193
21194        try {
21195            final XmlPullParser parser = Xml.newPullParser();
21196            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21197            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
21198                    new BlobXmlRestorer() {
21199                        @Override
21200                        public void apply(XmlPullParser parser, int userId)
21201                                throws XmlPullParserException, IOException {
21202                            synchronized (mPackages) {
21203                                mSettings.readPreferredActivitiesLPw(parser, userId);
21204                            }
21205                        }
21206                    } );
21207        } catch (Exception e) {
21208            if (DEBUG_BACKUP) {
21209                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21210            }
21211        }
21212    }
21213
21214    /**
21215     * Non-Binder method, support for the backup/restore mechanism: write the
21216     * default browser (etc) settings in its canonical XML format.  Returns the default
21217     * browser XML representation as a byte array, or null if there is none.
21218     */
21219    @Override
21220    public byte[] getDefaultAppsBackup(int userId) {
21221        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21222            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
21223        }
21224
21225        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21226        try {
21227            final XmlSerializer serializer = new FastXmlSerializer();
21228            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21229            serializer.startDocument(null, true);
21230            serializer.startTag(null, TAG_DEFAULT_APPS);
21231
21232            synchronized (mPackages) {
21233                mSettings.writeDefaultAppsLPr(serializer, userId);
21234            }
21235
21236            serializer.endTag(null, TAG_DEFAULT_APPS);
21237            serializer.endDocument();
21238            serializer.flush();
21239        } catch (Exception e) {
21240            if (DEBUG_BACKUP) {
21241                Slog.e(TAG, "Unable to write default apps for backup", e);
21242            }
21243            return null;
21244        }
21245
21246        return dataStream.toByteArray();
21247    }
21248
21249    @Override
21250    public void restoreDefaultApps(byte[] backup, int userId) {
21251        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21252            throw new SecurityException("Only the system may call restoreDefaultApps()");
21253        }
21254
21255        try {
21256            final XmlPullParser parser = Xml.newPullParser();
21257            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21258            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
21259                    new BlobXmlRestorer() {
21260                        @Override
21261                        public void apply(XmlPullParser parser, int userId)
21262                                throws XmlPullParserException, IOException {
21263                            synchronized (mPackages) {
21264                                mSettings.readDefaultAppsLPw(parser, userId);
21265                            }
21266                        }
21267                    } );
21268        } catch (Exception e) {
21269            if (DEBUG_BACKUP) {
21270                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
21271            }
21272        }
21273    }
21274
21275    @Override
21276    public byte[] getIntentFilterVerificationBackup(int userId) {
21277        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21278            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
21279        }
21280
21281        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21282        try {
21283            final XmlSerializer serializer = new FastXmlSerializer();
21284            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21285            serializer.startDocument(null, true);
21286            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
21287
21288            synchronized (mPackages) {
21289                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
21290            }
21291
21292            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
21293            serializer.endDocument();
21294            serializer.flush();
21295        } catch (Exception e) {
21296            if (DEBUG_BACKUP) {
21297                Slog.e(TAG, "Unable to write default apps for backup", e);
21298            }
21299            return null;
21300        }
21301
21302        return dataStream.toByteArray();
21303    }
21304
21305    @Override
21306    public void restoreIntentFilterVerification(byte[] backup, int userId) {
21307        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21308            throw new SecurityException("Only the system may call restorePreferredActivities()");
21309        }
21310
21311        try {
21312            final XmlPullParser parser = Xml.newPullParser();
21313            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21314            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
21315                    new BlobXmlRestorer() {
21316                        @Override
21317                        public void apply(XmlPullParser parser, int userId)
21318                                throws XmlPullParserException, IOException {
21319                            synchronized (mPackages) {
21320                                mSettings.readAllDomainVerificationsLPr(parser, userId);
21321                                mSettings.writeLPr();
21322                            }
21323                        }
21324                    } );
21325        } catch (Exception e) {
21326            if (DEBUG_BACKUP) {
21327                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21328            }
21329        }
21330    }
21331
21332    @Override
21333    public byte[] getPermissionGrantBackup(int userId) {
21334        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21335            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
21336        }
21337
21338        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21339        try {
21340            final XmlSerializer serializer = new FastXmlSerializer();
21341            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21342            serializer.startDocument(null, true);
21343            serializer.startTag(null, TAG_PERMISSION_BACKUP);
21344
21345            synchronized (mPackages) {
21346                serializeRuntimePermissionGrantsLPr(serializer, userId);
21347            }
21348
21349            serializer.endTag(null, TAG_PERMISSION_BACKUP);
21350            serializer.endDocument();
21351            serializer.flush();
21352        } catch (Exception e) {
21353            if (DEBUG_BACKUP) {
21354                Slog.e(TAG, "Unable to write default apps for backup", e);
21355            }
21356            return null;
21357        }
21358
21359        return dataStream.toByteArray();
21360    }
21361
21362    @Override
21363    public void restorePermissionGrants(byte[] backup, int userId) {
21364        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21365            throw new SecurityException("Only the system may call restorePermissionGrants()");
21366        }
21367
21368        try {
21369            final XmlPullParser parser = Xml.newPullParser();
21370            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21371            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
21372                    new BlobXmlRestorer() {
21373                        @Override
21374                        public void apply(XmlPullParser parser, int userId)
21375                                throws XmlPullParserException, IOException {
21376                            synchronized (mPackages) {
21377                                processRestoredPermissionGrantsLPr(parser, userId);
21378                            }
21379                        }
21380                    } );
21381        } catch (Exception e) {
21382            if (DEBUG_BACKUP) {
21383                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21384            }
21385        }
21386    }
21387
21388    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
21389            throws IOException {
21390        serializer.startTag(null, TAG_ALL_GRANTS);
21391
21392        final int N = mSettings.mPackages.size();
21393        for (int i = 0; i < N; i++) {
21394            final PackageSetting ps = mSettings.mPackages.valueAt(i);
21395            boolean pkgGrantsKnown = false;
21396
21397            PermissionsState packagePerms = ps.getPermissionsState();
21398
21399            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
21400                final int grantFlags = state.getFlags();
21401                // only look at grants that are not system/policy fixed
21402                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
21403                    final boolean isGranted = state.isGranted();
21404                    // And only back up the user-twiddled state bits
21405                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
21406                        final String packageName = mSettings.mPackages.keyAt(i);
21407                        if (!pkgGrantsKnown) {
21408                            serializer.startTag(null, TAG_GRANT);
21409                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
21410                            pkgGrantsKnown = true;
21411                        }
21412
21413                        final boolean userSet =
21414                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
21415                        final boolean userFixed =
21416                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
21417                        final boolean revoke =
21418                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
21419
21420                        serializer.startTag(null, TAG_PERMISSION);
21421                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
21422                        if (isGranted) {
21423                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
21424                        }
21425                        if (userSet) {
21426                            serializer.attribute(null, ATTR_USER_SET, "true");
21427                        }
21428                        if (userFixed) {
21429                            serializer.attribute(null, ATTR_USER_FIXED, "true");
21430                        }
21431                        if (revoke) {
21432                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
21433                        }
21434                        serializer.endTag(null, TAG_PERMISSION);
21435                    }
21436                }
21437            }
21438
21439            if (pkgGrantsKnown) {
21440                serializer.endTag(null, TAG_GRANT);
21441            }
21442        }
21443
21444        serializer.endTag(null, TAG_ALL_GRANTS);
21445    }
21446
21447    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
21448            throws XmlPullParserException, IOException {
21449        String pkgName = null;
21450        int outerDepth = parser.getDepth();
21451        int type;
21452        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
21453                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
21454            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
21455                continue;
21456            }
21457
21458            final String tagName = parser.getName();
21459            if (tagName.equals(TAG_GRANT)) {
21460                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
21461                if (DEBUG_BACKUP) {
21462                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
21463                }
21464            } else if (tagName.equals(TAG_PERMISSION)) {
21465
21466                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
21467                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
21468
21469                int newFlagSet = 0;
21470                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
21471                    newFlagSet |= FLAG_PERMISSION_USER_SET;
21472                }
21473                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
21474                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
21475                }
21476                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
21477                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
21478                }
21479                if (DEBUG_BACKUP) {
21480                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
21481                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
21482                }
21483                final PackageSetting ps = mSettings.mPackages.get(pkgName);
21484                if (ps != null) {
21485                    // Already installed so we apply the grant immediately
21486                    if (DEBUG_BACKUP) {
21487                        Slog.v(TAG, "        + already installed; applying");
21488                    }
21489                    PermissionsState perms = ps.getPermissionsState();
21490                    BasePermission bp = mSettings.mPermissions.get(permName);
21491                    if (bp != null) {
21492                        if (isGranted) {
21493                            perms.grantRuntimePermission(bp, userId);
21494                        }
21495                        if (newFlagSet != 0) {
21496                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
21497                        }
21498                    }
21499                } else {
21500                    // Need to wait for post-restore install to apply the grant
21501                    if (DEBUG_BACKUP) {
21502                        Slog.v(TAG, "        - not yet installed; saving for later");
21503                    }
21504                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
21505                            isGranted, newFlagSet, userId);
21506                }
21507            } else {
21508                PackageManagerService.reportSettingsProblem(Log.WARN,
21509                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
21510                XmlUtils.skipCurrentTag(parser);
21511            }
21512        }
21513
21514        scheduleWriteSettingsLocked();
21515        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
21516    }
21517
21518    @Override
21519    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
21520            int sourceUserId, int targetUserId, int flags) {
21521        mContext.enforceCallingOrSelfPermission(
21522                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21523        int callingUid = Binder.getCallingUid();
21524        enforceOwnerRights(ownerPackage, callingUid);
21525        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21526        if (intentFilter.countActions() == 0) {
21527            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
21528            return;
21529        }
21530        synchronized (mPackages) {
21531            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
21532                    ownerPackage, targetUserId, flags);
21533            CrossProfileIntentResolver resolver =
21534                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21535            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
21536            // We have all those whose filter is equal. Now checking if the rest is equal as well.
21537            if (existing != null) {
21538                int size = existing.size();
21539                for (int i = 0; i < size; i++) {
21540                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
21541                        return;
21542                    }
21543                }
21544            }
21545            resolver.addFilter(newFilter);
21546            scheduleWritePackageRestrictionsLocked(sourceUserId);
21547        }
21548    }
21549
21550    @Override
21551    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
21552        mContext.enforceCallingOrSelfPermission(
21553                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21554        final int callingUid = Binder.getCallingUid();
21555        enforceOwnerRights(ownerPackage, callingUid);
21556        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21557        synchronized (mPackages) {
21558            CrossProfileIntentResolver resolver =
21559                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21560            ArraySet<CrossProfileIntentFilter> set =
21561                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
21562            for (CrossProfileIntentFilter filter : set) {
21563                if (filter.getOwnerPackage().equals(ownerPackage)) {
21564                    resolver.removeFilter(filter);
21565                }
21566            }
21567            scheduleWritePackageRestrictionsLocked(sourceUserId);
21568        }
21569    }
21570
21571    // Enforcing that callingUid is owning pkg on userId
21572    private void enforceOwnerRights(String pkg, int callingUid) {
21573        // The system owns everything.
21574        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
21575            return;
21576        }
21577        final int callingUserId = UserHandle.getUserId(callingUid);
21578        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
21579        if (pi == null) {
21580            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
21581                    + callingUserId);
21582        }
21583        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
21584            throw new SecurityException("Calling uid " + callingUid
21585                    + " does not own package " + pkg);
21586        }
21587    }
21588
21589    @Override
21590    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
21591        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21592            return null;
21593        }
21594        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
21595    }
21596
21597    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
21598        UserManagerService ums = UserManagerService.getInstance();
21599        if (ums != null) {
21600            final UserInfo parent = ums.getProfileParent(userId);
21601            final int launcherUid = (parent != null) ? parent.id : userId;
21602            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
21603            if (launcherComponent != null) {
21604                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
21605                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
21606                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
21607                        .setPackage(launcherComponent.getPackageName());
21608                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
21609            }
21610        }
21611    }
21612
21613    /**
21614     * Report the 'Home' activity which is currently set as "always use this one". If non is set
21615     * then reports the most likely home activity or null if there are more than one.
21616     */
21617    private ComponentName getDefaultHomeActivity(int userId) {
21618        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
21619        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
21620        if (cn != null) {
21621            return cn;
21622        }
21623
21624        // Find the launcher with the highest priority and return that component if there are no
21625        // other home activity with the same priority.
21626        int lastPriority = Integer.MIN_VALUE;
21627        ComponentName lastComponent = null;
21628        final int size = allHomeCandidates.size();
21629        for (int i = 0; i < size; i++) {
21630            final ResolveInfo ri = allHomeCandidates.get(i);
21631            if (ri.priority > lastPriority) {
21632                lastComponent = ri.activityInfo.getComponentName();
21633                lastPriority = ri.priority;
21634            } else if (ri.priority == lastPriority) {
21635                // Two components found with same priority.
21636                lastComponent = null;
21637            }
21638        }
21639        return lastComponent;
21640    }
21641
21642    private Intent getHomeIntent() {
21643        Intent intent = new Intent(Intent.ACTION_MAIN);
21644        intent.addCategory(Intent.CATEGORY_HOME);
21645        intent.addCategory(Intent.CATEGORY_DEFAULT);
21646        return intent;
21647    }
21648
21649    private IntentFilter getHomeFilter() {
21650        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
21651        filter.addCategory(Intent.CATEGORY_HOME);
21652        filter.addCategory(Intent.CATEGORY_DEFAULT);
21653        return filter;
21654    }
21655
21656    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21657            int userId) {
21658        Intent intent  = getHomeIntent();
21659        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
21660                PackageManager.GET_META_DATA, userId);
21661        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
21662                true, false, false, userId);
21663
21664        allHomeCandidates.clear();
21665        if (list != null) {
21666            for (ResolveInfo ri : list) {
21667                allHomeCandidates.add(ri);
21668            }
21669        }
21670        return (preferred == null || preferred.activityInfo == null)
21671                ? null
21672                : new ComponentName(preferred.activityInfo.packageName,
21673                        preferred.activityInfo.name);
21674    }
21675
21676    @Override
21677    public void setHomeActivity(ComponentName comp, int userId) {
21678        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21679            return;
21680        }
21681        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21682        getHomeActivitiesAsUser(homeActivities, userId);
21683
21684        boolean found = false;
21685
21686        final int size = homeActivities.size();
21687        final ComponentName[] set = new ComponentName[size];
21688        for (int i = 0; i < size; i++) {
21689            final ResolveInfo candidate = homeActivities.get(i);
21690            final ActivityInfo info = candidate.activityInfo;
21691            final ComponentName activityName = new ComponentName(info.packageName, info.name);
21692            set[i] = activityName;
21693            if (!found && activityName.equals(comp)) {
21694                found = true;
21695            }
21696        }
21697        if (!found) {
21698            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21699                    + userId);
21700        }
21701        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21702                set, comp, userId);
21703    }
21704
21705    private @Nullable String getSetupWizardPackageName() {
21706        final Intent intent = new Intent(Intent.ACTION_MAIN);
21707        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21708
21709        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21710                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21711                        | MATCH_DISABLED_COMPONENTS,
21712                UserHandle.myUserId());
21713        if (matches.size() == 1) {
21714            return matches.get(0).getComponentInfo().packageName;
21715        } else {
21716            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21717                    + ": matches=" + matches);
21718            return null;
21719        }
21720    }
21721
21722    private @Nullable String getStorageManagerPackageName() {
21723        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21724
21725        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21726                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21727                        | MATCH_DISABLED_COMPONENTS,
21728                UserHandle.myUserId());
21729        if (matches.size() == 1) {
21730            return matches.get(0).getComponentInfo().packageName;
21731        } else {
21732            Slog.e(TAG, "There should probably be exactly one storage manager; found "
21733                    + matches.size() + ": matches=" + matches);
21734            return null;
21735        }
21736    }
21737
21738    @Override
21739    public void setApplicationEnabledSetting(String appPackageName,
21740            int newState, int flags, int userId, String callingPackage) {
21741        if (!sUserManager.exists(userId)) return;
21742        if (callingPackage == null) {
21743            callingPackage = Integer.toString(Binder.getCallingUid());
21744        }
21745        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21746    }
21747
21748    @Override
21749    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21750        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21751        synchronized (mPackages) {
21752            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21753            if (pkgSetting != null) {
21754                pkgSetting.setUpdateAvailable(updateAvailable);
21755            }
21756        }
21757    }
21758
21759    @Override
21760    public void setComponentEnabledSetting(ComponentName componentName,
21761            int newState, int flags, int userId) {
21762        if (!sUserManager.exists(userId)) return;
21763        setEnabledSetting(componentName.getPackageName(),
21764                componentName.getClassName(), newState, flags, userId, null);
21765    }
21766
21767    private void setEnabledSetting(final String packageName, String className, int newState,
21768            final int flags, int userId, String callingPackage) {
21769        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21770              || newState == COMPONENT_ENABLED_STATE_ENABLED
21771              || newState == COMPONENT_ENABLED_STATE_DISABLED
21772              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21773              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21774            throw new IllegalArgumentException("Invalid new component state: "
21775                    + newState);
21776        }
21777        PackageSetting pkgSetting;
21778        final int callingUid = Binder.getCallingUid();
21779        final int permission;
21780        if (callingUid == Process.SYSTEM_UID) {
21781            permission = PackageManager.PERMISSION_GRANTED;
21782        } else {
21783            permission = mContext.checkCallingOrSelfPermission(
21784                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21785        }
21786        enforceCrossUserPermission(callingUid, userId,
21787                false /* requireFullPermission */, true /* checkShell */, "set enabled");
21788        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21789        boolean sendNow = false;
21790        boolean isApp = (className == null);
21791        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21792        String componentName = isApp ? packageName : className;
21793        int packageUid = -1;
21794        ArrayList<String> components;
21795
21796        // reader
21797        synchronized (mPackages) {
21798            pkgSetting = mSettings.mPackages.get(packageName);
21799            if (pkgSetting == null) {
21800                if (!isCallerInstantApp) {
21801                    if (className == null) {
21802                        throw new IllegalArgumentException("Unknown package: " + packageName);
21803                    }
21804                    throw new IllegalArgumentException(
21805                            "Unknown component: " + packageName + "/" + className);
21806                } else {
21807                    // throw SecurityException to prevent leaking package information
21808                    throw new SecurityException(
21809                            "Attempt to change component state; "
21810                            + "pid=" + Binder.getCallingPid()
21811                            + ", uid=" + callingUid
21812                            + (className == null
21813                                    ? ", package=" + packageName
21814                                    : ", component=" + packageName + "/" + className));
21815                }
21816            }
21817        }
21818
21819        // Limit who can change which apps
21820        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21821            // Don't allow apps that don't have permission to modify other apps
21822            if (!allowedByPermission
21823                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21824                throw new SecurityException(
21825                        "Attempt to change component state; "
21826                        + "pid=" + Binder.getCallingPid()
21827                        + ", uid=" + callingUid
21828                        + (className == null
21829                                ? ", package=" + packageName
21830                                : ", component=" + packageName + "/" + className));
21831            }
21832            // Don't allow changing protected packages.
21833            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21834                throw new SecurityException("Cannot disable a protected package: " + packageName);
21835            }
21836        }
21837
21838        synchronized (mPackages) {
21839            if (callingUid == Process.SHELL_UID
21840                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21841                // Shell can only change whole packages between ENABLED and DISABLED_USER states
21842                // unless it is a test package.
21843                int oldState = pkgSetting.getEnabled(userId);
21844                if (className == null
21845                        &&
21846                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21847                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21848                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21849                        &&
21850                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21851                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
21852                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21853                    // ok
21854                } else {
21855                    throw new SecurityException(
21856                            "Shell cannot change component state for " + packageName + "/"
21857                                    + className + " to " + newState);
21858                }
21859            }
21860        }
21861        if (className == null) {
21862            // We're dealing with an application/package level state change
21863            synchronized (mPackages) {
21864                if (pkgSetting.getEnabled(userId) == newState) {
21865                    // Nothing to do
21866                    return;
21867                }
21868            }
21869            // If we're enabling a system stub, there's a little more work to do.
21870            // Prior to enabling the package, we need to decompress the APK(s) to the
21871            // data partition and then replace the version on the system partition.
21872            final PackageParser.Package deletedPkg = pkgSetting.pkg;
21873            final boolean isSystemStub = deletedPkg.isStub
21874                    && deletedPkg.isSystemApp();
21875            if (isSystemStub
21876                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21877                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
21878                final File codePath = decompressPackage(deletedPkg);
21879                if (codePath == null) {
21880                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
21881                    return;
21882                }
21883                // TODO remove direct parsing of the package object during internal cleanup
21884                // of scan package
21885                // We need to call parse directly here for no other reason than we need
21886                // the new package in order to disable the old one [we use the information
21887                // for some internal optimization to optionally create a new package setting
21888                // object on replace]. However, we can't get the package from the scan
21889                // because the scan modifies live structures and we need to remove the
21890                // old [system] package from the system before a scan can be attempted.
21891                // Once scan is indempotent we can remove this parse and use the package
21892                // object we scanned, prior to adding it to package settings.
21893                final PackageParser pp = new PackageParser();
21894                pp.setSeparateProcesses(mSeparateProcesses);
21895                pp.setDisplayMetrics(mMetrics);
21896                pp.setCallback(mPackageParserCallback);
21897                final PackageParser.Package tmpPkg;
21898                try {
21899                    final int parseFlags = mDefParseFlags
21900                            | PackageParser.PARSE_MUST_BE_APK
21901                            | PackageParser.PARSE_IS_SYSTEM
21902                            | PackageParser.PARSE_IS_SYSTEM_DIR;
21903                    tmpPkg = pp.parsePackage(codePath, parseFlags);
21904                } catch (PackageParserException e) {
21905                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
21906                    return;
21907                }
21908                synchronized (mInstallLock) {
21909                    // Disable the stub and remove any package entries
21910                    removePackageLI(deletedPkg, true);
21911                    synchronized (mPackages) {
21912                        disableSystemPackageLPw(deletedPkg, tmpPkg);
21913                    }
21914                    final PackageParser.Package newPkg;
21915                    try (PackageFreezer freezer =
21916                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
21917                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
21918                                | PackageParser.PARSE_ENFORCE_CODE;
21919                        newPkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
21920                                0 /*currentTime*/, null /*user*/);
21921                        prepareAppDataAfterInstallLIF(newPkg);
21922                        synchronized (mPackages) {
21923                            try {
21924                                updateSharedLibrariesLPr(newPkg, null);
21925                            } catch (PackageManagerException e) {
21926                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
21927                            }
21928                            updatePermissionsLPw(newPkg.packageName, newPkg,
21929                                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
21930                            mSettings.writeLPr();
21931                        }
21932                    } catch (PackageManagerException e) {
21933                        // Whoops! Something went wrong; try to roll back to the stub
21934                        Slog.w(TAG, "Failed to install compressed system package:"
21935                                + pkgSetting.name, e);
21936                        // Remove the failed install
21937                        removeCodePathLI(codePath);
21938
21939                        // Install the system package
21940                        try (PackageFreezer freezer =
21941                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
21942                            synchronized (mPackages) {
21943                                // NOTE: The system package always needs to be enabled; even
21944                                // if it's for a compressed stub. If we don't, installing the
21945                                // system package fails during scan [scanning checks the disabled
21946                                // packages]. We will reverse this later, after we've "installed"
21947                                // the stub.
21948                                // This leaves us in a fragile state; the stub should never be
21949                                // enabled, so, cross your fingers and hope nothing goes wrong
21950                                // until we can disable the package later.
21951                                enableSystemPackageLPw(deletedPkg);
21952                            }
21953                            installPackageFromSystemLIF(new File(deletedPkg.codePath),
21954                                    false /*isPrivileged*/, null /*allUserHandles*/,
21955                                    null /*origUserHandles*/, null /*origPermissionsState*/,
21956                                    true /*writeSettings*/);
21957                        } catch (PackageManagerException pme) {
21958                            Slog.w(TAG, "Failed to restore system package:"
21959                                    + deletedPkg.packageName, pme);
21960                        } finally {
21961                            synchronized (mPackages) {
21962                                mSettings.disableSystemPackageLPw(
21963                                        deletedPkg.packageName, true /*replaced*/);
21964                                mSettings.writeLPr();
21965                            }
21966                        }
21967                        return;
21968                    }
21969                    clearAppDataLIF(newPkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
21970                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21971                    clearAppProfilesLIF(newPkg, UserHandle.USER_ALL);
21972                    mDexManager.notifyPackageUpdated(newPkg.packageName,
21973                            newPkg.baseCodePath, newPkg.splitCodePaths);
21974                }
21975            }
21976            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21977                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
21978                // Don't care about who enables an app.
21979                callingPackage = null;
21980            }
21981            synchronized (mPackages) {
21982                pkgSetting.setEnabled(newState, userId, callingPackage);
21983            }
21984        } else {
21985            synchronized (mPackages) {
21986                // We're dealing with a component level state change
21987                // First, verify that this is a valid class name.
21988                PackageParser.Package pkg = pkgSetting.pkg;
21989                if (pkg == null || !pkg.hasComponentClassName(className)) {
21990                    if (pkg != null &&
21991                            pkg.applicationInfo.targetSdkVersion >=
21992                                    Build.VERSION_CODES.JELLY_BEAN) {
21993                        throw new IllegalArgumentException("Component class " + className
21994                                + " does not exist in " + packageName);
21995                    } else {
21996                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
21997                                + className + " does not exist in " + packageName);
21998                    }
21999                }
22000                switch (newState) {
22001                    case COMPONENT_ENABLED_STATE_ENABLED:
22002                        if (!pkgSetting.enableComponentLPw(className, userId)) {
22003                            return;
22004                        }
22005                        break;
22006                    case COMPONENT_ENABLED_STATE_DISABLED:
22007                        if (!pkgSetting.disableComponentLPw(className, userId)) {
22008                            return;
22009                        }
22010                        break;
22011                    case COMPONENT_ENABLED_STATE_DEFAULT:
22012                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
22013                            return;
22014                        }
22015                        break;
22016                    default:
22017                        Slog.e(TAG, "Invalid new component state: " + newState);
22018                        return;
22019                }
22020            }
22021        }
22022        synchronized (mPackages) {
22023            scheduleWritePackageRestrictionsLocked(userId);
22024            updateSequenceNumberLP(pkgSetting, new int[] { userId });
22025            final long callingId = Binder.clearCallingIdentity();
22026            try {
22027                updateInstantAppInstallerLocked(packageName);
22028            } finally {
22029                Binder.restoreCallingIdentity(callingId);
22030            }
22031            components = mPendingBroadcasts.get(userId, packageName);
22032            final boolean newPackage = components == null;
22033            if (newPackage) {
22034                components = new ArrayList<String>();
22035            }
22036            if (!components.contains(componentName)) {
22037                components.add(componentName);
22038            }
22039            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
22040                sendNow = true;
22041                // Purge entry from pending broadcast list if another one exists already
22042                // since we are sending one right away.
22043                mPendingBroadcasts.remove(userId, packageName);
22044            } else {
22045                if (newPackage) {
22046                    mPendingBroadcasts.put(userId, packageName, components);
22047                }
22048                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
22049                    // Schedule a message
22050                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
22051                }
22052            }
22053        }
22054
22055        long callingId = Binder.clearCallingIdentity();
22056        try {
22057            if (sendNow) {
22058                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
22059                sendPackageChangedBroadcast(packageName,
22060                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
22061            }
22062        } finally {
22063            Binder.restoreCallingIdentity(callingId);
22064        }
22065    }
22066
22067    @Override
22068    public void flushPackageRestrictionsAsUser(int userId) {
22069        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
22070            return;
22071        }
22072        if (!sUserManager.exists(userId)) {
22073            return;
22074        }
22075        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
22076                false /* checkShell */, "flushPackageRestrictions");
22077        synchronized (mPackages) {
22078            mSettings.writePackageRestrictionsLPr(userId);
22079            mDirtyUsers.remove(userId);
22080            if (mDirtyUsers.isEmpty()) {
22081                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
22082            }
22083        }
22084    }
22085
22086    private void sendPackageChangedBroadcast(String packageName,
22087            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
22088        if (DEBUG_INSTALL)
22089            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
22090                    + componentNames);
22091        Bundle extras = new Bundle(4);
22092        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
22093        String nameList[] = new String[componentNames.size()];
22094        componentNames.toArray(nameList);
22095        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
22096        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
22097        extras.putInt(Intent.EXTRA_UID, packageUid);
22098        // If this is not reporting a change of the overall package, then only send it
22099        // to registered receivers.  We don't want to launch a swath of apps for every
22100        // little component state change.
22101        final int flags = !componentNames.contains(packageName)
22102                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
22103        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
22104                new int[] {UserHandle.getUserId(packageUid)});
22105    }
22106
22107    @Override
22108    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
22109        if (!sUserManager.exists(userId)) return;
22110        final int callingUid = Binder.getCallingUid();
22111        if (getInstantAppPackageName(callingUid) != null) {
22112            return;
22113        }
22114        final int permission = mContext.checkCallingOrSelfPermission(
22115                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
22116        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
22117        enforceCrossUserPermission(callingUid, userId,
22118                true /* requireFullPermission */, true /* checkShell */, "stop package");
22119        // writer
22120        synchronized (mPackages) {
22121            final PackageSetting ps = mSettings.mPackages.get(packageName);
22122            if (!filterAppAccessLPr(ps, callingUid, userId)
22123                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
22124                            allowedByPermission, callingUid, userId)) {
22125                scheduleWritePackageRestrictionsLocked(userId);
22126            }
22127        }
22128    }
22129
22130    @Override
22131    public String getInstallerPackageName(String packageName) {
22132        final int callingUid = Binder.getCallingUid();
22133        if (getInstantAppPackageName(callingUid) != null) {
22134            return null;
22135        }
22136        // reader
22137        synchronized (mPackages) {
22138            final PackageSetting ps = mSettings.mPackages.get(packageName);
22139            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
22140                return null;
22141            }
22142            return mSettings.getInstallerPackageNameLPr(packageName);
22143        }
22144    }
22145
22146    public boolean isOrphaned(String packageName) {
22147        // reader
22148        synchronized (mPackages) {
22149            return mSettings.isOrphaned(packageName);
22150        }
22151    }
22152
22153    @Override
22154    public int getApplicationEnabledSetting(String packageName, int userId) {
22155        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
22156        int callingUid = Binder.getCallingUid();
22157        enforceCrossUserPermission(callingUid, userId,
22158                false /* requireFullPermission */, false /* checkShell */, "get enabled");
22159        // reader
22160        synchronized (mPackages) {
22161            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
22162                return COMPONENT_ENABLED_STATE_DISABLED;
22163            }
22164            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
22165        }
22166    }
22167
22168    @Override
22169    public int getComponentEnabledSetting(ComponentName component, int userId) {
22170        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
22171        int callingUid = Binder.getCallingUid();
22172        enforceCrossUserPermission(callingUid, userId,
22173                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
22174        synchronized (mPackages) {
22175            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
22176                    component, TYPE_UNKNOWN, userId)) {
22177                return COMPONENT_ENABLED_STATE_DISABLED;
22178            }
22179            return mSettings.getComponentEnabledSettingLPr(component, userId);
22180        }
22181    }
22182
22183    @Override
22184    public void enterSafeMode() {
22185        enforceSystemOrRoot("Only the system can request entering safe mode");
22186
22187        if (!mSystemReady) {
22188            mSafeMode = true;
22189        }
22190    }
22191
22192    @Override
22193    public void systemReady() {
22194        enforceSystemOrRoot("Only the system can claim the system is ready");
22195
22196        mSystemReady = true;
22197        final ContentResolver resolver = mContext.getContentResolver();
22198        ContentObserver co = new ContentObserver(mHandler) {
22199            @Override
22200            public void onChange(boolean selfChange) {
22201                mEphemeralAppsDisabled =
22202                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
22203                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
22204            }
22205        };
22206        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
22207                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
22208                false, co, UserHandle.USER_SYSTEM);
22209        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
22210                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
22211        co.onChange(true);
22212
22213        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
22214        // disabled after already being started.
22215        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
22216                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
22217
22218        // Read the compatibilty setting when the system is ready.
22219        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
22220                mContext.getContentResolver(),
22221                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
22222        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
22223        if (DEBUG_SETTINGS) {
22224            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
22225        }
22226
22227        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
22228
22229        synchronized (mPackages) {
22230            // Verify that all of the preferred activity components actually
22231            // exist.  It is possible for applications to be updated and at
22232            // that point remove a previously declared activity component that
22233            // had been set as a preferred activity.  We try to clean this up
22234            // the next time we encounter that preferred activity, but it is
22235            // possible for the user flow to never be able to return to that
22236            // situation so here we do a sanity check to make sure we haven't
22237            // left any junk around.
22238            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
22239            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22240                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22241                removed.clear();
22242                for (PreferredActivity pa : pir.filterSet()) {
22243                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
22244                        removed.add(pa);
22245                    }
22246                }
22247                if (removed.size() > 0) {
22248                    for (int r=0; r<removed.size(); r++) {
22249                        PreferredActivity pa = removed.get(r);
22250                        Slog.w(TAG, "Removing dangling preferred activity: "
22251                                + pa.mPref.mComponent);
22252                        pir.removeFilter(pa);
22253                    }
22254                    mSettings.writePackageRestrictionsLPr(
22255                            mSettings.mPreferredActivities.keyAt(i));
22256                }
22257            }
22258
22259            for (int userId : UserManagerService.getInstance().getUserIds()) {
22260                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
22261                    grantPermissionsUserIds = ArrayUtils.appendInt(
22262                            grantPermissionsUserIds, userId);
22263                }
22264            }
22265        }
22266        sUserManager.systemReady();
22267
22268        // If we upgraded grant all default permissions before kicking off.
22269        for (int userId : grantPermissionsUserIds) {
22270            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22271        }
22272
22273        // If we did not grant default permissions, we preload from this the
22274        // default permission exceptions lazily to ensure we don't hit the
22275        // disk on a new user creation.
22276        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
22277            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
22278        }
22279
22280        // Kick off any messages waiting for system ready
22281        if (mPostSystemReadyMessages != null) {
22282            for (Message msg : mPostSystemReadyMessages) {
22283                msg.sendToTarget();
22284            }
22285            mPostSystemReadyMessages = null;
22286        }
22287
22288        // Watch for external volumes that come and go over time
22289        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22290        storage.registerListener(mStorageListener);
22291
22292        mInstallerService.systemReady();
22293        mPackageDexOptimizer.systemReady();
22294
22295        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
22296                StorageManagerInternal.class);
22297        StorageManagerInternal.addExternalStoragePolicy(
22298                new StorageManagerInternal.ExternalStorageMountPolicy() {
22299            @Override
22300            public int getMountMode(int uid, String packageName) {
22301                if (Process.isIsolated(uid)) {
22302                    return Zygote.MOUNT_EXTERNAL_NONE;
22303                }
22304                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
22305                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
22306                }
22307                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
22308                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
22309                }
22310                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
22311                    return Zygote.MOUNT_EXTERNAL_READ;
22312                }
22313                return Zygote.MOUNT_EXTERNAL_WRITE;
22314            }
22315
22316            @Override
22317            public boolean hasExternalStorage(int uid, String packageName) {
22318                return true;
22319            }
22320        });
22321
22322        // Now that we're mostly running, clean up stale users and apps
22323        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
22324        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
22325
22326        if (mPrivappPermissionsViolations != null) {
22327            Slog.wtf(TAG,"Signature|privileged permissions not in "
22328                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
22329            mPrivappPermissionsViolations = null;
22330        }
22331    }
22332
22333    public void waitForAppDataPrepared() {
22334        if (mPrepareAppDataFuture == null) {
22335            return;
22336        }
22337        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
22338        mPrepareAppDataFuture = null;
22339    }
22340
22341    @Override
22342    public boolean isSafeMode() {
22343        // allow instant applications
22344        return mSafeMode;
22345    }
22346
22347    @Override
22348    public boolean hasSystemUidErrors() {
22349        // allow instant applications
22350        return mHasSystemUidErrors;
22351    }
22352
22353    static String arrayToString(int[] array) {
22354        StringBuffer buf = new StringBuffer(128);
22355        buf.append('[');
22356        if (array != null) {
22357            for (int i=0; i<array.length; i++) {
22358                if (i > 0) buf.append(", ");
22359                buf.append(array[i]);
22360            }
22361        }
22362        buf.append(']');
22363        return buf.toString();
22364    }
22365
22366    static class DumpState {
22367        public static final int DUMP_LIBS = 1 << 0;
22368        public static final int DUMP_FEATURES = 1 << 1;
22369        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
22370        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
22371        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
22372        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
22373        public static final int DUMP_PERMISSIONS = 1 << 6;
22374        public static final int DUMP_PACKAGES = 1 << 7;
22375        public static final int DUMP_SHARED_USERS = 1 << 8;
22376        public static final int DUMP_MESSAGES = 1 << 9;
22377        public static final int DUMP_PROVIDERS = 1 << 10;
22378        public static final int DUMP_VERIFIERS = 1 << 11;
22379        public static final int DUMP_PREFERRED = 1 << 12;
22380        public static final int DUMP_PREFERRED_XML = 1 << 13;
22381        public static final int DUMP_KEYSETS = 1 << 14;
22382        public static final int DUMP_VERSION = 1 << 15;
22383        public static final int DUMP_INSTALLS = 1 << 16;
22384        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
22385        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
22386        public static final int DUMP_FROZEN = 1 << 19;
22387        public static final int DUMP_DEXOPT = 1 << 20;
22388        public static final int DUMP_COMPILER_STATS = 1 << 21;
22389        public static final int DUMP_CHANGES = 1 << 22;
22390        public static final int DUMP_VOLUMES = 1 << 23;
22391
22392        public static final int OPTION_SHOW_FILTERS = 1 << 0;
22393
22394        private int mTypes;
22395
22396        private int mOptions;
22397
22398        private boolean mTitlePrinted;
22399
22400        private SharedUserSetting mSharedUser;
22401
22402        public boolean isDumping(int type) {
22403            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
22404                return true;
22405            }
22406
22407            return (mTypes & type) != 0;
22408        }
22409
22410        public void setDump(int type) {
22411            mTypes |= type;
22412        }
22413
22414        public boolean isOptionEnabled(int option) {
22415            return (mOptions & option) != 0;
22416        }
22417
22418        public void setOptionEnabled(int option) {
22419            mOptions |= option;
22420        }
22421
22422        public boolean onTitlePrinted() {
22423            final boolean printed = mTitlePrinted;
22424            mTitlePrinted = true;
22425            return printed;
22426        }
22427
22428        public boolean getTitlePrinted() {
22429            return mTitlePrinted;
22430        }
22431
22432        public void setTitlePrinted(boolean enabled) {
22433            mTitlePrinted = enabled;
22434        }
22435
22436        public SharedUserSetting getSharedUser() {
22437            return mSharedUser;
22438        }
22439
22440        public void setSharedUser(SharedUserSetting user) {
22441            mSharedUser = user;
22442        }
22443    }
22444
22445    @Override
22446    public void onShellCommand(FileDescriptor in, FileDescriptor out,
22447            FileDescriptor err, String[] args, ShellCallback callback,
22448            ResultReceiver resultReceiver) {
22449        (new PackageManagerShellCommand(this)).exec(
22450                this, in, out, err, args, callback, resultReceiver);
22451    }
22452
22453    @Override
22454    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
22455        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
22456
22457        DumpState dumpState = new DumpState();
22458        boolean fullPreferred = false;
22459        boolean checkin = false;
22460
22461        String packageName = null;
22462        ArraySet<String> permissionNames = null;
22463
22464        int opti = 0;
22465        while (opti < args.length) {
22466            String opt = args[opti];
22467            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
22468                break;
22469            }
22470            opti++;
22471
22472            if ("-a".equals(opt)) {
22473                // Right now we only know how to print all.
22474            } else if ("-h".equals(opt)) {
22475                pw.println("Package manager dump options:");
22476                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
22477                pw.println("    --checkin: dump for a checkin");
22478                pw.println("    -f: print details of intent filters");
22479                pw.println("    -h: print this help");
22480                pw.println("  cmd may be one of:");
22481                pw.println("    l[ibraries]: list known shared libraries");
22482                pw.println("    f[eatures]: list device features");
22483                pw.println("    k[eysets]: print known keysets");
22484                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
22485                pw.println("    perm[issions]: dump permissions");
22486                pw.println("    permission [name ...]: dump declaration and use of given permission");
22487                pw.println("    pref[erred]: print preferred package settings");
22488                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
22489                pw.println("    prov[iders]: dump content providers");
22490                pw.println("    p[ackages]: dump installed packages");
22491                pw.println("    s[hared-users]: dump shared user IDs");
22492                pw.println("    m[essages]: print collected runtime messages");
22493                pw.println("    v[erifiers]: print package verifier info");
22494                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
22495                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
22496                pw.println("    version: print database version info");
22497                pw.println("    write: write current settings now");
22498                pw.println("    installs: details about install sessions");
22499                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
22500                pw.println("    dexopt: dump dexopt state");
22501                pw.println("    compiler-stats: dump compiler statistics");
22502                pw.println("    enabled-overlays: dump list of enabled overlay packages");
22503                pw.println("    <package.name>: info about given package");
22504                return;
22505            } else if ("--checkin".equals(opt)) {
22506                checkin = true;
22507            } else if ("-f".equals(opt)) {
22508                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
22509            } else if ("--proto".equals(opt)) {
22510                dumpProto(fd);
22511                return;
22512            } else {
22513                pw.println("Unknown argument: " + opt + "; use -h for help");
22514            }
22515        }
22516
22517        // Is the caller requesting to dump a particular piece of data?
22518        if (opti < args.length) {
22519            String cmd = args[opti];
22520            opti++;
22521            // Is this a package name?
22522            if ("android".equals(cmd) || cmd.contains(".")) {
22523                packageName = cmd;
22524                // When dumping a single package, we always dump all of its
22525                // filter information since the amount of data will be reasonable.
22526                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
22527            } else if ("check-permission".equals(cmd)) {
22528                if (opti >= args.length) {
22529                    pw.println("Error: check-permission missing permission argument");
22530                    return;
22531                }
22532                String perm = args[opti];
22533                opti++;
22534                if (opti >= args.length) {
22535                    pw.println("Error: check-permission missing package argument");
22536                    return;
22537                }
22538
22539                String pkg = args[opti];
22540                opti++;
22541                int user = UserHandle.getUserId(Binder.getCallingUid());
22542                if (opti < args.length) {
22543                    try {
22544                        user = Integer.parseInt(args[opti]);
22545                    } catch (NumberFormatException e) {
22546                        pw.println("Error: check-permission user argument is not a number: "
22547                                + args[opti]);
22548                        return;
22549                    }
22550                }
22551
22552                // Normalize package name to handle renamed packages and static libs
22553                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
22554
22555                pw.println(checkPermission(perm, pkg, user));
22556                return;
22557            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
22558                dumpState.setDump(DumpState.DUMP_LIBS);
22559            } else if ("f".equals(cmd) || "features".equals(cmd)) {
22560                dumpState.setDump(DumpState.DUMP_FEATURES);
22561            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
22562                if (opti >= args.length) {
22563                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
22564                            | DumpState.DUMP_SERVICE_RESOLVERS
22565                            | DumpState.DUMP_RECEIVER_RESOLVERS
22566                            | DumpState.DUMP_CONTENT_RESOLVERS);
22567                } else {
22568                    while (opti < args.length) {
22569                        String name = args[opti];
22570                        if ("a".equals(name) || "activity".equals(name)) {
22571                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
22572                        } else if ("s".equals(name) || "service".equals(name)) {
22573                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
22574                        } else if ("r".equals(name) || "receiver".equals(name)) {
22575                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
22576                        } else if ("c".equals(name) || "content".equals(name)) {
22577                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
22578                        } else {
22579                            pw.println("Error: unknown resolver table type: " + name);
22580                            return;
22581                        }
22582                        opti++;
22583                    }
22584                }
22585            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
22586                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
22587            } else if ("permission".equals(cmd)) {
22588                if (opti >= args.length) {
22589                    pw.println("Error: permission requires permission name");
22590                    return;
22591                }
22592                permissionNames = new ArraySet<>();
22593                while (opti < args.length) {
22594                    permissionNames.add(args[opti]);
22595                    opti++;
22596                }
22597                dumpState.setDump(DumpState.DUMP_PERMISSIONS
22598                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
22599            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
22600                dumpState.setDump(DumpState.DUMP_PREFERRED);
22601            } else if ("preferred-xml".equals(cmd)) {
22602                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
22603                if (opti < args.length && "--full".equals(args[opti])) {
22604                    fullPreferred = true;
22605                    opti++;
22606                }
22607            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
22608                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
22609            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
22610                dumpState.setDump(DumpState.DUMP_PACKAGES);
22611            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
22612                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
22613            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
22614                dumpState.setDump(DumpState.DUMP_PROVIDERS);
22615            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
22616                dumpState.setDump(DumpState.DUMP_MESSAGES);
22617            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
22618                dumpState.setDump(DumpState.DUMP_VERIFIERS);
22619            } else if ("i".equals(cmd) || "ifv".equals(cmd)
22620                    || "intent-filter-verifiers".equals(cmd)) {
22621                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
22622            } else if ("version".equals(cmd)) {
22623                dumpState.setDump(DumpState.DUMP_VERSION);
22624            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
22625                dumpState.setDump(DumpState.DUMP_KEYSETS);
22626            } else if ("installs".equals(cmd)) {
22627                dumpState.setDump(DumpState.DUMP_INSTALLS);
22628            } else if ("frozen".equals(cmd)) {
22629                dumpState.setDump(DumpState.DUMP_FROZEN);
22630            } else if ("volumes".equals(cmd)) {
22631                dumpState.setDump(DumpState.DUMP_VOLUMES);
22632            } else if ("dexopt".equals(cmd)) {
22633                dumpState.setDump(DumpState.DUMP_DEXOPT);
22634            } else if ("compiler-stats".equals(cmd)) {
22635                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
22636            } else if ("changes".equals(cmd)) {
22637                dumpState.setDump(DumpState.DUMP_CHANGES);
22638            } else if ("write".equals(cmd)) {
22639                synchronized (mPackages) {
22640                    mSettings.writeLPr();
22641                    pw.println("Settings written.");
22642                    return;
22643                }
22644            }
22645        }
22646
22647        if (checkin) {
22648            pw.println("vers,1");
22649        }
22650
22651        // reader
22652        synchronized (mPackages) {
22653            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
22654                if (!checkin) {
22655                    if (dumpState.onTitlePrinted())
22656                        pw.println();
22657                    pw.println("Database versions:");
22658                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
22659                }
22660            }
22661
22662            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
22663                if (!checkin) {
22664                    if (dumpState.onTitlePrinted())
22665                        pw.println();
22666                    pw.println("Verifiers:");
22667                    pw.print("  Required: ");
22668                    pw.print(mRequiredVerifierPackage);
22669                    pw.print(" (uid=");
22670                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22671                            UserHandle.USER_SYSTEM));
22672                    pw.println(")");
22673                } else if (mRequiredVerifierPackage != null) {
22674                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
22675                    pw.print(",");
22676                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22677                            UserHandle.USER_SYSTEM));
22678                }
22679            }
22680
22681            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
22682                    packageName == null) {
22683                if (mIntentFilterVerifierComponent != null) {
22684                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22685                    if (!checkin) {
22686                        if (dumpState.onTitlePrinted())
22687                            pw.println();
22688                        pw.println("Intent Filter Verifier:");
22689                        pw.print("  Using: ");
22690                        pw.print(verifierPackageName);
22691                        pw.print(" (uid=");
22692                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22693                                UserHandle.USER_SYSTEM));
22694                        pw.println(")");
22695                    } else if (verifierPackageName != null) {
22696                        pw.print("ifv,"); pw.print(verifierPackageName);
22697                        pw.print(",");
22698                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22699                                UserHandle.USER_SYSTEM));
22700                    }
22701                } else {
22702                    pw.println();
22703                    pw.println("No Intent Filter Verifier available!");
22704                }
22705            }
22706
22707            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
22708                boolean printedHeader = false;
22709                final Iterator<String> it = mSharedLibraries.keySet().iterator();
22710                while (it.hasNext()) {
22711                    String libName = it.next();
22712                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22713                    if (versionedLib == null) {
22714                        continue;
22715                    }
22716                    final int versionCount = versionedLib.size();
22717                    for (int i = 0; i < versionCount; i++) {
22718                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
22719                        if (!checkin) {
22720                            if (!printedHeader) {
22721                                if (dumpState.onTitlePrinted())
22722                                    pw.println();
22723                                pw.println("Libraries:");
22724                                printedHeader = true;
22725                            }
22726                            pw.print("  ");
22727                        } else {
22728                            pw.print("lib,");
22729                        }
22730                        pw.print(libEntry.info.getName());
22731                        if (libEntry.info.isStatic()) {
22732                            pw.print(" version=" + libEntry.info.getVersion());
22733                        }
22734                        if (!checkin) {
22735                            pw.print(" -> ");
22736                        }
22737                        if (libEntry.path != null) {
22738                            pw.print(" (jar) ");
22739                            pw.print(libEntry.path);
22740                        } else {
22741                            pw.print(" (apk) ");
22742                            pw.print(libEntry.apk);
22743                        }
22744                        pw.println();
22745                    }
22746                }
22747            }
22748
22749            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
22750                if (dumpState.onTitlePrinted())
22751                    pw.println();
22752                if (!checkin) {
22753                    pw.println("Features:");
22754                }
22755
22756                synchronized (mAvailableFeatures) {
22757                    for (FeatureInfo feat : mAvailableFeatures.values()) {
22758                        if (checkin) {
22759                            pw.print("feat,");
22760                            pw.print(feat.name);
22761                            pw.print(",");
22762                            pw.println(feat.version);
22763                        } else {
22764                            pw.print("  ");
22765                            pw.print(feat.name);
22766                            if (feat.version > 0) {
22767                                pw.print(" version=");
22768                                pw.print(feat.version);
22769                            }
22770                            pw.println();
22771                        }
22772                    }
22773                }
22774            }
22775
22776            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
22777                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
22778                        : "Activity Resolver Table:", "  ", packageName,
22779                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22780                    dumpState.setTitlePrinted(true);
22781                }
22782            }
22783            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
22784                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
22785                        : "Receiver Resolver Table:", "  ", packageName,
22786                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22787                    dumpState.setTitlePrinted(true);
22788                }
22789            }
22790            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
22791                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
22792                        : "Service Resolver Table:", "  ", packageName,
22793                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22794                    dumpState.setTitlePrinted(true);
22795                }
22796            }
22797            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
22798                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
22799                        : "Provider Resolver Table:", "  ", packageName,
22800                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22801                    dumpState.setTitlePrinted(true);
22802                }
22803            }
22804
22805            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22806                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22807                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22808                    int user = mSettings.mPreferredActivities.keyAt(i);
22809                    if (pir.dump(pw,
22810                            dumpState.getTitlePrinted()
22811                                ? "\nPreferred Activities User " + user + ":"
22812                                : "Preferred Activities User " + user + ":", "  ",
22813                            packageName, true, false)) {
22814                        dumpState.setTitlePrinted(true);
22815                    }
22816                }
22817            }
22818
22819            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22820                pw.flush();
22821                FileOutputStream fout = new FileOutputStream(fd);
22822                BufferedOutputStream str = new BufferedOutputStream(fout);
22823                XmlSerializer serializer = new FastXmlSerializer();
22824                try {
22825                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
22826                    serializer.startDocument(null, true);
22827                    serializer.setFeature(
22828                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22829                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22830                    serializer.endDocument();
22831                    serializer.flush();
22832                } catch (IllegalArgumentException e) {
22833                    pw.println("Failed writing: " + e);
22834                } catch (IllegalStateException e) {
22835                    pw.println("Failed writing: " + e);
22836                } catch (IOException e) {
22837                    pw.println("Failed writing: " + e);
22838                }
22839            }
22840
22841            if (!checkin
22842                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22843                    && packageName == null) {
22844                pw.println();
22845                int count = mSettings.mPackages.size();
22846                if (count == 0) {
22847                    pw.println("No applications!");
22848                    pw.println();
22849                } else {
22850                    final String prefix = "  ";
22851                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22852                    if (allPackageSettings.size() == 0) {
22853                        pw.println("No domain preferred apps!");
22854                        pw.println();
22855                    } else {
22856                        pw.println("App verification status:");
22857                        pw.println();
22858                        count = 0;
22859                        for (PackageSetting ps : allPackageSettings) {
22860                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22861                            if (ivi == null || ivi.getPackageName() == null) continue;
22862                            pw.println(prefix + "Package: " + ivi.getPackageName());
22863                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
22864                            pw.println(prefix + "Status:  " + ivi.getStatusString());
22865                            pw.println();
22866                            count++;
22867                        }
22868                        if (count == 0) {
22869                            pw.println(prefix + "No app verification established.");
22870                            pw.println();
22871                        }
22872                        for (int userId : sUserManager.getUserIds()) {
22873                            pw.println("App linkages for user " + userId + ":");
22874                            pw.println();
22875                            count = 0;
22876                            for (PackageSetting ps : allPackageSettings) {
22877                                final long status = ps.getDomainVerificationStatusForUser(userId);
22878                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22879                                        && !DEBUG_DOMAIN_VERIFICATION) {
22880                                    continue;
22881                                }
22882                                pw.println(prefix + "Package: " + ps.name);
22883                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22884                                String statusStr = IntentFilterVerificationInfo.
22885                                        getStatusStringFromValue(status);
22886                                pw.println(prefix + "Status:  " + statusStr);
22887                                pw.println();
22888                                count++;
22889                            }
22890                            if (count == 0) {
22891                                pw.println(prefix + "No configured app linkages.");
22892                                pw.println();
22893                            }
22894                        }
22895                    }
22896                }
22897            }
22898
22899            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22900                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22901                if (packageName == null && permissionNames == null) {
22902                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22903                        if (iperm == 0) {
22904                            if (dumpState.onTitlePrinted())
22905                                pw.println();
22906                            pw.println("AppOp Permissions:");
22907                        }
22908                        pw.print("  AppOp Permission ");
22909                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
22910                        pw.println(":");
22911                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
22912                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
22913                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
22914                        }
22915                    }
22916                }
22917            }
22918
22919            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
22920                boolean printedSomething = false;
22921                for (PackageParser.Provider p : mProviders.mProviders.values()) {
22922                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22923                        continue;
22924                    }
22925                    if (!printedSomething) {
22926                        if (dumpState.onTitlePrinted())
22927                            pw.println();
22928                        pw.println("Registered ContentProviders:");
22929                        printedSomething = true;
22930                    }
22931                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
22932                    pw.print("    "); pw.println(p.toString());
22933                }
22934                printedSomething = false;
22935                for (Map.Entry<String, PackageParser.Provider> entry :
22936                        mProvidersByAuthority.entrySet()) {
22937                    PackageParser.Provider p = entry.getValue();
22938                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22939                        continue;
22940                    }
22941                    if (!printedSomething) {
22942                        if (dumpState.onTitlePrinted())
22943                            pw.println();
22944                        pw.println("ContentProvider Authorities:");
22945                        printedSomething = true;
22946                    }
22947                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
22948                    pw.print("    "); pw.println(p.toString());
22949                    if (p.info != null && p.info.applicationInfo != null) {
22950                        final String appInfo = p.info.applicationInfo.toString();
22951                        pw.print("      applicationInfo="); pw.println(appInfo);
22952                    }
22953                }
22954            }
22955
22956            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
22957                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
22958            }
22959
22960            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
22961                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
22962            }
22963
22964            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
22965                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
22966            }
22967
22968            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
22969                if (dumpState.onTitlePrinted()) pw.println();
22970                pw.println("Package Changes:");
22971                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
22972                final int K = mChangedPackages.size();
22973                for (int i = 0; i < K; i++) {
22974                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
22975                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
22976                    final int N = changes.size();
22977                    if (N == 0) {
22978                        pw.print("    "); pw.println("No packages changed");
22979                    } else {
22980                        for (int j = 0; j < N; j++) {
22981                            final String pkgName = changes.valueAt(j);
22982                            final int sequenceNumber = changes.keyAt(j);
22983                            pw.print("    ");
22984                            pw.print("seq=");
22985                            pw.print(sequenceNumber);
22986                            pw.print(", package=");
22987                            pw.println(pkgName);
22988                        }
22989                    }
22990                }
22991            }
22992
22993            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
22994                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
22995            }
22996
22997            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
22998                // XXX should handle packageName != null by dumping only install data that
22999                // the given package is involved with.
23000                if (dumpState.onTitlePrinted()) pw.println();
23001
23002                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
23003                ipw.println();
23004                ipw.println("Frozen packages:");
23005                ipw.increaseIndent();
23006                if (mFrozenPackages.size() == 0) {
23007                    ipw.println("(none)");
23008                } else {
23009                    for (int i = 0; i < mFrozenPackages.size(); i++) {
23010                        ipw.println(mFrozenPackages.valueAt(i));
23011                    }
23012                }
23013                ipw.decreaseIndent();
23014            }
23015
23016            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
23017                if (dumpState.onTitlePrinted()) pw.println();
23018
23019                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
23020                ipw.println();
23021                ipw.println("Loaded volumes:");
23022                ipw.increaseIndent();
23023                if (mLoadedVolumes.size() == 0) {
23024                    ipw.println("(none)");
23025                } else {
23026                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
23027                        ipw.println(mLoadedVolumes.valueAt(i));
23028                    }
23029                }
23030                ipw.decreaseIndent();
23031            }
23032
23033            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
23034                if (dumpState.onTitlePrinted()) pw.println();
23035                dumpDexoptStateLPr(pw, packageName);
23036            }
23037
23038            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
23039                if (dumpState.onTitlePrinted()) pw.println();
23040                dumpCompilerStatsLPr(pw, packageName);
23041            }
23042
23043            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
23044                if (dumpState.onTitlePrinted()) pw.println();
23045                mSettings.dumpReadMessagesLPr(pw, dumpState);
23046
23047                pw.println();
23048                pw.println("Package warning messages:");
23049                BufferedReader in = null;
23050                String line = null;
23051                try {
23052                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
23053                    while ((line = in.readLine()) != null) {
23054                        if (line.contains("ignored: updated version")) continue;
23055                        pw.println(line);
23056                    }
23057                } catch (IOException ignored) {
23058                } finally {
23059                    IoUtils.closeQuietly(in);
23060                }
23061            }
23062
23063            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
23064                BufferedReader in = null;
23065                String line = null;
23066                try {
23067                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
23068                    while ((line = in.readLine()) != null) {
23069                        if (line.contains("ignored: updated version")) continue;
23070                        pw.print("msg,");
23071                        pw.println(line);
23072                    }
23073                } catch (IOException ignored) {
23074                } finally {
23075                    IoUtils.closeQuietly(in);
23076                }
23077            }
23078        }
23079
23080        // PackageInstaller should be called outside of mPackages lock
23081        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
23082            // XXX should handle packageName != null by dumping only install data that
23083            // the given package is involved with.
23084            if (dumpState.onTitlePrinted()) pw.println();
23085            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
23086        }
23087    }
23088
23089    private void dumpProto(FileDescriptor fd) {
23090        final ProtoOutputStream proto = new ProtoOutputStream(fd);
23091
23092        synchronized (mPackages) {
23093            final long requiredVerifierPackageToken =
23094                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
23095            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
23096            proto.write(
23097                    PackageServiceDumpProto.PackageShortProto.UID,
23098                    getPackageUid(
23099                            mRequiredVerifierPackage,
23100                            MATCH_DEBUG_TRIAGED_MISSING,
23101                            UserHandle.USER_SYSTEM));
23102            proto.end(requiredVerifierPackageToken);
23103
23104            if (mIntentFilterVerifierComponent != null) {
23105                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
23106                final long verifierPackageToken =
23107                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
23108                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
23109                proto.write(
23110                        PackageServiceDumpProto.PackageShortProto.UID,
23111                        getPackageUid(
23112                                verifierPackageName,
23113                                MATCH_DEBUG_TRIAGED_MISSING,
23114                                UserHandle.USER_SYSTEM));
23115                proto.end(verifierPackageToken);
23116            }
23117
23118            dumpSharedLibrariesProto(proto);
23119            dumpFeaturesProto(proto);
23120            mSettings.dumpPackagesProto(proto);
23121            mSettings.dumpSharedUsersProto(proto);
23122            dumpMessagesProto(proto);
23123        }
23124        proto.flush();
23125    }
23126
23127    private void dumpMessagesProto(ProtoOutputStream proto) {
23128        BufferedReader in = null;
23129        String line = null;
23130        try {
23131            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
23132            while ((line = in.readLine()) != null) {
23133                if (line.contains("ignored: updated version")) continue;
23134                proto.write(PackageServiceDumpProto.MESSAGES, line);
23135            }
23136        } catch (IOException ignored) {
23137        } finally {
23138            IoUtils.closeQuietly(in);
23139        }
23140    }
23141
23142    private void dumpFeaturesProto(ProtoOutputStream proto) {
23143        synchronized (mAvailableFeatures) {
23144            final int count = mAvailableFeatures.size();
23145            for (int i = 0; i < count; i++) {
23146                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
23147                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
23148                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
23149                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
23150                proto.end(featureToken);
23151            }
23152        }
23153    }
23154
23155    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
23156        final int count = mSharedLibraries.size();
23157        for (int i = 0; i < count; i++) {
23158            final String libName = mSharedLibraries.keyAt(i);
23159            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
23160            if (versionedLib == null) {
23161                continue;
23162            }
23163            final int versionCount = versionedLib.size();
23164            for (int j = 0; j < versionCount; j++) {
23165                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
23166                final long sharedLibraryToken =
23167                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
23168                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
23169                final boolean isJar = (libEntry.path != null);
23170                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
23171                if (isJar) {
23172                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
23173                } else {
23174                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
23175                }
23176                proto.end(sharedLibraryToken);
23177            }
23178        }
23179    }
23180
23181    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
23182        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
23183        ipw.println();
23184        ipw.println("Dexopt state:");
23185        ipw.increaseIndent();
23186        Collection<PackageParser.Package> packages = null;
23187        if (packageName != null) {
23188            PackageParser.Package targetPackage = mPackages.get(packageName);
23189            if (targetPackage != null) {
23190                packages = Collections.singletonList(targetPackage);
23191            } else {
23192                ipw.println("Unable to find package: " + packageName);
23193                return;
23194            }
23195        } else {
23196            packages = mPackages.values();
23197        }
23198
23199        for (PackageParser.Package pkg : packages) {
23200            ipw.println("[" + pkg.packageName + "]");
23201            ipw.increaseIndent();
23202            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
23203                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
23204            ipw.decreaseIndent();
23205        }
23206    }
23207
23208    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
23209        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
23210        ipw.println();
23211        ipw.println("Compiler stats:");
23212        ipw.increaseIndent();
23213        Collection<PackageParser.Package> packages = null;
23214        if (packageName != null) {
23215            PackageParser.Package targetPackage = mPackages.get(packageName);
23216            if (targetPackage != null) {
23217                packages = Collections.singletonList(targetPackage);
23218            } else {
23219                ipw.println("Unable to find package: " + packageName);
23220                return;
23221            }
23222        } else {
23223            packages = mPackages.values();
23224        }
23225
23226        for (PackageParser.Package pkg : packages) {
23227            ipw.println("[" + pkg.packageName + "]");
23228            ipw.increaseIndent();
23229
23230            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
23231            if (stats == null) {
23232                ipw.println("(No recorded stats)");
23233            } else {
23234                stats.dump(ipw);
23235            }
23236            ipw.decreaseIndent();
23237        }
23238    }
23239
23240    private String dumpDomainString(String packageName) {
23241        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
23242                .getList();
23243        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
23244
23245        ArraySet<String> result = new ArraySet<>();
23246        if (iviList.size() > 0) {
23247            for (IntentFilterVerificationInfo ivi : iviList) {
23248                for (String host : ivi.getDomains()) {
23249                    result.add(host);
23250                }
23251            }
23252        }
23253        if (filters != null && filters.size() > 0) {
23254            for (IntentFilter filter : filters) {
23255                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
23256                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
23257                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
23258                    result.addAll(filter.getHostsList());
23259                }
23260            }
23261        }
23262
23263        StringBuilder sb = new StringBuilder(result.size() * 16);
23264        for (String domain : result) {
23265            if (sb.length() > 0) sb.append(" ");
23266            sb.append(domain);
23267        }
23268        return sb.toString();
23269    }
23270
23271    // ------- apps on sdcard specific code -------
23272    static final boolean DEBUG_SD_INSTALL = false;
23273
23274    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
23275
23276    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
23277
23278    private boolean mMediaMounted = false;
23279
23280    static String getEncryptKey() {
23281        try {
23282            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
23283                    SD_ENCRYPTION_KEYSTORE_NAME);
23284            if (sdEncKey == null) {
23285                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
23286                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
23287                if (sdEncKey == null) {
23288                    Slog.e(TAG, "Failed to create encryption keys");
23289                    return null;
23290                }
23291            }
23292            return sdEncKey;
23293        } catch (NoSuchAlgorithmException nsae) {
23294            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
23295            return null;
23296        } catch (IOException ioe) {
23297            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
23298            return null;
23299        }
23300    }
23301
23302    /*
23303     * Update media status on PackageManager.
23304     */
23305    @Override
23306    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
23307        enforceSystemOrRoot("Media status can only be updated by the system");
23308        // reader; this apparently protects mMediaMounted, but should probably
23309        // be a different lock in that case.
23310        synchronized (mPackages) {
23311            Log.i(TAG, "Updating external media status from "
23312                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
23313                    + (mediaStatus ? "mounted" : "unmounted"));
23314            if (DEBUG_SD_INSTALL)
23315                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
23316                        + ", mMediaMounted=" + mMediaMounted);
23317            if (mediaStatus == mMediaMounted) {
23318                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
23319                        : 0, -1);
23320                mHandler.sendMessage(msg);
23321                return;
23322            }
23323            mMediaMounted = mediaStatus;
23324        }
23325        // Queue up an async operation since the package installation may take a
23326        // little while.
23327        mHandler.post(new Runnable() {
23328            public void run() {
23329                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
23330            }
23331        });
23332    }
23333
23334    /**
23335     * Called by StorageManagerService when the initial ASECs to scan are available.
23336     * Should block until all the ASEC containers are finished being scanned.
23337     */
23338    public void scanAvailableAsecs() {
23339        updateExternalMediaStatusInner(true, false, false);
23340    }
23341
23342    /*
23343     * Collect information of applications on external media, map them against
23344     * existing containers and update information based on current mount status.
23345     * Please note that we always have to report status if reportStatus has been
23346     * set to true especially when unloading packages.
23347     */
23348    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
23349            boolean externalStorage) {
23350        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
23351        int[] uidArr = EmptyArray.INT;
23352
23353        final String[] list = PackageHelper.getSecureContainerList();
23354        if (ArrayUtils.isEmpty(list)) {
23355            Log.i(TAG, "No secure containers found");
23356        } else {
23357            // Process list of secure containers and categorize them
23358            // as active or stale based on their package internal state.
23359
23360            // reader
23361            synchronized (mPackages) {
23362                for (String cid : list) {
23363                    // Leave stages untouched for now; installer service owns them
23364                    if (PackageInstallerService.isStageName(cid)) continue;
23365
23366                    if (DEBUG_SD_INSTALL)
23367                        Log.i(TAG, "Processing container " + cid);
23368                    String pkgName = getAsecPackageName(cid);
23369                    if (pkgName == null) {
23370                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
23371                        continue;
23372                    }
23373                    if (DEBUG_SD_INSTALL)
23374                        Log.i(TAG, "Looking for pkg : " + pkgName);
23375
23376                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
23377                    if (ps == null) {
23378                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
23379                        continue;
23380                    }
23381
23382                    /*
23383                     * Skip packages that are not external if we're unmounting
23384                     * external storage.
23385                     */
23386                    if (externalStorage && !isMounted && !isExternal(ps)) {
23387                        continue;
23388                    }
23389
23390                    final AsecInstallArgs args = new AsecInstallArgs(cid,
23391                            getAppDexInstructionSets(ps), ps.isForwardLocked());
23392                    // The package status is changed only if the code path
23393                    // matches between settings and the container id.
23394                    if (ps.codePathString != null
23395                            && ps.codePathString.startsWith(args.getCodePath())) {
23396                        if (DEBUG_SD_INSTALL) {
23397                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
23398                                    + " at code path: " + ps.codePathString);
23399                        }
23400
23401                        // We do have a valid package installed on sdcard
23402                        processCids.put(args, ps.codePathString);
23403                        final int uid = ps.appId;
23404                        if (uid != -1) {
23405                            uidArr = ArrayUtils.appendInt(uidArr, uid);
23406                        }
23407                    } else {
23408                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
23409                                + ps.codePathString);
23410                    }
23411                }
23412            }
23413
23414            Arrays.sort(uidArr);
23415        }
23416
23417        // Process packages with valid entries.
23418        if (isMounted) {
23419            if (DEBUG_SD_INSTALL)
23420                Log.i(TAG, "Loading packages");
23421            loadMediaPackages(processCids, uidArr, externalStorage);
23422            startCleaningPackages();
23423            mInstallerService.onSecureContainersAvailable();
23424        } else {
23425            if (DEBUG_SD_INSTALL)
23426                Log.i(TAG, "Unloading packages");
23427            unloadMediaPackages(processCids, uidArr, reportStatus);
23428        }
23429    }
23430
23431    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23432            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
23433        final int size = infos.size();
23434        final String[] packageNames = new String[size];
23435        final int[] packageUids = new int[size];
23436        for (int i = 0; i < size; i++) {
23437            final ApplicationInfo info = infos.get(i);
23438            packageNames[i] = info.packageName;
23439            packageUids[i] = info.uid;
23440        }
23441        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
23442                finishedReceiver);
23443    }
23444
23445    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23446            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
23447        sendResourcesChangedBroadcast(mediaStatus, replacing,
23448                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
23449    }
23450
23451    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23452            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
23453        int size = pkgList.length;
23454        if (size > 0) {
23455            // Send broadcasts here
23456            Bundle extras = new Bundle();
23457            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
23458            if (uidArr != null) {
23459                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
23460            }
23461            if (replacing) {
23462                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
23463            }
23464            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
23465                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
23466            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
23467        }
23468    }
23469
23470   /*
23471     * Look at potentially valid container ids from processCids If package
23472     * information doesn't match the one on record or package scanning fails,
23473     * the cid is added to list of removeCids. We currently don't delete stale
23474     * containers.
23475     */
23476    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
23477            boolean externalStorage) {
23478        ArrayList<String> pkgList = new ArrayList<String>();
23479        Set<AsecInstallArgs> keys = processCids.keySet();
23480
23481        for (AsecInstallArgs args : keys) {
23482            String codePath = processCids.get(args);
23483            if (DEBUG_SD_INSTALL)
23484                Log.i(TAG, "Loading container : " + args.cid);
23485            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
23486            try {
23487                // Make sure there are no container errors first.
23488                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
23489                    Slog.e(TAG, "Failed to mount cid : " + args.cid
23490                            + " when installing from sdcard");
23491                    continue;
23492                }
23493                // Check code path here.
23494                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
23495                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
23496                            + " does not match one in settings " + codePath);
23497                    continue;
23498                }
23499                // Parse package
23500                int parseFlags = mDefParseFlags;
23501                if (args.isExternalAsec()) {
23502                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
23503                }
23504                if (args.isFwdLocked()) {
23505                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
23506                }
23507
23508                synchronized (mInstallLock) {
23509                    PackageParser.Package pkg = null;
23510                    try {
23511                        // Sadly we don't know the package name yet to freeze it
23512                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
23513                                SCAN_IGNORE_FROZEN, 0, null);
23514                    } catch (PackageManagerException e) {
23515                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
23516                    }
23517                    // Scan the package
23518                    if (pkg != null) {
23519                        /*
23520                         * TODO why is the lock being held? doPostInstall is
23521                         * called in other places without the lock. This needs
23522                         * to be straightened out.
23523                         */
23524                        // writer
23525                        synchronized (mPackages) {
23526                            retCode = PackageManager.INSTALL_SUCCEEDED;
23527                            pkgList.add(pkg.packageName);
23528                            // Post process args
23529                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
23530                                    pkg.applicationInfo.uid);
23531                        }
23532                    } else {
23533                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
23534                    }
23535                }
23536
23537            } finally {
23538                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
23539                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
23540                }
23541            }
23542        }
23543        // writer
23544        synchronized (mPackages) {
23545            // If the platform SDK has changed since the last time we booted,
23546            // we need to re-grant app permission to catch any new ones that
23547            // appear. This is really a hack, and means that apps can in some
23548            // cases get permissions that the user didn't initially explicitly
23549            // allow... it would be nice to have some better way to handle
23550            // this situation.
23551            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
23552                    : mSettings.getInternalVersion();
23553            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
23554                    : StorageManager.UUID_PRIVATE_INTERNAL;
23555
23556            int updateFlags = UPDATE_PERMISSIONS_ALL;
23557            if (ver.sdkVersion != mSdkVersion) {
23558                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23559                        + mSdkVersion + "; regranting permissions for external");
23560                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23561            }
23562            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23563
23564            // Yay, everything is now upgraded
23565            ver.forceCurrent();
23566
23567            // can downgrade to reader
23568            // Persist settings
23569            mSettings.writeLPr();
23570        }
23571        // Send a broadcast to let everyone know we are done processing
23572        if (pkgList.size() > 0) {
23573            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
23574        }
23575    }
23576
23577   /*
23578     * Utility method to unload a list of specified containers
23579     */
23580    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
23581        // Just unmount all valid containers.
23582        for (AsecInstallArgs arg : cidArgs) {
23583            synchronized (mInstallLock) {
23584                arg.doPostDeleteLI(false);
23585           }
23586       }
23587   }
23588
23589    /*
23590     * Unload packages mounted on external media. This involves deleting package
23591     * data from internal structures, sending broadcasts about disabled packages,
23592     * gc'ing to free up references, unmounting all secure containers
23593     * corresponding to packages on external media, and posting a
23594     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
23595     * that we always have to post this message if status has been requested no
23596     * matter what.
23597     */
23598    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
23599            final boolean reportStatus) {
23600        if (DEBUG_SD_INSTALL)
23601            Log.i(TAG, "unloading media packages");
23602        ArrayList<String> pkgList = new ArrayList<String>();
23603        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
23604        final Set<AsecInstallArgs> keys = processCids.keySet();
23605        for (AsecInstallArgs args : keys) {
23606            String pkgName = args.getPackageName();
23607            if (DEBUG_SD_INSTALL)
23608                Log.i(TAG, "Trying to unload pkg : " + pkgName);
23609            // Delete package internally
23610            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23611            synchronized (mInstallLock) {
23612                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23613                final boolean res;
23614                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
23615                        "unloadMediaPackages")) {
23616                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
23617                            null);
23618                }
23619                if (res) {
23620                    pkgList.add(pkgName);
23621                } else {
23622                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
23623                    failedList.add(args);
23624                }
23625            }
23626        }
23627
23628        // reader
23629        synchronized (mPackages) {
23630            // We didn't update the settings after removing each package;
23631            // write them now for all packages.
23632            mSettings.writeLPr();
23633        }
23634
23635        // We have to absolutely send UPDATED_MEDIA_STATUS only
23636        // after confirming that all the receivers processed the ordered
23637        // broadcast when packages get disabled, force a gc to clean things up.
23638        // and unload all the containers.
23639        if (pkgList.size() > 0) {
23640            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
23641                    new IIntentReceiver.Stub() {
23642                public void performReceive(Intent intent, int resultCode, String data,
23643                        Bundle extras, boolean ordered, boolean sticky,
23644                        int sendingUser) throws RemoteException {
23645                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
23646                            reportStatus ? 1 : 0, 1, keys);
23647                    mHandler.sendMessage(msg);
23648                }
23649            });
23650        } else {
23651            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
23652                    keys);
23653            mHandler.sendMessage(msg);
23654        }
23655    }
23656
23657    private void loadPrivatePackages(final VolumeInfo vol) {
23658        mHandler.post(new Runnable() {
23659            @Override
23660            public void run() {
23661                loadPrivatePackagesInner(vol);
23662            }
23663        });
23664    }
23665
23666    private void loadPrivatePackagesInner(VolumeInfo vol) {
23667        final String volumeUuid = vol.fsUuid;
23668        if (TextUtils.isEmpty(volumeUuid)) {
23669            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
23670            return;
23671        }
23672
23673        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
23674        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
23675        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
23676
23677        final VersionInfo ver;
23678        final List<PackageSetting> packages;
23679        synchronized (mPackages) {
23680            ver = mSettings.findOrCreateVersion(volumeUuid);
23681            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23682        }
23683
23684        for (PackageSetting ps : packages) {
23685            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
23686            synchronized (mInstallLock) {
23687                final PackageParser.Package pkg;
23688                try {
23689                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
23690                    loaded.add(pkg.applicationInfo);
23691
23692                } catch (PackageManagerException e) {
23693                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
23694                }
23695
23696                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
23697                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
23698                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
23699                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
23700                }
23701            }
23702        }
23703
23704        // Reconcile app data for all started/unlocked users
23705        final StorageManager sm = mContext.getSystemService(StorageManager.class);
23706        final UserManager um = mContext.getSystemService(UserManager.class);
23707        UserManagerInternal umInternal = getUserManagerInternal();
23708        for (UserInfo user : um.getUsers()) {
23709            final int flags;
23710            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23711                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23712            } else if (umInternal.isUserRunning(user.id)) {
23713                flags = StorageManager.FLAG_STORAGE_DE;
23714            } else {
23715                continue;
23716            }
23717
23718            try {
23719                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
23720                synchronized (mInstallLock) {
23721                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
23722                }
23723            } catch (IllegalStateException e) {
23724                // Device was probably ejected, and we'll process that event momentarily
23725                Slog.w(TAG, "Failed to prepare storage: " + e);
23726            }
23727        }
23728
23729        synchronized (mPackages) {
23730            int updateFlags = UPDATE_PERMISSIONS_ALL;
23731            if (ver.sdkVersion != mSdkVersion) {
23732                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23733                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
23734                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23735            }
23736            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23737
23738            // Yay, everything is now upgraded
23739            ver.forceCurrent();
23740
23741            mSettings.writeLPr();
23742        }
23743
23744        for (PackageFreezer freezer : freezers) {
23745            freezer.close();
23746        }
23747
23748        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
23749        sendResourcesChangedBroadcast(true, false, loaded, null);
23750        mLoadedVolumes.add(vol.getId());
23751    }
23752
23753    private void unloadPrivatePackages(final VolumeInfo vol) {
23754        mHandler.post(new Runnable() {
23755            @Override
23756            public void run() {
23757                unloadPrivatePackagesInner(vol);
23758            }
23759        });
23760    }
23761
23762    private void unloadPrivatePackagesInner(VolumeInfo vol) {
23763        final String volumeUuid = vol.fsUuid;
23764        if (TextUtils.isEmpty(volumeUuid)) {
23765            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
23766            return;
23767        }
23768
23769        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
23770        synchronized (mInstallLock) {
23771        synchronized (mPackages) {
23772            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
23773            for (PackageSetting ps : packages) {
23774                if (ps.pkg == null) continue;
23775
23776                final ApplicationInfo info = ps.pkg.applicationInfo;
23777                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23778                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23779
23780                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
23781                        "unloadPrivatePackagesInner")) {
23782                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
23783                            false, null)) {
23784                        unloaded.add(info);
23785                    } else {
23786                        Slog.w(TAG, "Failed to unload " + ps.codePath);
23787                    }
23788                }
23789
23790                // Try very hard to release any references to this package
23791                // so we don't risk the system server being killed due to
23792                // open FDs
23793                AttributeCache.instance().removePackage(ps.name);
23794            }
23795
23796            mSettings.writeLPr();
23797        }
23798        }
23799
23800        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
23801        sendResourcesChangedBroadcast(false, false, unloaded, null);
23802        mLoadedVolumes.remove(vol.getId());
23803
23804        // Try very hard to release any references to this path so we don't risk
23805        // the system server being killed due to open FDs
23806        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
23807
23808        for (int i = 0; i < 3; i++) {
23809            System.gc();
23810            System.runFinalization();
23811        }
23812    }
23813
23814    private void assertPackageKnown(String volumeUuid, String packageName)
23815            throws PackageManagerException {
23816        synchronized (mPackages) {
23817            // Normalize package name to handle renamed packages
23818            packageName = normalizePackageNameLPr(packageName);
23819
23820            final PackageSetting ps = mSettings.mPackages.get(packageName);
23821            if (ps == null) {
23822                throw new PackageManagerException("Package " + packageName + " is unknown");
23823            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23824                throw new PackageManagerException(
23825                        "Package " + packageName + " found on unknown volume " + volumeUuid
23826                                + "; expected volume " + ps.volumeUuid);
23827            }
23828        }
23829    }
23830
23831    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23832            throws PackageManagerException {
23833        synchronized (mPackages) {
23834            // Normalize package name to handle renamed packages
23835            packageName = normalizePackageNameLPr(packageName);
23836
23837            final PackageSetting ps = mSettings.mPackages.get(packageName);
23838            if (ps == null) {
23839                throw new PackageManagerException("Package " + packageName + " is unknown");
23840            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23841                throw new PackageManagerException(
23842                        "Package " + packageName + " found on unknown volume " + volumeUuid
23843                                + "; expected volume " + ps.volumeUuid);
23844            } else if (!ps.getInstalled(userId)) {
23845                throw new PackageManagerException(
23846                        "Package " + packageName + " not installed for user " + userId);
23847            }
23848        }
23849    }
23850
23851    private List<String> collectAbsoluteCodePaths() {
23852        synchronized (mPackages) {
23853            List<String> codePaths = new ArrayList<>();
23854            final int packageCount = mSettings.mPackages.size();
23855            for (int i = 0; i < packageCount; i++) {
23856                final PackageSetting ps = mSettings.mPackages.valueAt(i);
23857                codePaths.add(ps.codePath.getAbsolutePath());
23858            }
23859            return codePaths;
23860        }
23861    }
23862
23863    /**
23864     * Examine all apps present on given mounted volume, and destroy apps that
23865     * aren't expected, either due to uninstallation or reinstallation on
23866     * another volume.
23867     */
23868    private void reconcileApps(String volumeUuid) {
23869        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
23870        List<File> filesToDelete = null;
23871
23872        final File[] files = FileUtils.listFilesOrEmpty(
23873                Environment.getDataAppDirectory(volumeUuid));
23874        for (File file : files) {
23875            final boolean isPackage = (isApkFile(file) || file.isDirectory())
23876                    && !PackageInstallerService.isStageName(file.getName());
23877            if (!isPackage) {
23878                // Ignore entries which are not packages
23879                continue;
23880            }
23881
23882            String absolutePath = file.getAbsolutePath();
23883
23884            boolean pathValid = false;
23885            final int absoluteCodePathCount = absoluteCodePaths.size();
23886            for (int i = 0; i < absoluteCodePathCount; i++) {
23887                String absoluteCodePath = absoluteCodePaths.get(i);
23888                if (absolutePath.startsWith(absoluteCodePath)) {
23889                    pathValid = true;
23890                    break;
23891                }
23892            }
23893
23894            if (!pathValid) {
23895                if (filesToDelete == null) {
23896                    filesToDelete = new ArrayList<>();
23897                }
23898                filesToDelete.add(file);
23899            }
23900        }
23901
23902        if (filesToDelete != null) {
23903            final int fileToDeleteCount = filesToDelete.size();
23904            for (int i = 0; i < fileToDeleteCount; i++) {
23905                File fileToDelete = filesToDelete.get(i);
23906                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23907                synchronized (mInstallLock) {
23908                    removeCodePathLI(fileToDelete);
23909                }
23910            }
23911        }
23912    }
23913
23914    /**
23915     * Reconcile all app data for the given user.
23916     * <p>
23917     * Verifies that directories exist and that ownership and labeling is
23918     * correct for all installed apps on all mounted volumes.
23919     */
23920    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
23921        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23922        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
23923            final String volumeUuid = vol.getFsUuid();
23924            synchronized (mInstallLock) {
23925                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
23926            }
23927        }
23928    }
23929
23930    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23931            boolean migrateAppData) {
23932        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
23933    }
23934
23935    /**
23936     * Reconcile all app data on given mounted volume.
23937     * <p>
23938     * Destroys app data that isn't expected, either due to uninstallation or
23939     * reinstallation on another volume.
23940     * <p>
23941     * Verifies that directories exist and that ownership and labeling is
23942     * correct for all installed apps.
23943     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
23944     */
23945    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23946            boolean migrateAppData, boolean onlyCoreApps) {
23947        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
23948                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
23949        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
23950
23951        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
23952        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
23953
23954        // First look for stale data that doesn't belong, and check if things
23955        // have changed since we did our last restorecon
23956        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23957            if (StorageManager.isFileEncryptedNativeOrEmulated()
23958                    && !StorageManager.isUserKeyUnlocked(userId)) {
23959                throw new RuntimeException(
23960                        "Yikes, someone asked us to reconcile CE storage while " + userId
23961                                + " was still locked; this would have caused massive data loss!");
23962            }
23963
23964            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
23965            for (File file : files) {
23966                final String packageName = file.getName();
23967                try {
23968                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23969                } catch (PackageManagerException e) {
23970                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23971                    try {
23972                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23973                                StorageManager.FLAG_STORAGE_CE, 0);
23974                    } catch (InstallerException e2) {
23975                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23976                    }
23977                }
23978            }
23979        }
23980        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
23981            final File[] files = FileUtils.listFilesOrEmpty(deDir);
23982            for (File file : files) {
23983                final String packageName = file.getName();
23984                try {
23985                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23986                } catch (PackageManagerException e) {
23987                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23988                    try {
23989                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23990                                StorageManager.FLAG_STORAGE_DE, 0);
23991                    } catch (InstallerException e2) {
23992                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23993                    }
23994                }
23995            }
23996        }
23997
23998        // Ensure that data directories are ready to roll for all packages
23999        // installed for this volume and user
24000        final List<PackageSetting> packages;
24001        synchronized (mPackages) {
24002            packages = mSettings.getVolumePackagesLPr(volumeUuid);
24003        }
24004        int preparedCount = 0;
24005        for (PackageSetting ps : packages) {
24006            final String packageName = ps.name;
24007            if (ps.pkg == null) {
24008                Slog.w(TAG, "Odd, missing scanned package " + packageName);
24009                // TODO: might be due to legacy ASEC apps; we should circle back
24010                // and reconcile again once they're scanned
24011                continue;
24012            }
24013            // Skip non-core apps if requested
24014            if (onlyCoreApps && !ps.pkg.coreApp) {
24015                result.add(packageName);
24016                continue;
24017            }
24018
24019            if (ps.getInstalled(userId)) {
24020                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
24021                preparedCount++;
24022            }
24023        }
24024
24025        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
24026        return result;
24027    }
24028
24029    /**
24030     * Prepare app data for the given app just after it was installed or
24031     * upgraded. This method carefully only touches users that it's installed
24032     * for, and it forces a restorecon to handle any seinfo changes.
24033     * <p>
24034     * Verifies that directories exist and that ownership and labeling is
24035     * correct for all installed apps. If there is an ownership mismatch, it
24036     * will try recovering system apps by wiping data; third-party app data is
24037     * left intact.
24038     * <p>
24039     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
24040     */
24041    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
24042        final PackageSetting ps;
24043        synchronized (mPackages) {
24044            ps = mSettings.mPackages.get(pkg.packageName);
24045            mSettings.writeKernelMappingLPr(ps);
24046        }
24047
24048        final UserManager um = mContext.getSystemService(UserManager.class);
24049        UserManagerInternal umInternal = getUserManagerInternal();
24050        for (UserInfo user : um.getUsers()) {
24051            final int flags;
24052            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
24053                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
24054            } else if (umInternal.isUserRunning(user.id)) {
24055                flags = StorageManager.FLAG_STORAGE_DE;
24056            } else {
24057                continue;
24058            }
24059
24060            if (ps.getInstalled(user.id)) {
24061                // TODO: when user data is locked, mark that we're still dirty
24062                prepareAppDataLIF(pkg, user.id, flags);
24063            }
24064        }
24065    }
24066
24067    /**
24068     * Prepare app data for the given app.
24069     * <p>
24070     * Verifies that directories exist and that ownership and labeling is
24071     * correct for all installed apps. If there is an ownership mismatch, this
24072     * will try recovering system apps by wiping data; third-party app data is
24073     * left intact.
24074     */
24075    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
24076        if (pkg == null) {
24077            Slog.wtf(TAG, "Package was null!", new Throwable());
24078            return;
24079        }
24080        prepareAppDataLeafLIF(pkg, userId, flags);
24081        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
24082        for (int i = 0; i < childCount; i++) {
24083            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
24084        }
24085    }
24086
24087    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
24088            boolean maybeMigrateAppData) {
24089        prepareAppDataLIF(pkg, userId, flags);
24090
24091        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
24092            // We may have just shuffled around app data directories, so
24093            // prepare them one more time
24094            prepareAppDataLIF(pkg, userId, flags);
24095        }
24096    }
24097
24098    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
24099        if (DEBUG_APP_DATA) {
24100            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
24101                    + Integer.toHexString(flags));
24102        }
24103
24104        final String volumeUuid = pkg.volumeUuid;
24105        final String packageName = pkg.packageName;
24106        final ApplicationInfo app = pkg.applicationInfo;
24107        final int appId = UserHandle.getAppId(app.uid);
24108
24109        Preconditions.checkNotNull(app.seInfo);
24110
24111        long ceDataInode = -1;
24112        try {
24113            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
24114                    appId, app.seInfo, app.targetSdkVersion);
24115        } catch (InstallerException e) {
24116            if (app.isSystemApp()) {
24117                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
24118                        + ", but trying to recover: " + e);
24119                destroyAppDataLeafLIF(pkg, userId, flags);
24120                try {
24121                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
24122                            appId, app.seInfo, app.targetSdkVersion);
24123                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
24124                } catch (InstallerException e2) {
24125                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
24126                }
24127            } else {
24128                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
24129            }
24130        }
24131
24132        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
24133            // TODO: mark this structure as dirty so we persist it!
24134            synchronized (mPackages) {
24135                final PackageSetting ps = mSettings.mPackages.get(packageName);
24136                if (ps != null) {
24137                    ps.setCeDataInode(ceDataInode, userId);
24138                }
24139            }
24140        }
24141
24142        prepareAppDataContentsLeafLIF(pkg, userId, flags);
24143    }
24144
24145    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
24146        if (pkg == null) {
24147            Slog.wtf(TAG, "Package was null!", new Throwable());
24148            return;
24149        }
24150        prepareAppDataContentsLeafLIF(pkg, userId, flags);
24151        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
24152        for (int i = 0; i < childCount; i++) {
24153            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
24154        }
24155    }
24156
24157    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
24158        final String volumeUuid = pkg.volumeUuid;
24159        final String packageName = pkg.packageName;
24160        final ApplicationInfo app = pkg.applicationInfo;
24161
24162        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
24163            // Create a native library symlink only if we have native libraries
24164            // and if the native libraries are 32 bit libraries. We do not provide
24165            // this symlink for 64 bit libraries.
24166            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
24167                final String nativeLibPath = app.nativeLibraryDir;
24168                try {
24169                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
24170                            nativeLibPath, userId);
24171                } catch (InstallerException e) {
24172                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
24173                }
24174            }
24175        }
24176    }
24177
24178    /**
24179     * For system apps on non-FBE devices, this method migrates any existing
24180     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
24181     * requested by the app.
24182     */
24183    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
24184        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
24185                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
24186            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
24187                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
24188            try {
24189                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
24190                        storageTarget);
24191            } catch (InstallerException e) {
24192                logCriticalInfo(Log.WARN,
24193                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
24194            }
24195            return true;
24196        } else {
24197            return false;
24198        }
24199    }
24200
24201    public PackageFreezer freezePackage(String packageName, String killReason) {
24202        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
24203    }
24204
24205    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
24206        return new PackageFreezer(packageName, userId, killReason);
24207    }
24208
24209    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
24210            String killReason) {
24211        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
24212    }
24213
24214    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
24215            String killReason) {
24216        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
24217            return new PackageFreezer();
24218        } else {
24219            return freezePackage(packageName, userId, killReason);
24220        }
24221    }
24222
24223    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
24224            String killReason) {
24225        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
24226    }
24227
24228    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
24229            String killReason) {
24230        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
24231            return new PackageFreezer();
24232        } else {
24233            return freezePackage(packageName, userId, killReason);
24234        }
24235    }
24236
24237    /**
24238     * Class that freezes and kills the given package upon creation, and
24239     * unfreezes it upon closing. This is typically used when doing surgery on
24240     * app code/data to prevent the app from running while you're working.
24241     */
24242    private class PackageFreezer implements AutoCloseable {
24243        private final String mPackageName;
24244        private final PackageFreezer[] mChildren;
24245
24246        private final boolean mWeFroze;
24247
24248        private final AtomicBoolean mClosed = new AtomicBoolean();
24249        private final CloseGuard mCloseGuard = CloseGuard.get();
24250
24251        /**
24252         * Create and return a stub freezer that doesn't actually do anything,
24253         * typically used when someone requested
24254         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
24255         * {@link PackageManager#DELETE_DONT_KILL_APP}.
24256         */
24257        public PackageFreezer() {
24258            mPackageName = null;
24259            mChildren = null;
24260            mWeFroze = false;
24261            mCloseGuard.open("close");
24262        }
24263
24264        public PackageFreezer(String packageName, int userId, String killReason) {
24265            synchronized (mPackages) {
24266                mPackageName = packageName;
24267                mWeFroze = mFrozenPackages.add(mPackageName);
24268
24269                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
24270                if (ps != null) {
24271                    killApplication(ps.name, ps.appId, userId, killReason);
24272                }
24273
24274                final PackageParser.Package p = mPackages.get(packageName);
24275                if (p != null && p.childPackages != null) {
24276                    final int N = p.childPackages.size();
24277                    mChildren = new PackageFreezer[N];
24278                    for (int i = 0; i < N; i++) {
24279                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
24280                                userId, killReason);
24281                    }
24282                } else {
24283                    mChildren = null;
24284                }
24285            }
24286            mCloseGuard.open("close");
24287        }
24288
24289        @Override
24290        protected void finalize() throws Throwable {
24291            try {
24292                if (mCloseGuard != null) {
24293                    mCloseGuard.warnIfOpen();
24294                }
24295
24296                close();
24297            } finally {
24298                super.finalize();
24299            }
24300        }
24301
24302        @Override
24303        public void close() {
24304            mCloseGuard.close();
24305            if (mClosed.compareAndSet(false, true)) {
24306                synchronized (mPackages) {
24307                    if (mWeFroze) {
24308                        mFrozenPackages.remove(mPackageName);
24309                    }
24310
24311                    if (mChildren != null) {
24312                        for (PackageFreezer freezer : mChildren) {
24313                            freezer.close();
24314                        }
24315                    }
24316                }
24317            }
24318        }
24319    }
24320
24321    /**
24322     * Verify that given package is currently frozen.
24323     */
24324    private void checkPackageFrozen(String packageName) {
24325        synchronized (mPackages) {
24326            if (!mFrozenPackages.contains(packageName)) {
24327                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
24328            }
24329        }
24330    }
24331
24332    @Override
24333    public int movePackage(final String packageName, final String volumeUuid) {
24334        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
24335
24336        final int callingUid = Binder.getCallingUid();
24337        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
24338        final int moveId = mNextMoveId.getAndIncrement();
24339        mHandler.post(new Runnable() {
24340            @Override
24341            public void run() {
24342                try {
24343                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
24344                } catch (PackageManagerException e) {
24345                    Slog.w(TAG, "Failed to move " + packageName, e);
24346                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
24347                }
24348            }
24349        });
24350        return moveId;
24351    }
24352
24353    private void movePackageInternal(final String packageName, final String volumeUuid,
24354            final int moveId, final int callingUid, UserHandle user)
24355                    throws PackageManagerException {
24356        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24357        final PackageManager pm = mContext.getPackageManager();
24358
24359        final boolean currentAsec;
24360        final String currentVolumeUuid;
24361        final File codeFile;
24362        final String installerPackageName;
24363        final String packageAbiOverride;
24364        final int appId;
24365        final String seinfo;
24366        final String label;
24367        final int targetSdkVersion;
24368        final PackageFreezer freezer;
24369        final int[] installedUserIds;
24370
24371        // reader
24372        synchronized (mPackages) {
24373            final PackageParser.Package pkg = mPackages.get(packageName);
24374            final PackageSetting ps = mSettings.mPackages.get(packageName);
24375            if (pkg == null
24376                    || ps == null
24377                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
24378                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
24379            }
24380            if (pkg.applicationInfo.isSystemApp()) {
24381                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
24382                        "Cannot move system application");
24383            }
24384
24385            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
24386            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
24387                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
24388            if (isInternalStorage && !allow3rdPartyOnInternal) {
24389                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
24390                        "3rd party apps are not allowed on internal storage");
24391            }
24392
24393            if (pkg.applicationInfo.isExternalAsec()) {
24394                currentAsec = true;
24395                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
24396            } else if (pkg.applicationInfo.isForwardLocked()) {
24397                currentAsec = true;
24398                currentVolumeUuid = "forward_locked";
24399            } else {
24400                currentAsec = false;
24401                currentVolumeUuid = ps.volumeUuid;
24402
24403                final File probe = new File(pkg.codePath);
24404                final File probeOat = new File(probe, "oat");
24405                if (!probe.isDirectory() || !probeOat.isDirectory()) {
24406                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24407                            "Move only supported for modern cluster style installs");
24408                }
24409            }
24410
24411            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
24412                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24413                        "Package already moved to " + volumeUuid);
24414            }
24415            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
24416                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
24417                        "Device admin cannot be moved");
24418            }
24419
24420            if (mFrozenPackages.contains(packageName)) {
24421                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
24422                        "Failed to move already frozen package");
24423            }
24424
24425            codeFile = new File(pkg.codePath);
24426            installerPackageName = ps.installerPackageName;
24427            packageAbiOverride = ps.cpuAbiOverrideString;
24428            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
24429            seinfo = pkg.applicationInfo.seInfo;
24430            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
24431            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
24432            freezer = freezePackage(packageName, "movePackageInternal");
24433            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
24434        }
24435
24436        final Bundle extras = new Bundle();
24437        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
24438        extras.putString(Intent.EXTRA_TITLE, label);
24439        mMoveCallbacks.notifyCreated(moveId, extras);
24440
24441        int installFlags;
24442        final boolean moveCompleteApp;
24443        final File measurePath;
24444
24445        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
24446            installFlags = INSTALL_INTERNAL;
24447            moveCompleteApp = !currentAsec;
24448            measurePath = Environment.getDataAppDirectory(volumeUuid);
24449        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
24450            installFlags = INSTALL_EXTERNAL;
24451            moveCompleteApp = false;
24452            measurePath = storage.getPrimaryPhysicalVolume().getPath();
24453        } else {
24454            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
24455            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
24456                    || !volume.isMountedWritable()) {
24457                freezer.close();
24458                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24459                        "Move location not mounted private volume");
24460            }
24461
24462            Preconditions.checkState(!currentAsec);
24463
24464            installFlags = INSTALL_INTERNAL;
24465            moveCompleteApp = true;
24466            measurePath = Environment.getDataAppDirectory(volumeUuid);
24467        }
24468
24469        // If we're moving app data around, we need all the users unlocked
24470        if (moveCompleteApp) {
24471            for (int userId : installedUserIds) {
24472                if (StorageManager.isFileEncryptedNativeOrEmulated()
24473                        && !StorageManager.isUserKeyUnlocked(userId)) {
24474                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
24475                            "User " + userId + " must be unlocked");
24476                }
24477            }
24478        }
24479
24480        final PackageStats stats = new PackageStats(null, -1);
24481        synchronized (mInstaller) {
24482            for (int userId : installedUserIds) {
24483                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
24484                    freezer.close();
24485                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24486                            "Failed to measure package size");
24487                }
24488            }
24489        }
24490
24491        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
24492                + stats.dataSize);
24493
24494        final long startFreeBytes = measurePath.getUsableSpace();
24495        final long sizeBytes;
24496        if (moveCompleteApp) {
24497            sizeBytes = stats.codeSize + stats.dataSize;
24498        } else {
24499            sizeBytes = stats.codeSize;
24500        }
24501
24502        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
24503            freezer.close();
24504            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24505                    "Not enough free space to move");
24506        }
24507
24508        mMoveCallbacks.notifyStatusChanged(moveId, 10);
24509
24510        final CountDownLatch installedLatch = new CountDownLatch(1);
24511        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
24512            @Override
24513            public void onUserActionRequired(Intent intent) throws RemoteException {
24514                throw new IllegalStateException();
24515            }
24516
24517            @Override
24518            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
24519                    Bundle extras) throws RemoteException {
24520                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
24521                        + PackageManager.installStatusToString(returnCode, msg));
24522
24523                installedLatch.countDown();
24524                freezer.close();
24525
24526                final int status = PackageManager.installStatusToPublicStatus(returnCode);
24527                switch (status) {
24528                    case PackageInstaller.STATUS_SUCCESS:
24529                        mMoveCallbacks.notifyStatusChanged(moveId,
24530                                PackageManager.MOVE_SUCCEEDED);
24531                        break;
24532                    case PackageInstaller.STATUS_FAILURE_STORAGE:
24533                        mMoveCallbacks.notifyStatusChanged(moveId,
24534                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
24535                        break;
24536                    default:
24537                        mMoveCallbacks.notifyStatusChanged(moveId,
24538                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
24539                        break;
24540                }
24541            }
24542        };
24543
24544        final MoveInfo move;
24545        if (moveCompleteApp) {
24546            // Kick off a thread to report progress estimates
24547            new Thread() {
24548                @Override
24549                public void run() {
24550                    while (true) {
24551                        try {
24552                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
24553                                break;
24554                            }
24555                        } catch (InterruptedException ignored) {
24556                        }
24557
24558                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
24559                        final int progress = 10 + (int) MathUtils.constrain(
24560                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
24561                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
24562                    }
24563                }
24564            }.start();
24565
24566            final String dataAppName = codeFile.getName();
24567            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
24568                    dataAppName, appId, seinfo, targetSdkVersion);
24569        } else {
24570            move = null;
24571        }
24572
24573        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
24574
24575        final Message msg = mHandler.obtainMessage(INIT_COPY);
24576        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
24577        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
24578                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
24579                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
24580                PackageManager.INSTALL_REASON_UNKNOWN);
24581        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
24582        msg.obj = params;
24583
24584        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
24585                System.identityHashCode(msg.obj));
24586        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
24587                System.identityHashCode(msg.obj));
24588
24589        mHandler.sendMessage(msg);
24590    }
24591
24592    @Override
24593    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
24594        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
24595
24596        final int realMoveId = mNextMoveId.getAndIncrement();
24597        final Bundle extras = new Bundle();
24598        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
24599        mMoveCallbacks.notifyCreated(realMoveId, extras);
24600
24601        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
24602            @Override
24603            public void onCreated(int moveId, Bundle extras) {
24604                // Ignored
24605            }
24606
24607            @Override
24608            public void onStatusChanged(int moveId, int status, long estMillis) {
24609                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
24610            }
24611        };
24612
24613        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24614        storage.setPrimaryStorageUuid(volumeUuid, callback);
24615        return realMoveId;
24616    }
24617
24618    @Override
24619    public int getMoveStatus(int moveId) {
24620        mContext.enforceCallingOrSelfPermission(
24621                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24622        return mMoveCallbacks.mLastStatus.get(moveId);
24623    }
24624
24625    @Override
24626    public void registerMoveCallback(IPackageMoveObserver callback) {
24627        mContext.enforceCallingOrSelfPermission(
24628                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24629        mMoveCallbacks.register(callback);
24630    }
24631
24632    @Override
24633    public void unregisterMoveCallback(IPackageMoveObserver callback) {
24634        mContext.enforceCallingOrSelfPermission(
24635                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24636        mMoveCallbacks.unregister(callback);
24637    }
24638
24639    @Override
24640    public boolean setInstallLocation(int loc) {
24641        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
24642                null);
24643        if (getInstallLocation() == loc) {
24644            return true;
24645        }
24646        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
24647                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
24648            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
24649                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
24650            return true;
24651        }
24652        return false;
24653   }
24654
24655    @Override
24656    public int getInstallLocation() {
24657        // allow instant app access
24658        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
24659                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
24660                PackageHelper.APP_INSTALL_AUTO);
24661    }
24662
24663    /** Called by UserManagerService */
24664    void cleanUpUser(UserManagerService userManager, int userHandle) {
24665        synchronized (mPackages) {
24666            mDirtyUsers.remove(userHandle);
24667            mUserNeedsBadging.delete(userHandle);
24668            mSettings.removeUserLPw(userHandle);
24669            mPendingBroadcasts.remove(userHandle);
24670            mInstantAppRegistry.onUserRemovedLPw(userHandle);
24671            removeUnusedPackagesLPw(userManager, userHandle);
24672        }
24673    }
24674
24675    /**
24676     * We're removing userHandle and would like to remove any downloaded packages
24677     * that are no longer in use by any other user.
24678     * @param userHandle the user being removed
24679     */
24680    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
24681        final boolean DEBUG_CLEAN_APKS = false;
24682        int [] users = userManager.getUserIds();
24683        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
24684        while (psit.hasNext()) {
24685            PackageSetting ps = psit.next();
24686            if (ps.pkg == null) {
24687                continue;
24688            }
24689            final String packageName = ps.pkg.packageName;
24690            // Skip over if system app
24691            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
24692                continue;
24693            }
24694            if (DEBUG_CLEAN_APKS) {
24695                Slog.i(TAG, "Checking package " + packageName);
24696            }
24697            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
24698            if (keep) {
24699                if (DEBUG_CLEAN_APKS) {
24700                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
24701                }
24702            } else {
24703                for (int i = 0; i < users.length; i++) {
24704                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
24705                        keep = true;
24706                        if (DEBUG_CLEAN_APKS) {
24707                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
24708                                    + users[i]);
24709                        }
24710                        break;
24711                    }
24712                }
24713            }
24714            if (!keep) {
24715                if (DEBUG_CLEAN_APKS) {
24716                    Slog.i(TAG, "  Removing package " + packageName);
24717                }
24718                mHandler.post(new Runnable() {
24719                    public void run() {
24720                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24721                                userHandle, 0);
24722                    } //end run
24723                });
24724            }
24725        }
24726    }
24727
24728    /** Called by UserManagerService */
24729    void createNewUser(int userId, String[] disallowedPackages) {
24730        synchronized (mInstallLock) {
24731            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
24732        }
24733        synchronized (mPackages) {
24734            scheduleWritePackageRestrictionsLocked(userId);
24735            scheduleWritePackageListLocked(userId);
24736            applyFactoryDefaultBrowserLPw(userId);
24737            primeDomainVerificationsLPw(userId);
24738        }
24739    }
24740
24741    void onNewUserCreated(final int userId) {
24742        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
24743        // If permission review for legacy apps is required, we represent
24744        // dagerous permissions for such apps as always granted runtime
24745        // permissions to keep per user flag state whether review is needed.
24746        // Hence, if a new user is added we have to propagate dangerous
24747        // permission grants for these legacy apps.
24748        if (mPermissionReviewRequired) {
24749            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
24750                    | UPDATE_PERMISSIONS_REPLACE_ALL);
24751        }
24752    }
24753
24754    @Override
24755    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
24756        mContext.enforceCallingOrSelfPermission(
24757                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
24758                "Only package verification agents can read the verifier device identity");
24759
24760        synchronized (mPackages) {
24761            return mSettings.getVerifierDeviceIdentityLPw();
24762        }
24763    }
24764
24765    @Override
24766    public void setPermissionEnforced(String permission, boolean enforced) {
24767        // TODO: Now that we no longer change GID for storage, this should to away.
24768        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
24769                "setPermissionEnforced");
24770        if (READ_EXTERNAL_STORAGE.equals(permission)) {
24771            synchronized (mPackages) {
24772                if (mSettings.mReadExternalStorageEnforced == null
24773                        || mSettings.mReadExternalStorageEnforced != enforced) {
24774                    mSettings.mReadExternalStorageEnforced = enforced;
24775                    mSettings.writeLPr();
24776                }
24777            }
24778            // kill any non-foreground processes so we restart them and
24779            // grant/revoke the GID.
24780            final IActivityManager am = ActivityManager.getService();
24781            if (am != null) {
24782                final long token = Binder.clearCallingIdentity();
24783                try {
24784                    am.killProcessesBelowForeground("setPermissionEnforcement");
24785                } catch (RemoteException e) {
24786                } finally {
24787                    Binder.restoreCallingIdentity(token);
24788                }
24789            }
24790        } else {
24791            throw new IllegalArgumentException("No selective enforcement for " + permission);
24792        }
24793    }
24794
24795    @Override
24796    @Deprecated
24797    public boolean isPermissionEnforced(String permission) {
24798        // allow instant applications
24799        return true;
24800    }
24801
24802    @Override
24803    public boolean isStorageLow() {
24804        // allow instant applications
24805        final long token = Binder.clearCallingIdentity();
24806        try {
24807            final DeviceStorageMonitorInternal
24808                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
24809            if (dsm != null) {
24810                return dsm.isMemoryLow();
24811            } else {
24812                return false;
24813            }
24814        } finally {
24815            Binder.restoreCallingIdentity(token);
24816        }
24817    }
24818
24819    @Override
24820    public IPackageInstaller getPackageInstaller() {
24821        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24822            return null;
24823        }
24824        return mInstallerService;
24825    }
24826
24827    private boolean userNeedsBadging(int userId) {
24828        int index = mUserNeedsBadging.indexOfKey(userId);
24829        if (index < 0) {
24830            final UserInfo userInfo;
24831            final long token = Binder.clearCallingIdentity();
24832            try {
24833                userInfo = sUserManager.getUserInfo(userId);
24834            } finally {
24835                Binder.restoreCallingIdentity(token);
24836            }
24837            final boolean b;
24838            if (userInfo != null && userInfo.isManagedProfile()) {
24839                b = true;
24840            } else {
24841                b = false;
24842            }
24843            mUserNeedsBadging.put(userId, b);
24844            return b;
24845        }
24846        return mUserNeedsBadging.valueAt(index);
24847    }
24848
24849    @Override
24850    public KeySet getKeySetByAlias(String packageName, String alias) {
24851        if (packageName == null || alias == null) {
24852            return null;
24853        }
24854        synchronized(mPackages) {
24855            final PackageParser.Package pkg = mPackages.get(packageName);
24856            if (pkg == null) {
24857                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24858                throw new IllegalArgumentException("Unknown package: " + packageName);
24859            }
24860            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24861            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24862                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24863                throw new IllegalArgumentException("Unknown package: " + packageName);
24864            }
24865            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24866            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24867        }
24868    }
24869
24870    @Override
24871    public KeySet getSigningKeySet(String packageName) {
24872        if (packageName == null) {
24873            return null;
24874        }
24875        synchronized(mPackages) {
24876            final int callingUid = Binder.getCallingUid();
24877            final int callingUserId = UserHandle.getUserId(callingUid);
24878            final PackageParser.Package pkg = mPackages.get(packageName);
24879            if (pkg == null) {
24880                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24881                throw new IllegalArgumentException("Unknown package: " + packageName);
24882            }
24883            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24884            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24885                // filter and pretend the package doesn't exist
24886                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24887                        + ", uid:" + callingUid);
24888                throw new IllegalArgumentException("Unknown package: " + packageName);
24889            }
24890            if (pkg.applicationInfo.uid != callingUid
24891                    && Process.SYSTEM_UID != callingUid) {
24892                throw new SecurityException("May not access signing KeySet of other apps.");
24893            }
24894            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24895            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24896        }
24897    }
24898
24899    @Override
24900    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
24901        final int callingUid = Binder.getCallingUid();
24902        if (getInstantAppPackageName(callingUid) != null) {
24903            return false;
24904        }
24905        if (packageName == null || ks == null) {
24906            return false;
24907        }
24908        synchronized(mPackages) {
24909            final PackageParser.Package pkg = mPackages.get(packageName);
24910            if (pkg == null
24911                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24912                            UserHandle.getUserId(callingUid))) {
24913                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24914                throw new IllegalArgumentException("Unknown package: " + packageName);
24915            }
24916            IBinder ksh = ks.getToken();
24917            if (ksh instanceof KeySetHandle) {
24918                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24919                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
24920            }
24921            return false;
24922        }
24923    }
24924
24925    @Override
24926    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
24927        final int callingUid = Binder.getCallingUid();
24928        if (getInstantAppPackageName(callingUid) != null) {
24929            return false;
24930        }
24931        if (packageName == null || ks == null) {
24932            return false;
24933        }
24934        synchronized(mPackages) {
24935            final PackageParser.Package pkg = mPackages.get(packageName);
24936            if (pkg == null
24937                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24938                            UserHandle.getUserId(callingUid))) {
24939                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24940                throw new IllegalArgumentException("Unknown package: " + packageName);
24941            }
24942            IBinder ksh = ks.getToken();
24943            if (ksh instanceof KeySetHandle) {
24944                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24945                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
24946            }
24947            return false;
24948        }
24949    }
24950
24951    private void deletePackageIfUnusedLPr(final String packageName) {
24952        PackageSetting ps = mSettings.mPackages.get(packageName);
24953        if (ps == null) {
24954            return;
24955        }
24956        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
24957            // TODO Implement atomic delete if package is unused
24958            // It is currently possible that the package will be deleted even if it is installed
24959            // after this method returns.
24960            mHandler.post(new Runnable() {
24961                public void run() {
24962                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24963                            0, PackageManager.DELETE_ALL_USERS);
24964                }
24965            });
24966        }
24967    }
24968
24969    /**
24970     * Check and throw if the given before/after packages would be considered a
24971     * downgrade.
24972     */
24973    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
24974            throws PackageManagerException {
24975        if (after.versionCode < before.mVersionCode) {
24976            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24977                    "Update version code " + after.versionCode + " is older than current "
24978                    + before.mVersionCode);
24979        } else if (after.versionCode == before.mVersionCode) {
24980            if (after.baseRevisionCode < before.baseRevisionCode) {
24981                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24982                        "Update base revision code " + after.baseRevisionCode
24983                        + " is older than current " + before.baseRevisionCode);
24984            }
24985
24986            if (!ArrayUtils.isEmpty(after.splitNames)) {
24987                for (int i = 0; i < after.splitNames.length; i++) {
24988                    final String splitName = after.splitNames[i];
24989                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
24990                    if (j != -1) {
24991                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
24992                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24993                                    "Update split " + splitName + " revision code "
24994                                    + after.splitRevisionCodes[i] + " is older than current "
24995                                    + before.splitRevisionCodes[j]);
24996                        }
24997                    }
24998                }
24999            }
25000        }
25001    }
25002
25003    private static class MoveCallbacks extends Handler {
25004        private static final int MSG_CREATED = 1;
25005        private static final int MSG_STATUS_CHANGED = 2;
25006
25007        private final RemoteCallbackList<IPackageMoveObserver>
25008                mCallbacks = new RemoteCallbackList<>();
25009
25010        private final SparseIntArray mLastStatus = new SparseIntArray();
25011
25012        public MoveCallbacks(Looper looper) {
25013            super(looper);
25014        }
25015
25016        public void register(IPackageMoveObserver callback) {
25017            mCallbacks.register(callback);
25018        }
25019
25020        public void unregister(IPackageMoveObserver callback) {
25021            mCallbacks.unregister(callback);
25022        }
25023
25024        @Override
25025        public void handleMessage(Message msg) {
25026            final SomeArgs args = (SomeArgs) msg.obj;
25027            final int n = mCallbacks.beginBroadcast();
25028            for (int i = 0; i < n; i++) {
25029                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
25030                try {
25031                    invokeCallback(callback, msg.what, args);
25032                } catch (RemoteException ignored) {
25033                }
25034            }
25035            mCallbacks.finishBroadcast();
25036            args.recycle();
25037        }
25038
25039        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
25040                throws RemoteException {
25041            switch (what) {
25042                case MSG_CREATED: {
25043                    callback.onCreated(args.argi1, (Bundle) args.arg2);
25044                    break;
25045                }
25046                case MSG_STATUS_CHANGED: {
25047                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
25048                    break;
25049                }
25050            }
25051        }
25052
25053        private void notifyCreated(int moveId, Bundle extras) {
25054            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
25055
25056            final SomeArgs args = SomeArgs.obtain();
25057            args.argi1 = moveId;
25058            args.arg2 = extras;
25059            obtainMessage(MSG_CREATED, args).sendToTarget();
25060        }
25061
25062        private void notifyStatusChanged(int moveId, int status) {
25063            notifyStatusChanged(moveId, status, -1);
25064        }
25065
25066        private void notifyStatusChanged(int moveId, int status, long estMillis) {
25067            Slog.v(TAG, "Move " + moveId + " status " + status);
25068
25069            final SomeArgs args = SomeArgs.obtain();
25070            args.argi1 = moveId;
25071            args.argi2 = status;
25072            args.arg3 = estMillis;
25073            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
25074
25075            synchronized (mLastStatus) {
25076                mLastStatus.put(moveId, status);
25077            }
25078        }
25079    }
25080
25081    private final static class OnPermissionChangeListeners extends Handler {
25082        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
25083
25084        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
25085                new RemoteCallbackList<>();
25086
25087        public OnPermissionChangeListeners(Looper looper) {
25088            super(looper);
25089        }
25090
25091        @Override
25092        public void handleMessage(Message msg) {
25093            switch (msg.what) {
25094                case MSG_ON_PERMISSIONS_CHANGED: {
25095                    final int uid = msg.arg1;
25096                    handleOnPermissionsChanged(uid);
25097                } break;
25098            }
25099        }
25100
25101        public void addListenerLocked(IOnPermissionsChangeListener listener) {
25102            mPermissionListeners.register(listener);
25103
25104        }
25105
25106        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
25107            mPermissionListeners.unregister(listener);
25108        }
25109
25110        public void onPermissionsChanged(int uid) {
25111            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
25112                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
25113            }
25114        }
25115
25116        private void handleOnPermissionsChanged(int uid) {
25117            final int count = mPermissionListeners.beginBroadcast();
25118            try {
25119                for (int i = 0; i < count; i++) {
25120                    IOnPermissionsChangeListener callback = mPermissionListeners
25121                            .getBroadcastItem(i);
25122                    try {
25123                        callback.onPermissionsChanged(uid);
25124                    } catch (RemoteException e) {
25125                        Log.e(TAG, "Permission listener is dead", e);
25126                    }
25127                }
25128            } finally {
25129                mPermissionListeners.finishBroadcast();
25130            }
25131        }
25132    }
25133
25134    private class PackageManagerNative extends IPackageManagerNative.Stub {
25135        @Override
25136        public String[] getNamesForUids(int[] uids) throws RemoteException {
25137            final String[] results = PackageManagerService.this.getNamesForUids(uids);
25138            // massage results so they can be parsed by the native binder
25139            for (int i = results.length - 1; i >= 0; --i) {
25140                if (results[i] == null) {
25141                    results[i] = "";
25142                }
25143            }
25144            return results;
25145        }
25146    }
25147
25148    private class PackageManagerInternalImpl extends PackageManagerInternal {
25149        @Override
25150        public void setLocationPackagesProvider(PackagesProvider provider) {
25151            synchronized (mPackages) {
25152                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
25153            }
25154        }
25155
25156        @Override
25157        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
25158            synchronized (mPackages) {
25159                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
25160            }
25161        }
25162
25163        @Override
25164        public void setSmsAppPackagesProvider(PackagesProvider provider) {
25165            synchronized (mPackages) {
25166                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
25167            }
25168        }
25169
25170        @Override
25171        public void setDialerAppPackagesProvider(PackagesProvider provider) {
25172            synchronized (mPackages) {
25173                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
25174            }
25175        }
25176
25177        @Override
25178        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
25179            synchronized (mPackages) {
25180                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
25181            }
25182        }
25183
25184        @Override
25185        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
25186            synchronized (mPackages) {
25187                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
25188            }
25189        }
25190
25191        @Override
25192        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
25193            synchronized (mPackages) {
25194                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
25195                        packageName, userId);
25196            }
25197        }
25198
25199        @Override
25200        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
25201            synchronized (mPackages) {
25202                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
25203                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
25204                        packageName, userId);
25205            }
25206        }
25207
25208        @Override
25209        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
25210            synchronized (mPackages) {
25211                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
25212                        packageName, userId);
25213            }
25214        }
25215
25216        @Override
25217        public void setKeepUninstalledPackages(final List<String> packageList) {
25218            Preconditions.checkNotNull(packageList);
25219            List<String> removedFromList = null;
25220            synchronized (mPackages) {
25221                if (mKeepUninstalledPackages != null) {
25222                    final int packagesCount = mKeepUninstalledPackages.size();
25223                    for (int i = 0; i < packagesCount; i++) {
25224                        String oldPackage = mKeepUninstalledPackages.get(i);
25225                        if (packageList != null && packageList.contains(oldPackage)) {
25226                            continue;
25227                        }
25228                        if (removedFromList == null) {
25229                            removedFromList = new ArrayList<>();
25230                        }
25231                        removedFromList.add(oldPackage);
25232                    }
25233                }
25234                mKeepUninstalledPackages = new ArrayList<>(packageList);
25235                if (removedFromList != null) {
25236                    final int removedCount = removedFromList.size();
25237                    for (int i = 0; i < removedCount; i++) {
25238                        deletePackageIfUnusedLPr(removedFromList.get(i));
25239                    }
25240                }
25241            }
25242        }
25243
25244        @Override
25245        public boolean isPermissionsReviewRequired(String packageName, int userId) {
25246            synchronized (mPackages) {
25247                // If we do not support permission review, done.
25248                if (!mPermissionReviewRequired) {
25249                    return false;
25250                }
25251
25252                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
25253                if (packageSetting == null) {
25254                    return false;
25255                }
25256
25257                // Permission review applies only to apps not supporting the new permission model.
25258                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
25259                    return false;
25260                }
25261
25262                // Legacy apps have the permission and get user consent on launch.
25263                PermissionsState permissionsState = packageSetting.getPermissionsState();
25264                return permissionsState.isPermissionReviewRequired(userId);
25265            }
25266        }
25267
25268        @Override
25269        public PackageInfo getPackageInfo(
25270                String packageName, int flags, int filterCallingUid, int userId) {
25271            return PackageManagerService.this
25272                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
25273                            flags, filterCallingUid, userId);
25274        }
25275
25276        @Override
25277        public ApplicationInfo getApplicationInfo(
25278                String packageName, int flags, int filterCallingUid, int userId) {
25279            return PackageManagerService.this
25280                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
25281        }
25282
25283        @Override
25284        public ActivityInfo getActivityInfo(
25285                ComponentName component, int flags, int filterCallingUid, int userId) {
25286            return PackageManagerService.this
25287                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
25288        }
25289
25290        @Override
25291        public List<ResolveInfo> queryIntentActivities(
25292                Intent intent, int flags, int filterCallingUid, int userId) {
25293            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
25294            return PackageManagerService.this
25295                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
25296                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
25297        }
25298
25299        @Override
25300        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
25301                int userId) {
25302            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
25303        }
25304
25305        @Override
25306        public void setDeviceAndProfileOwnerPackages(
25307                int deviceOwnerUserId, String deviceOwnerPackage,
25308                SparseArray<String> profileOwnerPackages) {
25309            mProtectedPackages.setDeviceAndProfileOwnerPackages(
25310                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
25311        }
25312
25313        @Override
25314        public boolean isPackageDataProtected(int userId, String packageName) {
25315            return mProtectedPackages.isPackageDataProtected(userId, packageName);
25316        }
25317
25318        @Override
25319        public boolean isPackageEphemeral(int userId, String packageName) {
25320            synchronized (mPackages) {
25321                final PackageSetting ps = mSettings.mPackages.get(packageName);
25322                return ps != null ? ps.getInstantApp(userId) : false;
25323            }
25324        }
25325
25326        @Override
25327        public boolean wasPackageEverLaunched(String packageName, int userId) {
25328            synchronized (mPackages) {
25329                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
25330            }
25331        }
25332
25333        @Override
25334        public void grantRuntimePermission(String packageName, String name, int userId,
25335                boolean overridePolicy) {
25336            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
25337                    overridePolicy);
25338        }
25339
25340        @Override
25341        public void revokeRuntimePermission(String packageName, String name, int userId,
25342                boolean overridePolicy) {
25343            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
25344                    overridePolicy);
25345        }
25346
25347        @Override
25348        public String getNameForUid(int uid) {
25349            return PackageManagerService.this.getNameForUid(uid);
25350        }
25351
25352        @Override
25353        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
25354                Intent origIntent, String resolvedType, String callingPackage,
25355                Bundle verificationBundle, int userId) {
25356            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
25357                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
25358                    userId);
25359        }
25360
25361        @Override
25362        public void grantEphemeralAccess(int userId, Intent intent,
25363                int targetAppId, int ephemeralAppId) {
25364            synchronized (mPackages) {
25365                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
25366                        targetAppId, ephemeralAppId);
25367            }
25368        }
25369
25370        @Override
25371        public boolean isInstantAppInstallerComponent(ComponentName component) {
25372            synchronized (mPackages) {
25373                return mInstantAppInstallerActivity != null
25374                        && mInstantAppInstallerActivity.getComponentName().equals(component);
25375            }
25376        }
25377
25378        @Override
25379        public void pruneInstantApps() {
25380            mInstantAppRegistry.pruneInstantApps();
25381        }
25382
25383        @Override
25384        public String getSetupWizardPackageName() {
25385            return mSetupWizardPackage;
25386        }
25387
25388        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
25389            if (policy != null) {
25390                mExternalSourcesPolicy = policy;
25391            }
25392        }
25393
25394        @Override
25395        public boolean isPackagePersistent(String packageName) {
25396            synchronized (mPackages) {
25397                PackageParser.Package pkg = mPackages.get(packageName);
25398                return pkg != null
25399                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
25400                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
25401                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
25402                        : false;
25403            }
25404        }
25405
25406        @Override
25407        public List<PackageInfo> getOverlayPackages(int userId) {
25408            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
25409            synchronized (mPackages) {
25410                for (PackageParser.Package p : mPackages.values()) {
25411                    if (p.mOverlayTarget != null) {
25412                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
25413                        if (pkg != null) {
25414                            overlayPackages.add(pkg);
25415                        }
25416                    }
25417                }
25418            }
25419            return overlayPackages;
25420        }
25421
25422        @Override
25423        public List<String> getTargetPackageNames(int userId) {
25424            List<String> targetPackages = new ArrayList<>();
25425            synchronized (mPackages) {
25426                for (PackageParser.Package p : mPackages.values()) {
25427                    if (p.mOverlayTarget == null) {
25428                        targetPackages.add(p.packageName);
25429                    }
25430                }
25431            }
25432            return targetPackages;
25433        }
25434
25435        @Override
25436        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
25437                @Nullable List<String> overlayPackageNames) {
25438            synchronized (mPackages) {
25439                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
25440                    Slog.e(TAG, "failed to find package " + targetPackageName);
25441                    return false;
25442                }
25443                ArrayList<String> overlayPaths = null;
25444                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
25445                    final int N = overlayPackageNames.size();
25446                    overlayPaths = new ArrayList<>(N);
25447                    for (int i = 0; i < N; i++) {
25448                        final String packageName = overlayPackageNames.get(i);
25449                        final PackageParser.Package pkg = mPackages.get(packageName);
25450                        if (pkg == null) {
25451                            Slog.e(TAG, "failed to find package " + packageName);
25452                            return false;
25453                        }
25454                        overlayPaths.add(pkg.baseCodePath);
25455                    }
25456                }
25457
25458                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
25459                ps.setOverlayPaths(overlayPaths, userId);
25460                return true;
25461            }
25462        }
25463
25464        @Override
25465        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
25466                int flags, int userId) {
25467            return resolveIntentInternal(
25468                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
25469        }
25470
25471        @Override
25472        public ResolveInfo resolveService(Intent intent, String resolvedType,
25473                int flags, int userId, int callingUid) {
25474            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
25475        }
25476
25477        @Override
25478        public void addIsolatedUid(int isolatedUid, int ownerUid) {
25479            synchronized (mPackages) {
25480                mIsolatedOwners.put(isolatedUid, ownerUid);
25481            }
25482        }
25483
25484        @Override
25485        public void removeIsolatedUid(int isolatedUid) {
25486            synchronized (mPackages) {
25487                mIsolatedOwners.delete(isolatedUid);
25488            }
25489        }
25490
25491        @Override
25492        public int getUidTargetSdkVersion(int uid) {
25493            synchronized (mPackages) {
25494                return getUidTargetSdkVersionLockedLPr(uid);
25495            }
25496        }
25497
25498        @Override
25499        public boolean canAccessInstantApps(int callingUid, int userId) {
25500            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
25501        }
25502
25503        @Override
25504        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
25505            synchronized (mPackages) {
25506                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
25507            }
25508        }
25509
25510        @Override
25511        public void notifyPackageUse(String packageName, int reason) {
25512            synchronized (mPackages) {
25513                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
25514            }
25515        }
25516    }
25517
25518    @Override
25519    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
25520        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
25521        synchronized (mPackages) {
25522            final long identity = Binder.clearCallingIdentity();
25523            try {
25524                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
25525                        packageNames, userId);
25526            } finally {
25527                Binder.restoreCallingIdentity(identity);
25528            }
25529        }
25530    }
25531
25532    @Override
25533    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
25534        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
25535        synchronized (mPackages) {
25536            final long identity = Binder.clearCallingIdentity();
25537            try {
25538                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
25539                        packageNames, userId);
25540            } finally {
25541                Binder.restoreCallingIdentity(identity);
25542            }
25543        }
25544    }
25545
25546    private static void enforceSystemOrPhoneCaller(String tag) {
25547        int callingUid = Binder.getCallingUid();
25548        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
25549            throw new SecurityException(
25550                    "Cannot call " + tag + " from UID " + callingUid);
25551        }
25552    }
25553
25554    boolean isHistoricalPackageUsageAvailable() {
25555        return mPackageUsage.isHistoricalPackageUsageAvailable();
25556    }
25557
25558    /**
25559     * Return a <b>copy</b> of the collection of packages known to the package manager.
25560     * @return A copy of the values of mPackages.
25561     */
25562    Collection<PackageParser.Package> getPackages() {
25563        synchronized (mPackages) {
25564            return new ArrayList<>(mPackages.values());
25565        }
25566    }
25567
25568    /**
25569     * Logs process start information (including base APK hash) to the security log.
25570     * @hide
25571     */
25572    @Override
25573    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
25574            String apkFile, int pid) {
25575        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25576            return;
25577        }
25578        if (!SecurityLog.isLoggingEnabled()) {
25579            return;
25580        }
25581        Bundle data = new Bundle();
25582        data.putLong("startTimestamp", System.currentTimeMillis());
25583        data.putString("processName", processName);
25584        data.putInt("uid", uid);
25585        data.putString("seinfo", seinfo);
25586        data.putString("apkFile", apkFile);
25587        data.putInt("pid", pid);
25588        Message msg = mProcessLoggingHandler.obtainMessage(
25589                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
25590        msg.setData(data);
25591        mProcessLoggingHandler.sendMessage(msg);
25592    }
25593
25594    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
25595        return mCompilerStats.getPackageStats(pkgName);
25596    }
25597
25598    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
25599        return getOrCreateCompilerPackageStats(pkg.packageName);
25600    }
25601
25602    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
25603        return mCompilerStats.getOrCreatePackageStats(pkgName);
25604    }
25605
25606    public void deleteCompilerPackageStats(String pkgName) {
25607        mCompilerStats.deletePackageStats(pkgName);
25608    }
25609
25610    @Override
25611    public int getInstallReason(String packageName, int userId) {
25612        final int callingUid = Binder.getCallingUid();
25613        enforceCrossUserPermission(callingUid, userId,
25614                true /* requireFullPermission */, false /* checkShell */,
25615                "get install reason");
25616        synchronized (mPackages) {
25617            final PackageSetting ps = mSettings.mPackages.get(packageName);
25618            if (filterAppAccessLPr(ps, callingUid, userId)) {
25619                return PackageManager.INSTALL_REASON_UNKNOWN;
25620            }
25621            if (ps != null) {
25622                return ps.getInstallReason(userId);
25623            }
25624        }
25625        return PackageManager.INSTALL_REASON_UNKNOWN;
25626    }
25627
25628    @Override
25629    public boolean canRequestPackageInstalls(String packageName, int userId) {
25630        return canRequestPackageInstallsInternal(packageName, 0, userId,
25631                true /* throwIfPermNotDeclared*/);
25632    }
25633
25634    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
25635            boolean throwIfPermNotDeclared) {
25636        int callingUid = Binder.getCallingUid();
25637        int uid = getPackageUid(packageName, 0, userId);
25638        if (callingUid != uid && callingUid != Process.ROOT_UID
25639                && callingUid != Process.SYSTEM_UID) {
25640            throw new SecurityException(
25641                    "Caller uid " + callingUid + " does not own package " + packageName);
25642        }
25643        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
25644        if (info == null) {
25645            return false;
25646        }
25647        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
25648            return false;
25649        }
25650        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
25651        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
25652        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
25653            if (throwIfPermNotDeclared) {
25654                throw new SecurityException("Need to declare " + appOpPermission
25655                        + " to call this api");
25656            } else {
25657                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
25658                return false;
25659            }
25660        }
25661        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
25662            return false;
25663        }
25664        if (mExternalSourcesPolicy != null) {
25665            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
25666            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
25667                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
25668            }
25669        }
25670        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
25671    }
25672
25673    @Override
25674    public ComponentName getInstantAppResolverSettingsComponent() {
25675        return mInstantAppResolverSettingsComponent;
25676    }
25677
25678    @Override
25679    public ComponentName getInstantAppInstallerComponent() {
25680        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25681            return null;
25682        }
25683        return mInstantAppInstallerActivity == null
25684                ? null : mInstantAppInstallerActivity.getComponentName();
25685    }
25686
25687    @Override
25688    public String getInstantAppAndroidId(String packageName, int userId) {
25689        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
25690                "getInstantAppAndroidId");
25691        enforceCrossUserPermission(Binder.getCallingUid(), userId,
25692                true /* requireFullPermission */, false /* checkShell */,
25693                "getInstantAppAndroidId");
25694        // Make sure the target is an Instant App.
25695        if (!isInstantApp(packageName, userId)) {
25696            return null;
25697        }
25698        synchronized (mPackages) {
25699            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
25700        }
25701    }
25702
25703    boolean canHaveOatDir(String packageName) {
25704        synchronized (mPackages) {
25705            PackageParser.Package p = mPackages.get(packageName);
25706            if (p == null) {
25707                return false;
25708            }
25709            return p.canHaveOatDir();
25710        }
25711    }
25712
25713    private String getOatDir(PackageParser.Package pkg) {
25714        if (!pkg.canHaveOatDir()) {
25715            return null;
25716        }
25717        File codePath = new File(pkg.codePath);
25718        if (codePath.isDirectory()) {
25719            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
25720        }
25721        return null;
25722    }
25723
25724    void deleteOatArtifactsOfPackage(String packageName) {
25725        final String[] instructionSets;
25726        final List<String> codePaths;
25727        final String oatDir;
25728        final PackageParser.Package pkg;
25729        synchronized (mPackages) {
25730            pkg = mPackages.get(packageName);
25731        }
25732        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
25733        codePaths = pkg.getAllCodePaths();
25734        oatDir = getOatDir(pkg);
25735
25736        for (String codePath : codePaths) {
25737            for (String isa : instructionSets) {
25738                try {
25739                    mInstaller.deleteOdex(codePath, isa, oatDir);
25740                } catch (InstallerException e) {
25741                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
25742                }
25743            }
25744        }
25745    }
25746
25747    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
25748        Set<String> unusedPackages = new HashSet<>();
25749        long currentTimeInMillis = System.currentTimeMillis();
25750        synchronized (mPackages) {
25751            for (PackageParser.Package pkg : mPackages.values()) {
25752                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
25753                if (ps == null) {
25754                    continue;
25755                }
25756                PackageDexUsage.PackageUseInfo packageUseInfo =
25757                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
25758                if (PackageManagerServiceUtils
25759                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
25760                                downgradeTimeThresholdMillis, packageUseInfo,
25761                                pkg.getLatestPackageUseTimeInMills(),
25762                                pkg.getLatestForegroundPackageUseTimeInMills())) {
25763                    unusedPackages.add(pkg.packageName);
25764                }
25765            }
25766        }
25767        return unusedPackages;
25768    }
25769}
25770
25771interface PackageSender {
25772    void sendPackageBroadcast(final String action, final String pkg,
25773        final Bundle extras, final int flags, final String targetPkg,
25774        final IIntentReceiver finishedReceiver, final int[] userIds);
25775    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
25776        boolean includeStopped, int appId, int... userIds);
25777}
25778