PackageManagerService.java revision 74629e3183b275b87e54387ff620cfa377d314b6
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.system.OsConstants.O_CREAT;
89import static android.system.OsConstants.O_RDWR;
90
91import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
92import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
93import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
94import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
95import static com.android.internal.util.ArrayUtils.appendInt;
96import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
97import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
98import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
99import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
100import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
102import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
103import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
104import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
105import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
106
107import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
108
109import android.Manifest;
110import android.annotation.IntDef;
111import android.annotation.NonNull;
112import android.annotation.Nullable;
113import android.app.ActivityManager;
114import android.app.AppOpsManager;
115import android.app.IActivityManager;
116import android.app.ResourcesManager;
117import android.app.admin.IDevicePolicyManager;
118import android.app.admin.SecurityLog;
119import android.app.backup.IBackupManager;
120import android.content.BroadcastReceiver;
121import android.content.ComponentName;
122import android.content.ContentResolver;
123import android.content.Context;
124import android.content.IIntentReceiver;
125import android.content.Intent;
126import android.content.IntentFilter;
127import android.content.IntentSender;
128import android.content.IntentSender.SendIntentException;
129import android.content.ServiceConnection;
130import android.content.pm.ActivityInfo;
131import android.content.pm.ApplicationInfo;
132import android.content.pm.AppsQueryHelper;
133import android.content.pm.AuxiliaryResolveInfo;
134import android.content.pm.ChangedPackages;
135import android.content.pm.ComponentInfo;
136import android.content.pm.FallbackCategoryProvider;
137import android.content.pm.FeatureInfo;
138import android.content.pm.IDexModuleRegisterCallback;
139import android.content.pm.IOnPermissionsChangeListener;
140import android.content.pm.IPackageDataObserver;
141import android.content.pm.IPackageDeleteObserver;
142import android.content.pm.IPackageDeleteObserver2;
143import android.content.pm.IPackageInstallObserver2;
144import android.content.pm.IPackageInstaller;
145import android.content.pm.IPackageManager;
146import android.content.pm.IPackageManagerNative;
147import android.content.pm.IPackageMoveObserver;
148import android.content.pm.IPackageStatsObserver;
149import android.content.pm.InstantAppInfo;
150import android.content.pm.InstantAppRequest;
151import android.content.pm.InstantAppResolveInfo;
152import android.content.pm.InstrumentationInfo;
153import android.content.pm.IntentFilterVerificationInfo;
154import android.content.pm.KeySet;
155import android.content.pm.PackageCleanItem;
156import android.content.pm.PackageInfo;
157import android.content.pm.PackageInfoLite;
158import android.content.pm.PackageInstaller;
159import android.content.pm.PackageManager;
160import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
161import android.content.pm.PackageManagerInternal;
162import android.content.pm.PackageParser;
163import android.content.pm.PackageParser.ActivityIntentInfo;
164import android.content.pm.PackageParser.PackageLite;
165import android.content.pm.PackageParser.PackageParserException;
166import android.content.pm.PackageStats;
167import android.content.pm.PackageUserState;
168import android.content.pm.ParceledListSlice;
169import android.content.pm.PermissionGroupInfo;
170import android.content.pm.PermissionInfo;
171import android.content.pm.ProviderInfo;
172import android.content.pm.ResolveInfo;
173import android.content.pm.ServiceInfo;
174import android.content.pm.SharedLibraryInfo;
175import android.content.pm.Signature;
176import android.content.pm.UserInfo;
177import android.content.pm.VerifierDeviceIdentity;
178import android.content.pm.VerifierInfo;
179import android.content.pm.VersionedPackage;
180import android.content.res.Resources;
181import android.database.ContentObserver;
182import android.graphics.Bitmap;
183import android.hardware.display.DisplayManager;
184import android.net.Uri;
185import android.os.Binder;
186import android.os.Build;
187import android.os.Bundle;
188import android.os.Debug;
189import android.os.Environment;
190import android.os.Environment.UserEnvironment;
191import android.os.FileUtils;
192import android.os.Handler;
193import android.os.IBinder;
194import android.os.Looper;
195import android.os.Message;
196import android.os.Parcel;
197import android.os.ParcelFileDescriptor;
198import android.os.PatternMatcher;
199import android.os.Process;
200import android.os.RemoteCallbackList;
201import android.os.RemoteException;
202import android.os.ResultReceiver;
203import android.os.SELinux;
204import android.os.ServiceManager;
205import android.os.ShellCallback;
206import android.os.SystemClock;
207import android.os.SystemProperties;
208import android.os.Trace;
209import android.os.UserHandle;
210import android.os.UserManager;
211import android.os.UserManagerInternal;
212import android.os.storage.IStorageManager;
213import android.os.storage.StorageEventListener;
214import android.os.storage.StorageManager;
215import android.os.storage.StorageManagerInternal;
216import android.os.storage.VolumeInfo;
217import android.os.storage.VolumeRecord;
218import android.provider.Settings.Global;
219import android.provider.Settings.Secure;
220import android.security.KeyStore;
221import android.security.SystemKeyStore;
222import android.service.pm.PackageServiceDumpProto;
223import android.system.ErrnoException;
224import android.system.Os;
225import android.text.TextUtils;
226import android.text.format.DateUtils;
227import android.util.ArrayMap;
228import android.util.ArraySet;
229import android.util.Base64;
230import android.util.BootTimingsTraceLog;
231import android.util.DisplayMetrics;
232import android.util.EventLog;
233import android.util.ExceptionUtils;
234import android.util.Log;
235import android.util.LogPrinter;
236import android.util.MathUtils;
237import android.util.PackageUtils;
238import android.util.Pair;
239import android.util.PrintStreamPrinter;
240import android.util.Slog;
241import android.util.SparseArray;
242import android.util.SparseBooleanArray;
243import android.util.SparseIntArray;
244import android.util.Xml;
245import android.util.jar.StrictJarFile;
246import android.util.proto.ProtoOutputStream;
247import android.view.Display;
248
249import com.android.internal.R;
250import com.android.internal.annotations.GuardedBy;
251import com.android.internal.app.IMediaContainerService;
252import com.android.internal.app.ResolverActivity;
253import com.android.internal.content.NativeLibraryHelper;
254import com.android.internal.content.PackageHelper;
255import com.android.internal.logging.MetricsLogger;
256import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
257import com.android.internal.os.IParcelFileDescriptorFactory;
258import com.android.internal.os.RoSystemProperties;
259import com.android.internal.os.SomeArgs;
260import com.android.internal.os.Zygote;
261import com.android.internal.telephony.CarrierAppUtils;
262import com.android.internal.util.ArrayUtils;
263import com.android.internal.util.ConcurrentUtils;
264import com.android.internal.util.DumpUtils;
265import com.android.internal.util.FastPrintWriter;
266import com.android.internal.util.FastXmlSerializer;
267import com.android.internal.util.IndentingPrintWriter;
268import com.android.internal.util.Preconditions;
269import com.android.internal.util.XmlUtils;
270import com.android.server.AttributeCache;
271import com.android.server.DeviceIdleController;
272import com.android.server.EventLogTags;
273import com.android.server.FgThread;
274import com.android.server.IntentResolver;
275import com.android.server.LocalServices;
276import com.android.server.LockGuard;
277import com.android.server.ServiceThread;
278import com.android.server.SystemConfig;
279import com.android.server.SystemServerInitThreadPool;
280import com.android.server.Watchdog;
281import com.android.server.net.NetworkPolicyManagerInternal;
282import com.android.server.pm.Installer.InstallerException;
283import com.android.server.pm.PermissionsState.PermissionState;
284import com.android.server.pm.Settings.DatabaseVersion;
285import com.android.server.pm.Settings.VersionInfo;
286import com.android.server.pm.dex.DexManager;
287import com.android.server.pm.dex.DexoptOptions;
288import com.android.server.pm.dex.PackageDexUsage;
289import com.android.server.storage.DeviceStorageMonitorInternal;
290
291import dalvik.system.CloseGuard;
292import dalvik.system.DexFile;
293import dalvik.system.VMRuntime;
294
295import libcore.io.IoUtils;
296import libcore.io.Streams;
297import libcore.util.EmptyArray;
298
299import org.xmlpull.v1.XmlPullParser;
300import org.xmlpull.v1.XmlPullParserException;
301import org.xmlpull.v1.XmlSerializer;
302
303import java.io.BufferedOutputStream;
304import java.io.BufferedReader;
305import java.io.ByteArrayInputStream;
306import java.io.ByteArrayOutputStream;
307import java.io.File;
308import java.io.FileDescriptor;
309import java.io.FileInputStream;
310import java.io.FileOutputStream;
311import java.io.FileReader;
312import java.io.FilenameFilter;
313import java.io.IOException;
314import java.io.InputStream;
315import java.io.OutputStream;
316import java.io.PrintWriter;
317import java.lang.annotation.Retention;
318import java.lang.annotation.RetentionPolicy;
319import java.nio.charset.StandardCharsets;
320import java.security.DigestInputStream;
321import java.security.MessageDigest;
322import java.security.NoSuchAlgorithmException;
323import java.security.PublicKey;
324import java.security.SecureRandom;
325import java.security.cert.Certificate;
326import java.security.cert.CertificateEncodingException;
327import java.security.cert.CertificateException;
328import java.text.SimpleDateFormat;
329import java.util.ArrayList;
330import java.util.Arrays;
331import java.util.Collection;
332import java.util.Collections;
333import java.util.Comparator;
334import java.util.Date;
335import java.util.HashMap;
336import java.util.HashSet;
337import java.util.Iterator;
338import java.util.List;
339import java.util.Map;
340import java.util.Objects;
341import java.util.Set;
342import java.util.concurrent.CountDownLatch;
343import java.util.concurrent.Future;
344import java.util.concurrent.TimeUnit;
345import java.util.concurrent.atomic.AtomicBoolean;
346import java.util.concurrent.atomic.AtomicInteger;
347import java.util.zip.GZIPInputStream;
348
349/**
350 * Keep track of all those APKs everywhere.
351 * <p>
352 * Internally there are two important locks:
353 * <ul>
354 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
355 * and other related state. It is a fine-grained lock that should only be held
356 * momentarily, as it's one of the most contended locks in the system.
357 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
358 * operations typically involve heavy lifting of application data on disk. Since
359 * {@code installd} is single-threaded, and it's operations can often be slow,
360 * this lock should never be acquired while already holding {@link #mPackages}.
361 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
362 * holding {@link #mInstallLock}.
363 * </ul>
364 * Many internal methods rely on the caller to hold the appropriate locks, and
365 * this contract is expressed through method name suffixes:
366 * <ul>
367 * <li>fooLI(): the caller must hold {@link #mInstallLock}
368 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
369 * being modified must be frozen
370 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
371 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
372 * </ul>
373 * <p>
374 * Because this class is very central to the platform's security; please run all
375 * CTS and unit tests whenever making modifications:
376 *
377 * <pre>
378 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
379 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
380 * </pre>
381 */
382public class PackageManagerService extends IPackageManager.Stub
383        implements PackageSender {
384    static final String TAG = "PackageManager";
385    static final boolean DEBUG_SETTINGS = false;
386    static final boolean DEBUG_PREFERRED = false;
387    static final boolean DEBUG_UPGRADE = false;
388    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
389    private static final boolean DEBUG_BACKUP = false;
390    private static final boolean DEBUG_INSTALL = false;
391    private static final boolean DEBUG_REMOVE = false;
392    private static final boolean DEBUG_BROADCASTS = false;
393    private static final boolean DEBUG_SHOW_INFO = false;
394    private static final boolean DEBUG_PACKAGE_INFO = false;
395    private static final boolean DEBUG_INTENT_MATCHING = false;
396    private static final boolean DEBUG_PACKAGE_SCANNING = false;
397    private static final boolean DEBUG_VERIFY = false;
398    private static final boolean DEBUG_FILTERS = false;
399    private static final boolean DEBUG_PERMISSIONS = false;
400    private static final boolean DEBUG_SHARED_LIBRARIES = false;
401    private static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
402
403    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
404    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
405    // user, but by default initialize to this.
406    public static final boolean DEBUG_DEXOPT = false;
407
408    private static final boolean DEBUG_ABI_SELECTION = false;
409    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
410    private static final boolean DEBUG_TRIAGED_MISSING = false;
411    private static final boolean DEBUG_APP_DATA = false;
412
413    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
414    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
415
416    private static final boolean HIDE_EPHEMERAL_APIS = false;
417
418    private static final boolean ENABLE_FREE_CACHE_V2 =
419            SystemProperties.getBoolean("fw.free_cache_v2", true);
420
421    private static final int RADIO_UID = Process.PHONE_UID;
422    private static final int LOG_UID = Process.LOG_UID;
423    private static final int NFC_UID = Process.NFC_UID;
424    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
425    private static final int SHELL_UID = Process.SHELL_UID;
426
427    // Cap the size of permission trees that 3rd party apps can define
428    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
429
430    // Suffix used during package installation when copying/moving
431    // package apks to install directory.
432    private static final String INSTALL_PACKAGE_SUFFIX = "-";
433
434    static final int SCAN_NO_DEX = 1<<1;
435    static final int SCAN_FORCE_DEX = 1<<2;
436    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
437    static final int SCAN_NEW_INSTALL = 1<<4;
438    static final int SCAN_UPDATE_TIME = 1<<5;
439    static final int SCAN_BOOTING = 1<<6;
440    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
441    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
442    static final int SCAN_REPLACING = 1<<9;
443    static final int SCAN_REQUIRE_KNOWN = 1<<10;
444    static final int SCAN_MOVE = 1<<11;
445    static final int SCAN_INITIAL = 1<<12;
446    static final int SCAN_CHECK_ONLY = 1<<13;
447    static final int SCAN_DONT_KILL_APP = 1<<14;
448    static final int SCAN_IGNORE_FROZEN = 1<<15;
449    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
450    static final int SCAN_AS_INSTANT_APP = 1<<17;
451    static final int SCAN_AS_FULL_APP = 1<<18;
452    static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<19;
453    /** Should not be with the scan flags */
454    static final int FLAGS_REMOVE_CHATTY = 1<<31;
455
456    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
457    /** Extension of the compressed packages */
458    private final static String COMPRESSED_EXTENSION = ".gz";
459
460    private static final int[] EMPTY_INT_ARRAY = new int[0];
461
462    private static final int TYPE_UNKNOWN = 0;
463    private static final int TYPE_ACTIVITY = 1;
464    private static final int TYPE_RECEIVER = 2;
465    private static final int TYPE_SERVICE = 3;
466    private static final int TYPE_PROVIDER = 4;
467    @IntDef(prefix = { "TYPE_" }, value = {
468            TYPE_UNKNOWN,
469            TYPE_ACTIVITY,
470            TYPE_RECEIVER,
471            TYPE_SERVICE,
472            TYPE_PROVIDER,
473    })
474    @Retention(RetentionPolicy.SOURCE)
475    public @interface ComponentType {}
476
477    /**
478     * Timeout (in milliseconds) after which the watchdog should declare that
479     * our handler thread is wedged.  The usual default for such things is one
480     * minute but we sometimes do very lengthy I/O operations on this thread,
481     * such as installing multi-gigabyte applications, so ours needs to be longer.
482     */
483    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
484
485    /**
486     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
487     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
488     * settings entry if available, otherwise we use the hardcoded default.  If it's been
489     * more than this long since the last fstrim, we force one during the boot sequence.
490     *
491     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
492     * one gets run at the next available charging+idle time.  This final mandatory
493     * no-fstrim check kicks in only of the other scheduling criteria is never met.
494     */
495    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
496
497    /**
498     * Whether verification is enabled by default.
499     */
500    private static final boolean DEFAULT_VERIFY_ENABLE = true;
501
502    /**
503     * The default maximum time to wait for the verification agent to return in
504     * milliseconds.
505     */
506    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
507
508    /**
509     * The default response for package verification timeout.
510     *
511     * This can be either PackageManager.VERIFICATION_ALLOW or
512     * PackageManager.VERIFICATION_REJECT.
513     */
514    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
515
516    static final String PLATFORM_PACKAGE_NAME = "android";
517
518    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
519
520    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
521            DEFAULT_CONTAINER_PACKAGE,
522            "com.android.defcontainer.DefaultContainerService");
523
524    private static final String KILL_APP_REASON_GIDS_CHANGED =
525            "permission grant or revoke changed gids";
526
527    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
528            "permissions revoked";
529
530    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
531
532    private static final String PACKAGE_SCHEME = "package";
533
534    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
535
536    /** Permission grant: not grant the permission. */
537    private static final int GRANT_DENIED = 1;
538
539    /** Permission grant: grant the permission as an install permission. */
540    private static final int GRANT_INSTALL = 2;
541
542    /** Permission grant: grant the permission as a runtime one. */
543    private static final int GRANT_RUNTIME = 3;
544
545    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
546    private static final int GRANT_UPGRADE = 4;
547
548    /** Canonical intent used to identify what counts as a "web browser" app */
549    private static final Intent sBrowserIntent;
550    static {
551        sBrowserIntent = new Intent();
552        sBrowserIntent.setAction(Intent.ACTION_VIEW);
553        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
554        sBrowserIntent.setData(Uri.parse("http:"));
555    }
556
557    /**
558     * The set of all protected actions [i.e. those actions for which a high priority
559     * intent filter is disallowed].
560     */
561    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
562    static {
563        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
564        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
565        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
566        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
567    }
568
569    // Compilation reasons.
570    public static final int REASON_FIRST_BOOT = 0;
571    public static final int REASON_BOOT = 1;
572    public static final int REASON_INSTALL = 2;
573    public static final int REASON_BACKGROUND_DEXOPT = 3;
574    public static final int REASON_AB_OTA = 4;
575    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
576
577    public static final int REASON_LAST = REASON_INACTIVE_PACKAGE_DOWNGRADE;
578
579    /** All dangerous permission names in the same order as the events in MetricsEvent */
580    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
581            Manifest.permission.READ_CALENDAR,
582            Manifest.permission.WRITE_CALENDAR,
583            Manifest.permission.CAMERA,
584            Manifest.permission.READ_CONTACTS,
585            Manifest.permission.WRITE_CONTACTS,
586            Manifest.permission.GET_ACCOUNTS,
587            Manifest.permission.ACCESS_FINE_LOCATION,
588            Manifest.permission.ACCESS_COARSE_LOCATION,
589            Manifest.permission.RECORD_AUDIO,
590            Manifest.permission.READ_PHONE_STATE,
591            Manifest.permission.CALL_PHONE,
592            Manifest.permission.READ_CALL_LOG,
593            Manifest.permission.WRITE_CALL_LOG,
594            Manifest.permission.ADD_VOICEMAIL,
595            Manifest.permission.USE_SIP,
596            Manifest.permission.PROCESS_OUTGOING_CALLS,
597            Manifest.permission.READ_CELL_BROADCASTS,
598            Manifest.permission.BODY_SENSORS,
599            Manifest.permission.SEND_SMS,
600            Manifest.permission.RECEIVE_SMS,
601            Manifest.permission.READ_SMS,
602            Manifest.permission.RECEIVE_WAP_PUSH,
603            Manifest.permission.RECEIVE_MMS,
604            Manifest.permission.READ_EXTERNAL_STORAGE,
605            Manifest.permission.WRITE_EXTERNAL_STORAGE,
606            Manifest.permission.READ_PHONE_NUMBERS,
607            Manifest.permission.ANSWER_PHONE_CALLS);
608
609
610    /**
611     * Version number for the package parser cache. Increment this whenever the format or
612     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
613     */
614    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
615
616    /**
617     * Whether the package parser cache is enabled.
618     */
619    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
620
621    final ServiceThread mHandlerThread;
622
623    final PackageHandler mHandler;
624
625    private final ProcessLoggingHandler mProcessLoggingHandler;
626
627    /**
628     * Messages for {@link #mHandler} that need to wait for system ready before
629     * being dispatched.
630     */
631    private ArrayList<Message> mPostSystemReadyMessages;
632
633    final int mSdkVersion = Build.VERSION.SDK_INT;
634
635    final Context mContext;
636    final boolean mFactoryTest;
637    final boolean mOnlyCore;
638    final DisplayMetrics mMetrics;
639    final int mDefParseFlags;
640    final String[] mSeparateProcesses;
641    final boolean mIsUpgrade;
642    final boolean mIsPreNUpgrade;
643    final boolean mIsPreNMR1Upgrade;
644
645    // Have we told the Activity Manager to whitelist the default container service by uid yet?
646    @GuardedBy("mPackages")
647    boolean mDefaultContainerWhitelisted = false;
648
649    @GuardedBy("mPackages")
650    private boolean mDexOptDialogShown;
651
652    /** The location for ASEC container files on internal storage. */
653    final String mAsecInternalPath;
654
655    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
656    // LOCK HELD.  Can be called with mInstallLock held.
657    @GuardedBy("mInstallLock")
658    final Installer mInstaller;
659
660    /** Directory where installed third-party apps stored */
661    final File mAppInstallDir;
662
663    /**
664     * Directory to which applications installed internally have their
665     * 32 bit native libraries copied.
666     */
667    private File mAppLib32InstallDir;
668
669    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
670    // apps.
671    final File mDrmAppPrivateInstallDir;
672
673    // ----------------------------------------------------------------
674
675    // Lock for state used when installing and doing other long running
676    // operations.  Methods that must be called with this lock held have
677    // the suffix "LI".
678    final Object mInstallLock = new Object();
679
680    // ----------------------------------------------------------------
681
682    // Keys are String (package name), values are Package.  This also serves
683    // as the lock for the global state.  Methods that must be called with
684    // this lock held have the prefix "LP".
685    @GuardedBy("mPackages")
686    final ArrayMap<String, PackageParser.Package> mPackages =
687            new ArrayMap<String, PackageParser.Package>();
688
689    final ArrayMap<String, Set<String>> mKnownCodebase =
690            new ArrayMap<String, Set<String>>();
691
692    // Keys are isolated uids and values are the uid of the application
693    // that created the isolated proccess.
694    @GuardedBy("mPackages")
695    final SparseIntArray mIsolatedOwners = new SparseIntArray();
696
697    /**
698     * Tracks new system packages [received in an OTA] that we expect to
699     * find updated user-installed versions. Keys are package name, values
700     * are package location.
701     */
702    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
703    /**
704     * Tracks high priority intent filters for protected actions. During boot, certain
705     * filter actions are protected and should never be allowed to have a high priority
706     * intent filter for them. However, there is one, and only one exception -- the
707     * setup wizard. It must be able to define a high priority intent filter for these
708     * actions to ensure there are no escapes from the wizard. We need to delay processing
709     * of these during boot as we need to look at all of the system packages in order
710     * to know which component is the setup wizard.
711     */
712    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
713    /**
714     * Whether or not processing protected filters should be deferred.
715     */
716    private boolean mDeferProtectedFilters = true;
717
718    /**
719     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
720     */
721    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
722    /**
723     * Whether or not system app permissions should be promoted from install to runtime.
724     */
725    boolean mPromoteSystemApps;
726
727    @GuardedBy("mPackages")
728    final Settings mSettings;
729
730    /**
731     * Set of package names that are currently "frozen", which means active
732     * surgery is being done on the code/data for that package. The platform
733     * will refuse to launch frozen packages to avoid race conditions.
734     *
735     * @see PackageFreezer
736     */
737    @GuardedBy("mPackages")
738    final ArraySet<String> mFrozenPackages = new ArraySet<>();
739
740    final ProtectedPackages mProtectedPackages;
741
742    @GuardedBy("mLoadedVolumes")
743    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
744
745    boolean mFirstBoot;
746
747    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
748
749    // System configuration read by SystemConfig.
750    final int[] mGlobalGids;
751    final SparseArray<ArraySet<String>> mSystemPermissions;
752    @GuardedBy("mAvailableFeatures")
753    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
754
755    // If mac_permissions.xml was found for seinfo labeling.
756    boolean mFoundPolicyFile;
757
758    private final InstantAppRegistry mInstantAppRegistry;
759
760    @GuardedBy("mPackages")
761    int mChangedPackagesSequenceNumber;
762    /**
763     * List of changed [installed, removed or updated] packages.
764     * mapping from user id -> sequence number -> package name
765     */
766    @GuardedBy("mPackages")
767    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
768    /**
769     * The sequence number of the last change to a package.
770     * mapping from user id -> package name -> sequence number
771     */
772    @GuardedBy("mPackages")
773    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
774
775    class PackageParserCallback implements PackageParser.Callback {
776        @Override public final boolean hasFeature(String feature) {
777            return PackageManagerService.this.hasSystemFeature(feature, 0);
778        }
779
780        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
781                Collection<PackageParser.Package> allPackages, String targetPackageName) {
782            List<PackageParser.Package> overlayPackages = null;
783            for (PackageParser.Package p : allPackages) {
784                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
785                    if (overlayPackages == null) {
786                        overlayPackages = new ArrayList<PackageParser.Package>();
787                    }
788                    overlayPackages.add(p);
789                }
790            }
791            if (overlayPackages != null) {
792                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
793                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
794                        return p1.mOverlayPriority - p2.mOverlayPriority;
795                    }
796                };
797                Collections.sort(overlayPackages, cmp);
798            }
799            return overlayPackages;
800        }
801
802        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
803                String targetPackageName, String targetPath) {
804            if ("android".equals(targetPackageName)) {
805                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
806                // native AssetManager.
807                return null;
808            }
809            List<PackageParser.Package> overlayPackages =
810                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
811            if (overlayPackages == null || overlayPackages.isEmpty()) {
812                return null;
813            }
814            List<String> overlayPathList = null;
815            for (PackageParser.Package overlayPackage : overlayPackages) {
816                if (targetPath == null) {
817                    if (overlayPathList == null) {
818                        overlayPathList = new ArrayList<String>();
819                    }
820                    overlayPathList.add(overlayPackage.baseCodePath);
821                    continue;
822                }
823
824                try {
825                    // Creates idmaps for system to parse correctly the Android manifest of the
826                    // target package.
827                    //
828                    // OverlayManagerService will update each of them with a correct gid from its
829                    // target package app id.
830                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
831                            UserHandle.getSharedAppGid(
832                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
833                    if (overlayPathList == null) {
834                        overlayPathList = new ArrayList<String>();
835                    }
836                    overlayPathList.add(overlayPackage.baseCodePath);
837                } catch (InstallerException e) {
838                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
839                            overlayPackage.baseCodePath);
840                }
841            }
842            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
843        }
844
845        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
846            synchronized (mPackages) {
847                return getStaticOverlayPathsLocked(
848                        mPackages.values(), targetPackageName, targetPath);
849            }
850        }
851
852        @Override public final String[] getOverlayApks(String targetPackageName) {
853            return getStaticOverlayPaths(targetPackageName, null);
854        }
855
856        @Override public final String[] getOverlayPaths(String targetPackageName,
857                String targetPath) {
858            return getStaticOverlayPaths(targetPackageName, targetPath);
859        }
860    };
861
862    class ParallelPackageParserCallback extends PackageParserCallback {
863        List<PackageParser.Package> mOverlayPackages = null;
864
865        void findStaticOverlayPackages() {
866            synchronized (mPackages) {
867                for (PackageParser.Package p : mPackages.values()) {
868                    if (p.mIsStaticOverlay) {
869                        if (mOverlayPackages == null) {
870                            mOverlayPackages = new ArrayList<PackageParser.Package>();
871                        }
872                        mOverlayPackages.add(p);
873                    }
874                }
875            }
876        }
877
878        @Override
879        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
880            // We can trust mOverlayPackages without holding mPackages because package uninstall
881            // can't happen while running parallel parsing.
882            // Moreover holding mPackages on each parsing thread causes dead-lock.
883            return mOverlayPackages == null ? null :
884                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
885        }
886    }
887
888    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
889    final ParallelPackageParserCallback mParallelPackageParserCallback =
890            new ParallelPackageParserCallback();
891
892    public static final class SharedLibraryEntry {
893        public final @Nullable String path;
894        public final @Nullable String apk;
895        public final @NonNull SharedLibraryInfo info;
896
897        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
898                String declaringPackageName, int declaringPackageVersionCode) {
899            path = _path;
900            apk = _apk;
901            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
902                    declaringPackageName, declaringPackageVersionCode), null);
903        }
904    }
905
906    // Currently known shared libraries.
907    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
908    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
909            new ArrayMap<>();
910
911    // All available activities, for your resolving pleasure.
912    final ActivityIntentResolver mActivities =
913            new ActivityIntentResolver();
914
915    // All available receivers, for your resolving pleasure.
916    final ActivityIntentResolver mReceivers =
917            new ActivityIntentResolver();
918
919    // All available services, for your resolving pleasure.
920    final ServiceIntentResolver mServices = new ServiceIntentResolver();
921
922    // All available providers, for your resolving pleasure.
923    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
924
925    // Mapping from provider base names (first directory in content URI codePath)
926    // to the provider information.
927    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
928            new ArrayMap<String, PackageParser.Provider>();
929
930    // Mapping from instrumentation class names to info about them.
931    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
932            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
933
934    // Mapping from permission names to info about them.
935    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
936            new ArrayMap<String, PackageParser.PermissionGroup>();
937
938    // Packages whose data we have transfered into another package, thus
939    // should no longer exist.
940    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
941
942    // Broadcast actions that are only available to the system.
943    @GuardedBy("mProtectedBroadcasts")
944    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
945
946    /** List of packages waiting for verification. */
947    final SparseArray<PackageVerificationState> mPendingVerification
948            = new SparseArray<PackageVerificationState>();
949
950    /** Set of packages associated with each app op permission. */
951    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
952
953    final PackageInstallerService mInstallerService;
954
955    private final PackageDexOptimizer mPackageDexOptimizer;
956    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
957    // is used by other apps).
958    private final DexManager mDexManager;
959
960    private AtomicInteger mNextMoveId = new AtomicInteger();
961    private final MoveCallbacks mMoveCallbacks;
962
963    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
964
965    // Cache of users who need badging.
966    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
967
968    /** Token for keys in mPendingVerification. */
969    private int mPendingVerificationToken = 0;
970
971    volatile boolean mSystemReady;
972    volatile boolean mSafeMode;
973    volatile boolean mHasSystemUidErrors;
974    private volatile boolean mEphemeralAppsDisabled;
975
976    ApplicationInfo mAndroidApplication;
977    final ActivityInfo mResolveActivity = new ActivityInfo();
978    final ResolveInfo mResolveInfo = new ResolveInfo();
979    ComponentName mResolveComponentName;
980    PackageParser.Package mPlatformPackage;
981    ComponentName mCustomResolverComponentName;
982
983    boolean mResolverReplaced = false;
984
985    private final @Nullable ComponentName mIntentFilterVerifierComponent;
986    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
987
988    private int mIntentFilterVerificationToken = 0;
989
990    /** The service connection to the ephemeral resolver */
991    final EphemeralResolverConnection mInstantAppResolverConnection;
992    /** Component used to show resolver settings for Instant Apps */
993    final ComponentName mInstantAppResolverSettingsComponent;
994
995    /** Activity used to install instant applications */
996    ActivityInfo mInstantAppInstallerActivity;
997    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
998
999    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
1000            = new SparseArray<IntentFilterVerificationState>();
1001
1002    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
1003
1004    // List of packages names to keep cached, even if they are uninstalled for all users
1005    private List<String> mKeepUninstalledPackages;
1006
1007    private UserManagerInternal mUserManagerInternal;
1008
1009    private DeviceIdleController.LocalService mDeviceIdleController;
1010
1011    private File mCacheDir;
1012
1013    private ArraySet<String> mPrivappPermissionsViolations;
1014
1015    private Future<?> mPrepareAppDataFuture;
1016
1017    private static class IFVerificationParams {
1018        PackageParser.Package pkg;
1019        boolean replacing;
1020        int userId;
1021        int verifierUid;
1022
1023        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1024                int _userId, int _verifierUid) {
1025            pkg = _pkg;
1026            replacing = _replacing;
1027            userId = _userId;
1028            replacing = _replacing;
1029            verifierUid = _verifierUid;
1030        }
1031    }
1032
1033    private interface IntentFilterVerifier<T extends IntentFilter> {
1034        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1035                                               T filter, String packageName);
1036        void startVerifications(int userId);
1037        void receiveVerificationResponse(int verificationId);
1038    }
1039
1040    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1041        private Context mContext;
1042        private ComponentName mIntentFilterVerifierComponent;
1043        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1044
1045        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1046            mContext = context;
1047            mIntentFilterVerifierComponent = verifierComponent;
1048        }
1049
1050        private String getDefaultScheme() {
1051            return IntentFilter.SCHEME_HTTPS;
1052        }
1053
1054        @Override
1055        public void startVerifications(int userId) {
1056            // Launch verifications requests
1057            int count = mCurrentIntentFilterVerifications.size();
1058            for (int n=0; n<count; n++) {
1059                int verificationId = mCurrentIntentFilterVerifications.get(n);
1060                final IntentFilterVerificationState ivs =
1061                        mIntentFilterVerificationStates.get(verificationId);
1062
1063                String packageName = ivs.getPackageName();
1064
1065                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1066                final int filterCount = filters.size();
1067                ArraySet<String> domainsSet = new ArraySet<>();
1068                for (int m=0; m<filterCount; m++) {
1069                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1070                    domainsSet.addAll(filter.getHostsList());
1071                }
1072                synchronized (mPackages) {
1073                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1074                            packageName, domainsSet) != null) {
1075                        scheduleWriteSettingsLocked();
1076                    }
1077                }
1078                sendVerificationRequest(verificationId, ivs);
1079            }
1080            mCurrentIntentFilterVerifications.clear();
1081        }
1082
1083        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1084            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1085            verificationIntent.putExtra(
1086                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1087                    verificationId);
1088            verificationIntent.putExtra(
1089                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1090                    getDefaultScheme());
1091            verificationIntent.putExtra(
1092                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1093                    ivs.getHostsString());
1094            verificationIntent.putExtra(
1095                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1096                    ivs.getPackageName());
1097            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1098            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1099
1100            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1101            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1102                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1103                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1104
1105            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1106            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1107                    "Sending IntentFilter verification broadcast");
1108        }
1109
1110        public void receiveVerificationResponse(int verificationId) {
1111            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1112
1113            final boolean verified = ivs.isVerified();
1114
1115            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1116            final int count = filters.size();
1117            if (DEBUG_DOMAIN_VERIFICATION) {
1118                Slog.i(TAG, "Received verification response " + verificationId
1119                        + " for " + count + " filters, verified=" + verified);
1120            }
1121            for (int n=0; n<count; n++) {
1122                PackageParser.ActivityIntentInfo filter = filters.get(n);
1123                filter.setVerified(verified);
1124
1125                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1126                        + " verified with result:" + verified + " and hosts:"
1127                        + ivs.getHostsString());
1128            }
1129
1130            mIntentFilterVerificationStates.remove(verificationId);
1131
1132            final String packageName = ivs.getPackageName();
1133            IntentFilterVerificationInfo ivi = null;
1134
1135            synchronized (mPackages) {
1136                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1137            }
1138            if (ivi == null) {
1139                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1140                        + verificationId + " packageName:" + packageName);
1141                return;
1142            }
1143            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1144                    "Updating IntentFilterVerificationInfo for package " + packageName
1145                            +" verificationId:" + verificationId);
1146
1147            synchronized (mPackages) {
1148                if (verified) {
1149                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1150                } else {
1151                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1152                }
1153                scheduleWriteSettingsLocked();
1154
1155                final int userId = ivs.getUserId();
1156                if (userId != UserHandle.USER_ALL) {
1157                    final int userStatus =
1158                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1159
1160                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1161                    boolean needUpdate = false;
1162
1163                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1164                    // already been set by the User thru the Disambiguation dialog
1165                    switch (userStatus) {
1166                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1167                            if (verified) {
1168                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1169                            } else {
1170                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1171                            }
1172                            needUpdate = true;
1173                            break;
1174
1175                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1176                            if (verified) {
1177                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1178                                needUpdate = true;
1179                            }
1180                            break;
1181
1182                        default:
1183                            // Nothing to do
1184                    }
1185
1186                    if (needUpdate) {
1187                        mSettings.updateIntentFilterVerificationStatusLPw(
1188                                packageName, updatedStatus, userId);
1189                        scheduleWritePackageRestrictionsLocked(userId);
1190                    }
1191                }
1192            }
1193        }
1194
1195        @Override
1196        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1197                    ActivityIntentInfo filter, String packageName) {
1198            if (!hasValidDomains(filter)) {
1199                return false;
1200            }
1201            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1202            if (ivs == null) {
1203                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1204                        packageName);
1205            }
1206            if (DEBUG_DOMAIN_VERIFICATION) {
1207                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1208            }
1209            ivs.addFilter(filter);
1210            return true;
1211        }
1212
1213        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1214                int userId, int verificationId, String packageName) {
1215            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1216                    verifierUid, userId, packageName);
1217            ivs.setPendingState();
1218            synchronized (mPackages) {
1219                mIntentFilterVerificationStates.append(verificationId, ivs);
1220                mCurrentIntentFilterVerifications.add(verificationId);
1221            }
1222            return ivs;
1223        }
1224    }
1225
1226    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1227        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1228                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1229                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1230    }
1231
1232    // Set of pending broadcasts for aggregating enable/disable of components.
1233    static class PendingPackageBroadcasts {
1234        // for each user id, a map of <package name -> components within that package>
1235        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1236
1237        public PendingPackageBroadcasts() {
1238            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1239        }
1240
1241        public ArrayList<String> get(int userId, String packageName) {
1242            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1243            return packages.get(packageName);
1244        }
1245
1246        public void put(int userId, String packageName, ArrayList<String> components) {
1247            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1248            packages.put(packageName, components);
1249        }
1250
1251        public void remove(int userId, String packageName) {
1252            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1253            if (packages != null) {
1254                packages.remove(packageName);
1255            }
1256        }
1257
1258        public void remove(int userId) {
1259            mUidMap.remove(userId);
1260        }
1261
1262        public int userIdCount() {
1263            return mUidMap.size();
1264        }
1265
1266        public int userIdAt(int n) {
1267            return mUidMap.keyAt(n);
1268        }
1269
1270        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1271            return mUidMap.get(userId);
1272        }
1273
1274        public int size() {
1275            // total number of pending broadcast entries across all userIds
1276            int num = 0;
1277            for (int i = 0; i< mUidMap.size(); i++) {
1278                num += mUidMap.valueAt(i).size();
1279            }
1280            return num;
1281        }
1282
1283        public void clear() {
1284            mUidMap.clear();
1285        }
1286
1287        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1288            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1289            if (map == null) {
1290                map = new ArrayMap<String, ArrayList<String>>();
1291                mUidMap.put(userId, map);
1292            }
1293            return map;
1294        }
1295    }
1296    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1297
1298    // Service Connection to remote media container service to copy
1299    // package uri's from external media onto secure containers
1300    // or internal storage.
1301    private IMediaContainerService mContainerService = null;
1302
1303    static final int SEND_PENDING_BROADCAST = 1;
1304    static final int MCS_BOUND = 3;
1305    static final int END_COPY = 4;
1306    static final int INIT_COPY = 5;
1307    static final int MCS_UNBIND = 6;
1308    static final int START_CLEANING_PACKAGE = 7;
1309    static final int FIND_INSTALL_LOC = 8;
1310    static final int POST_INSTALL = 9;
1311    static final int MCS_RECONNECT = 10;
1312    static final int MCS_GIVE_UP = 11;
1313    static final int UPDATED_MEDIA_STATUS = 12;
1314    static final int WRITE_SETTINGS = 13;
1315    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1316    static final int PACKAGE_VERIFIED = 15;
1317    static final int CHECK_PENDING_VERIFICATION = 16;
1318    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1319    static final int INTENT_FILTER_VERIFIED = 18;
1320    static final int WRITE_PACKAGE_LIST = 19;
1321    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1322
1323    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1324
1325    // Delay time in millisecs
1326    static final int BROADCAST_DELAY = 10 * 1000;
1327
1328    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1329            2 * 60 * 60 * 1000L; /* two hours */
1330
1331    static UserManagerService sUserManager;
1332
1333    // Stores a list of users whose package restrictions file needs to be updated
1334    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1335
1336    final private DefaultContainerConnection mDefContainerConn =
1337            new DefaultContainerConnection();
1338    class DefaultContainerConnection implements ServiceConnection {
1339        public void onServiceConnected(ComponentName name, IBinder service) {
1340            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1341            final IMediaContainerService imcs = IMediaContainerService.Stub
1342                    .asInterface(Binder.allowBlocking(service));
1343            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1344        }
1345
1346        public void onServiceDisconnected(ComponentName name) {
1347            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1348        }
1349    }
1350
1351    // Recordkeeping of restore-after-install operations that are currently in flight
1352    // between the Package Manager and the Backup Manager
1353    static class PostInstallData {
1354        public InstallArgs args;
1355        public PackageInstalledInfo res;
1356
1357        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1358            args = _a;
1359            res = _r;
1360        }
1361    }
1362
1363    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1364    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1365
1366    // XML tags for backup/restore of various bits of state
1367    private static final String TAG_PREFERRED_BACKUP = "pa";
1368    private static final String TAG_DEFAULT_APPS = "da";
1369    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1370
1371    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1372    private static final String TAG_ALL_GRANTS = "rt-grants";
1373    private static final String TAG_GRANT = "grant";
1374    private static final String ATTR_PACKAGE_NAME = "pkg";
1375
1376    private static final String TAG_PERMISSION = "perm";
1377    private static final String ATTR_PERMISSION_NAME = "name";
1378    private static final String ATTR_IS_GRANTED = "g";
1379    private static final String ATTR_USER_SET = "set";
1380    private static final String ATTR_USER_FIXED = "fixed";
1381    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1382
1383    // System/policy permission grants are not backed up
1384    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1385            FLAG_PERMISSION_POLICY_FIXED
1386            | FLAG_PERMISSION_SYSTEM_FIXED
1387            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1388
1389    // And we back up these user-adjusted states
1390    private static final int USER_RUNTIME_GRANT_MASK =
1391            FLAG_PERMISSION_USER_SET
1392            | FLAG_PERMISSION_USER_FIXED
1393            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1394
1395    final @Nullable String mRequiredVerifierPackage;
1396    final @NonNull String mRequiredInstallerPackage;
1397    final @NonNull String mRequiredUninstallerPackage;
1398    final @Nullable String mSetupWizardPackage;
1399    final @Nullable String mStorageManagerPackage;
1400    final @NonNull String mServicesSystemSharedLibraryPackageName;
1401    final @NonNull String mSharedSystemSharedLibraryPackageName;
1402
1403    final boolean mPermissionReviewRequired;
1404
1405    private final PackageUsage mPackageUsage = new PackageUsage();
1406    private final CompilerStats mCompilerStats = new CompilerStats();
1407
1408    class PackageHandler extends Handler {
1409        private boolean mBound = false;
1410        final ArrayList<HandlerParams> mPendingInstalls =
1411            new ArrayList<HandlerParams>();
1412
1413        private boolean connectToService() {
1414            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1415                    " DefaultContainerService");
1416            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1417            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1418            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1419                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1420                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1421                mBound = true;
1422                return true;
1423            }
1424            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1425            return false;
1426        }
1427
1428        private void disconnectService() {
1429            mContainerService = null;
1430            mBound = false;
1431            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1432            mContext.unbindService(mDefContainerConn);
1433            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1434        }
1435
1436        PackageHandler(Looper looper) {
1437            super(looper);
1438        }
1439
1440        public void handleMessage(Message msg) {
1441            try {
1442                doHandleMessage(msg);
1443            } finally {
1444                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1445            }
1446        }
1447
1448        void doHandleMessage(Message msg) {
1449            switch (msg.what) {
1450                case INIT_COPY: {
1451                    HandlerParams params = (HandlerParams) msg.obj;
1452                    int idx = mPendingInstalls.size();
1453                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1454                    // If a bind was already initiated we dont really
1455                    // need to do anything. The pending install
1456                    // will be processed later on.
1457                    if (!mBound) {
1458                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1459                                System.identityHashCode(mHandler));
1460                        // If this is the only one pending we might
1461                        // have to bind to the service again.
1462                        if (!connectToService()) {
1463                            Slog.e(TAG, "Failed to bind to media container service");
1464                            params.serviceError();
1465                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1466                                    System.identityHashCode(mHandler));
1467                            if (params.traceMethod != null) {
1468                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1469                                        params.traceCookie);
1470                            }
1471                            return;
1472                        } else {
1473                            // Once we bind to the service, the first
1474                            // pending request will be processed.
1475                            mPendingInstalls.add(idx, params);
1476                        }
1477                    } else {
1478                        mPendingInstalls.add(idx, params);
1479                        // Already bound to the service. Just make
1480                        // sure we trigger off processing the first request.
1481                        if (idx == 0) {
1482                            mHandler.sendEmptyMessage(MCS_BOUND);
1483                        }
1484                    }
1485                    break;
1486                }
1487                case MCS_BOUND: {
1488                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1489                    if (msg.obj != null) {
1490                        mContainerService = (IMediaContainerService) msg.obj;
1491                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1492                                System.identityHashCode(mHandler));
1493                    }
1494                    if (mContainerService == null) {
1495                        if (!mBound) {
1496                            // Something seriously wrong since we are not bound and we are not
1497                            // waiting for connection. Bail out.
1498                            Slog.e(TAG, "Cannot bind to media container service");
1499                            for (HandlerParams params : mPendingInstalls) {
1500                                // Indicate service bind error
1501                                params.serviceError();
1502                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1503                                        System.identityHashCode(params));
1504                                if (params.traceMethod != null) {
1505                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1506                                            params.traceMethod, params.traceCookie);
1507                                }
1508                                return;
1509                            }
1510                            mPendingInstalls.clear();
1511                        } else {
1512                            Slog.w(TAG, "Waiting to connect to media container service");
1513                        }
1514                    } else if (mPendingInstalls.size() > 0) {
1515                        HandlerParams params = mPendingInstalls.get(0);
1516                        if (params != null) {
1517                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1518                                    System.identityHashCode(params));
1519                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1520                            if (params.startCopy()) {
1521                                // We are done...  look for more work or to
1522                                // go idle.
1523                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1524                                        "Checking for more work or unbind...");
1525                                // Delete pending install
1526                                if (mPendingInstalls.size() > 0) {
1527                                    mPendingInstalls.remove(0);
1528                                }
1529                                if (mPendingInstalls.size() == 0) {
1530                                    if (mBound) {
1531                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1532                                                "Posting delayed MCS_UNBIND");
1533                                        removeMessages(MCS_UNBIND);
1534                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1535                                        // Unbind after a little delay, to avoid
1536                                        // continual thrashing.
1537                                        sendMessageDelayed(ubmsg, 10000);
1538                                    }
1539                                } else {
1540                                    // There are more pending requests in queue.
1541                                    // Just post MCS_BOUND message to trigger processing
1542                                    // of next pending install.
1543                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1544                                            "Posting MCS_BOUND for next work");
1545                                    mHandler.sendEmptyMessage(MCS_BOUND);
1546                                }
1547                            }
1548                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1549                        }
1550                    } else {
1551                        // Should never happen ideally.
1552                        Slog.w(TAG, "Empty queue");
1553                    }
1554                    break;
1555                }
1556                case MCS_RECONNECT: {
1557                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1558                    if (mPendingInstalls.size() > 0) {
1559                        if (mBound) {
1560                            disconnectService();
1561                        }
1562                        if (!connectToService()) {
1563                            Slog.e(TAG, "Failed to bind to media container service");
1564                            for (HandlerParams params : mPendingInstalls) {
1565                                // Indicate service bind error
1566                                params.serviceError();
1567                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1568                                        System.identityHashCode(params));
1569                            }
1570                            mPendingInstalls.clear();
1571                        }
1572                    }
1573                    break;
1574                }
1575                case MCS_UNBIND: {
1576                    // If there is no actual work left, then time to unbind.
1577                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1578
1579                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1580                        if (mBound) {
1581                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1582
1583                            disconnectService();
1584                        }
1585                    } else if (mPendingInstalls.size() > 0) {
1586                        // There are more pending requests in queue.
1587                        // Just post MCS_BOUND message to trigger processing
1588                        // of next pending install.
1589                        mHandler.sendEmptyMessage(MCS_BOUND);
1590                    }
1591
1592                    break;
1593                }
1594                case MCS_GIVE_UP: {
1595                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1596                    HandlerParams params = mPendingInstalls.remove(0);
1597                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1598                            System.identityHashCode(params));
1599                    break;
1600                }
1601                case SEND_PENDING_BROADCAST: {
1602                    String packages[];
1603                    ArrayList<String> components[];
1604                    int size = 0;
1605                    int uids[];
1606                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1607                    synchronized (mPackages) {
1608                        if (mPendingBroadcasts == null) {
1609                            return;
1610                        }
1611                        size = mPendingBroadcasts.size();
1612                        if (size <= 0) {
1613                            // Nothing to be done. Just return
1614                            return;
1615                        }
1616                        packages = new String[size];
1617                        components = new ArrayList[size];
1618                        uids = new int[size];
1619                        int i = 0;  // filling out the above arrays
1620
1621                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1622                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1623                            Iterator<Map.Entry<String, ArrayList<String>>> it
1624                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1625                                            .entrySet().iterator();
1626                            while (it.hasNext() && i < size) {
1627                                Map.Entry<String, ArrayList<String>> ent = it.next();
1628                                packages[i] = ent.getKey();
1629                                components[i] = ent.getValue();
1630                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1631                                uids[i] = (ps != null)
1632                                        ? UserHandle.getUid(packageUserId, ps.appId)
1633                                        : -1;
1634                                i++;
1635                            }
1636                        }
1637                        size = i;
1638                        mPendingBroadcasts.clear();
1639                    }
1640                    // Send broadcasts
1641                    for (int i = 0; i < size; i++) {
1642                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1643                    }
1644                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1645                    break;
1646                }
1647                case START_CLEANING_PACKAGE: {
1648                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1649                    final String packageName = (String)msg.obj;
1650                    final int userId = msg.arg1;
1651                    final boolean andCode = msg.arg2 != 0;
1652                    synchronized (mPackages) {
1653                        if (userId == UserHandle.USER_ALL) {
1654                            int[] users = sUserManager.getUserIds();
1655                            for (int user : users) {
1656                                mSettings.addPackageToCleanLPw(
1657                                        new PackageCleanItem(user, packageName, andCode));
1658                            }
1659                        } else {
1660                            mSettings.addPackageToCleanLPw(
1661                                    new PackageCleanItem(userId, packageName, andCode));
1662                        }
1663                    }
1664                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1665                    startCleaningPackages();
1666                } break;
1667                case POST_INSTALL: {
1668                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1669
1670                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1671                    final boolean didRestore = (msg.arg2 != 0);
1672                    mRunningInstalls.delete(msg.arg1);
1673
1674                    if (data != null) {
1675                        InstallArgs args = data.args;
1676                        PackageInstalledInfo parentRes = data.res;
1677
1678                        final boolean grantPermissions = (args.installFlags
1679                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1680                        final boolean killApp = (args.installFlags
1681                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1682                        final boolean virtualPreload = ((args.installFlags
1683                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1684                        final String[] grantedPermissions = args.installGrantPermissions;
1685
1686                        // Handle the parent package
1687                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1688                                virtualPreload, grantedPermissions, didRestore,
1689                                args.installerPackageName, args.observer);
1690
1691                        // Handle the child packages
1692                        final int childCount = (parentRes.addedChildPackages != null)
1693                                ? parentRes.addedChildPackages.size() : 0;
1694                        for (int i = 0; i < childCount; i++) {
1695                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1696                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1697                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1698                                    args.installerPackageName, args.observer);
1699                        }
1700
1701                        // Log tracing if needed
1702                        if (args.traceMethod != null) {
1703                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1704                                    args.traceCookie);
1705                        }
1706                    } else {
1707                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1708                    }
1709
1710                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1711                } break;
1712                case UPDATED_MEDIA_STATUS: {
1713                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1714                    boolean reportStatus = msg.arg1 == 1;
1715                    boolean doGc = msg.arg2 == 1;
1716                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1717                    if (doGc) {
1718                        // Force a gc to clear up stale containers.
1719                        Runtime.getRuntime().gc();
1720                    }
1721                    if (msg.obj != null) {
1722                        @SuppressWarnings("unchecked")
1723                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1724                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1725                        // Unload containers
1726                        unloadAllContainers(args);
1727                    }
1728                    if (reportStatus) {
1729                        try {
1730                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1731                                    "Invoking StorageManagerService call back");
1732                            PackageHelper.getStorageManager().finishMediaUpdate();
1733                        } catch (RemoteException e) {
1734                            Log.e(TAG, "StorageManagerService not running?");
1735                        }
1736                    }
1737                } break;
1738                case WRITE_SETTINGS: {
1739                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1740                    synchronized (mPackages) {
1741                        removeMessages(WRITE_SETTINGS);
1742                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1743                        mSettings.writeLPr();
1744                        mDirtyUsers.clear();
1745                    }
1746                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1747                } break;
1748                case WRITE_PACKAGE_RESTRICTIONS: {
1749                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1750                    synchronized (mPackages) {
1751                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1752                        for (int userId : mDirtyUsers) {
1753                            mSettings.writePackageRestrictionsLPr(userId);
1754                        }
1755                        mDirtyUsers.clear();
1756                    }
1757                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1758                } break;
1759                case WRITE_PACKAGE_LIST: {
1760                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1761                    synchronized (mPackages) {
1762                        removeMessages(WRITE_PACKAGE_LIST);
1763                        mSettings.writePackageListLPr(msg.arg1);
1764                    }
1765                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1766                } break;
1767                case CHECK_PENDING_VERIFICATION: {
1768                    final int verificationId = msg.arg1;
1769                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1770
1771                    if ((state != null) && !state.timeoutExtended()) {
1772                        final InstallArgs args = state.getInstallArgs();
1773                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1774
1775                        Slog.i(TAG, "Verification timed out for " + originUri);
1776                        mPendingVerification.remove(verificationId);
1777
1778                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1779
1780                        final UserHandle user = args.getUser();
1781                        if (getDefaultVerificationResponse(user)
1782                                == PackageManager.VERIFICATION_ALLOW) {
1783                            Slog.i(TAG, "Continuing with installation of " + originUri);
1784                            state.setVerifierResponse(Binder.getCallingUid(),
1785                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1786                            broadcastPackageVerified(verificationId, originUri,
1787                                    PackageManager.VERIFICATION_ALLOW, user);
1788                            try {
1789                                ret = args.copyApk(mContainerService, true);
1790                            } catch (RemoteException e) {
1791                                Slog.e(TAG, "Could not contact the ContainerService");
1792                            }
1793                        } else {
1794                            broadcastPackageVerified(verificationId, originUri,
1795                                    PackageManager.VERIFICATION_REJECT, user);
1796                        }
1797
1798                        Trace.asyncTraceEnd(
1799                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1800
1801                        processPendingInstall(args, ret);
1802                        mHandler.sendEmptyMessage(MCS_UNBIND);
1803                    }
1804                    break;
1805                }
1806                case PACKAGE_VERIFIED: {
1807                    final int verificationId = msg.arg1;
1808
1809                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1810                    if (state == null) {
1811                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1812                        break;
1813                    }
1814
1815                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1816
1817                    state.setVerifierResponse(response.callerUid, response.code);
1818
1819                    if (state.isVerificationComplete()) {
1820                        mPendingVerification.remove(verificationId);
1821
1822                        final InstallArgs args = state.getInstallArgs();
1823                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1824
1825                        int ret;
1826                        if (state.isInstallAllowed()) {
1827                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1828                            broadcastPackageVerified(verificationId, originUri,
1829                                    response.code, state.getInstallArgs().getUser());
1830                            try {
1831                                ret = args.copyApk(mContainerService, true);
1832                            } catch (RemoteException e) {
1833                                Slog.e(TAG, "Could not contact the ContainerService");
1834                            }
1835                        } else {
1836                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1837                        }
1838
1839                        Trace.asyncTraceEnd(
1840                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1841
1842                        processPendingInstall(args, ret);
1843                        mHandler.sendEmptyMessage(MCS_UNBIND);
1844                    }
1845
1846                    break;
1847                }
1848                case START_INTENT_FILTER_VERIFICATIONS: {
1849                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1850                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1851                            params.replacing, params.pkg);
1852                    break;
1853                }
1854                case INTENT_FILTER_VERIFIED: {
1855                    final int verificationId = msg.arg1;
1856
1857                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1858                            verificationId);
1859                    if (state == null) {
1860                        Slog.w(TAG, "Invalid IntentFilter verification token "
1861                                + verificationId + " received");
1862                        break;
1863                    }
1864
1865                    final int userId = state.getUserId();
1866
1867                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1868                            "Processing IntentFilter verification with token:"
1869                            + verificationId + " and userId:" + userId);
1870
1871                    final IntentFilterVerificationResponse response =
1872                            (IntentFilterVerificationResponse) msg.obj;
1873
1874                    state.setVerifierResponse(response.callerUid, response.code);
1875
1876                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1877                            "IntentFilter verification with token:" + verificationId
1878                            + " and userId:" + userId
1879                            + " is settings verifier response with response code:"
1880                            + response.code);
1881
1882                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1883                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1884                                + response.getFailedDomainsString());
1885                    }
1886
1887                    if (state.isVerificationComplete()) {
1888                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1889                    } else {
1890                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1891                                "IntentFilter verification with token:" + verificationId
1892                                + " was not said to be complete");
1893                    }
1894
1895                    break;
1896                }
1897                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1898                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1899                            mInstantAppResolverConnection,
1900                            (InstantAppRequest) msg.obj,
1901                            mInstantAppInstallerActivity,
1902                            mHandler);
1903                }
1904            }
1905        }
1906    }
1907
1908    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1909            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1910            boolean launchedForRestore, String installerPackage,
1911            IPackageInstallObserver2 installObserver) {
1912        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1913            // Send the removed broadcasts
1914            if (res.removedInfo != null) {
1915                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1916            }
1917
1918            // Now that we successfully installed the package, grant runtime
1919            // permissions if requested before broadcasting the install. Also
1920            // for legacy apps in permission review mode we clear the permission
1921            // review flag which is used to emulate runtime permissions for
1922            // legacy apps.
1923            if (grantPermissions) {
1924                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1925            }
1926
1927            final boolean update = res.removedInfo != null
1928                    && res.removedInfo.removedPackage != null;
1929            final String origInstallerPackageName = res.removedInfo != null
1930                    ? res.removedInfo.installerPackageName : null;
1931
1932            // If this is the first time we have child packages for a disabled privileged
1933            // app that had no children, we grant requested runtime permissions to the new
1934            // children if the parent on the system image had them already granted.
1935            if (res.pkg.parentPackage != null) {
1936                synchronized (mPackages) {
1937                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1938                }
1939            }
1940
1941            synchronized (mPackages) {
1942                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1943            }
1944
1945            final String packageName = res.pkg.applicationInfo.packageName;
1946
1947            // Determine the set of users who are adding this package for
1948            // the first time vs. those who are seeing an update.
1949            int[] firstUsers = EMPTY_INT_ARRAY;
1950            int[] updateUsers = EMPTY_INT_ARRAY;
1951            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1952            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1953            for (int newUser : res.newUsers) {
1954                if (ps.getInstantApp(newUser)) {
1955                    continue;
1956                }
1957                if (allNewUsers) {
1958                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1959                    continue;
1960                }
1961                boolean isNew = true;
1962                for (int origUser : res.origUsers) {
1963                    if (origUser == newUser) {
1964                        isNew = false;
1965                        break;
1966                    }
1967                }
1968                if (isNew) {
1969                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1970                } else {
1971                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1972                }
1973            }
1974
1975            // Send installed broadcasts if the package is not a static shared lib.
1976            if (res.pkg.staticSharedLibName == null) {
1977                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1978
1979                // Send added for users that see the package for the first time
1980                // sendPackageAddedForNewUsers also deals with system apps
1981                int appId = UserHandle.getAppId(res.uid);
1982                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1983                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
1984                        virtualPreload /*startReceiver*/, appId, firstUsers);
1985
1986                // Send added for users that don't see the package for the first time
1987                Bundle extras = new Bundle(1);
1988                extras.putInt(Intent.EXTRA_UID, res.uid);
1989                if (update) {
1990                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1991                }
1992                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1993                        extras, 0 /*flags*/,
1994                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
1995                if (origInstallerPackageName != null) {
1996                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1997                            extras, 0 /*flags*/,
1998                            origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1999                }
2000
2001                // Send replaced for users that don't see the package for the first time
2002                if (update) {
2003                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2004                            packageName, extras, 0 /*flags*/,
2005                            null /*targetPackage*/, null /*finishedReceiver*/,
2006                            updateUsers);
2007                    if (origInstallerPackageName != null) {
2008                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2009                                extras, 0 /*flags*/,
2010                                origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
2011                    }
2012                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2013                            null /*package*/, null /*extras*/, 0 /*flags*/,
2014                            packageName /*targetPackage*/,
2015                            null /*finishedReceiver*/, updateUsers);
2016                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2017                    // First-install and we did a restore, so we're responsible for the
2018                    // first-launch broadcast.
2019                    if (DEBUG_BACKUP) {
2020                        Slog.i(TAG, "Post-restore of " + packageName
2021                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2022                    }
2023                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2024                }
2025
2026                // Send broadcast package appeared if forward locked/external for all users
2027                // treat asec-hosted packages like removable media on upgrade
2028                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2029                    if (DEBUG_INSTALL) {
2030                        Slog.i(TAG, "upgrading pkg " + res.pkg
2031                                + " is ASEC-hosted -> AVAILABLE");
2032                    }
2033                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2034                    ArrayList<String> pkgList = new ArrayList<>(1);
2035                    pkgList.add(packageName);
2036                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2037                }
2038            }
2039
2040            // Work that needs to happen on first install within each user
2041            if (firstUsers != null && firstUsers.length > 0) {
2042                synchronized (mPackages) {
2043                    for (int userId : firstUsers) {
2044                        // If this app is a browser and it's newly-installed for some
2045                        // users, clear any default-browser state in those users. The
2046                        // app's nature doesn't depend on the user, so we can just check
2047                        // its browser nature in any user and generalize.
2048                        if (packageIsBrowser(packageName, userId)) {
2049                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2050                        }
2051
2052                        // We may also need to apply pending (restored) runtime
2053                        // permission grants within these users.
2054                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2055                    }
2056                }
2057            }
2058
2059            // Log current value of "unknown sources" setting
2060            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2061                    getUnknownSourcesSettings());
2062
2063            // Remove the replaced package's older resources safely now
2064            // We delete after a gc for applications  on sdcard.
2065            if (res.removedInfo != null && res.removedInfo.args != null) {
2066                Runtime.getRuntime().gc();
2067                synchronized (mInstallLock) {
2068                    res.removedInfo.args.doPostDeleteLI(true);
2069                }
2070            } else {
2071                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2072                // and not block here.
2073                VMRuntime.getRuntime().requestConcurrentGC();
2074            }
2075
2076            // Notify DexManager that the package was installed for new users.
2077            // The updated users should already be indexed and the package code paths
2078            // should not change.
2079            // Don't notify the manager for ephemeral apps as they are not expected to
2080            // survive long enough to benefit of background optimizations.
2081            for (int userId : firstUsers) {
2082                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2083                // There's a race currently where some install events may interleave with an uninstall.
2084                // This can lead to package info being null (b/36642664).
2085                if (info != null) {
2086                    mDexManager.notifyPackageInstalled(info, userId);
2087                }
2088            }
2089        }
2090
2091        // If someone is watching installs - notify them
2092        if (installObserver != null) {
2093            try {
2094                Bundle extras = extrasForInstallResult(res);
2095                installObserver.onPackageInstalled(res.name, res.returnCode,
2096                        res.returnMsg, extras);
2097            } catch (RemoteException e) {
2098                Slog.i(TAG, "Observer no longer exists.");
2099            }
2100        }
2101    }
2102
2103    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2104            PackageParser.Package pkg) {
2105        if (pkg.parentPackage == null) {
2106            return;
2107        }
2108        if (pkg.requestedPermissions == null) {
2109            return;
2110        }
2111        final PackageSetting disabledSysParentPs = mSettings
2112                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2113        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2114                || !disabledSysParentPs.isPrivileged()
2115                || (disabledSysParentPs.childPackageNames != null
2116                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2117            return;
2118        }
2119        final int[] allUserIds = sUserManager.getUserIds();
2120        final int permCount = pkg.requestedPermissions.size();
2121        for (int i = 0; i < permCount; i++) {
2122            String permission = pkg.requestedPermissions.get(i);
2123            BasePermission bp = mSettings.mPermissions.get(permission);
2124            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2125                continue;
2126            }
2127            for (int userId : allUserIds) {
2128                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2129                        permission, userId)) {
2130                    grantRuntimePermission(pkg.packageName, permission, userId);
2131                }
2132            }
2133        }
2134    }
2135
2136    private StorageEventListener mStorageListener = new StorageEventListener() {
2137        @Override
2138        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2139            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2140                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2141                    final String volumeUuid = vol.getFsUuid();
2142
2143                    // Clean up any users or apps that were removed or recreated
2144                    // while this volume was missing
2145                    sUserManager.reconcileUsers(volumeUuid);
2146                    reconcileApps(volumeUuid);
2147
2148                    // Clean up any install sessions that expired or were
2149                    // cancelled while this volume was missing
2150                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2151
2152                    loadPrivatePackages(vol);
2153
2154                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2155                    unloadPrivatePackages(vol);
2156                }
2157            }
2158
2159            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2160                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2161                    updateExternalMediaStatus(true, false);
2162                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2163                    updateExternalMediaStatus(false, false);
2164                }
2165            }
2166        }
2167
2168        @Override
2169        public void onVolumeForgotten(String fsUuid) {
2170            if (TextUtils.isEmpty(fsUuid)) {
2171                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2172                return;
2173            }
2174
2175            // Remove any apps installed on the forgotten volume
2176            synchronized (mPackages) {
2177                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2178                for (PackageSetting ps : packages) {
2179                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2180                    deletePackageVersioned(new VersionedPackage(ps.name,
2181                            PackageManager.VERSION_CODE_HIGHEST),
2182                            new LegacyPackageDeleteObserver(null).getBinder(),
2183                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2184                    // Try very hard to release any references to this package
2185                    // so we don't risk the system server being killed due to
2186                    // open FDs
2187                    AttributeCache.instance().removePackage(ps.name);
2188                }
2189
2190                mSettings.onVolumeForgotten(fsUuid);
2191                mSettings.writeLPr();
2192            }
2193        }
2194    };
2195
2196    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2197            String[] grantedPermissions) {
2198        for (int userId : userIds) {
2199            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2200        }
2201    }
2202
2203    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2204            String[] grantedPermissions) {
2205        PackageSetting ps = (PackageSetting) pkg.mExtras;
2206        if (ps == null) {
2207            return;
2208        }
2209
2210        PermissionsState permissionsState = ps.getPermissionsState();
2211
2212        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2213                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2214
2215        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2216                >= Build.VERSION_CODES.M;
2217
2218        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2219
2220        for (String permission : pkg.requestedPermissions) {
2221            final BasePermission bp;
2222            synchronized (mPackages) {
2223                bp = mSettings.mPermissions.get(permission);
2224            }
2225            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2226                    && (!instantApp || bp.isInstant())
2227                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2228                    && (grantedPermissions == null
2229                           || ArrayUtils.contains(grantedPermissions, permission))) {
2230                final int flags = permissionsState.getPermissionFlags(permission, userId);
2231                if (supportsRuntimePermissions) {
2232                    // Installer cannot change immutable permissions.
2233                    if ((flags & immutableFlags) == 0) {
2234                        grantRuntimePermission(pkg.packageName, permission, userId);
2235                    }
2236                } else if (mPermissionReviewRequired) {
2237                    // In permission review mode we clear the review flag when we
2238                    // are asked to install the app with all permissions granted.
2239                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2240                        updatePermissionFlags(permission, pkg.packageName,
2241                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2242                    }
2243                }
2244            }
2245        }
2246    }
2247
2248    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2249        Bundle extras = null;
2250        switch (res.returnCode) {
2251            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2252                extras = new Bundle();
2253                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2254                        res.origPermission);
2255                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2256                        res.origPackage);
2257                break;
2258            }
2259            case PackageManager.INSTALL_SUCCEEDED: {
2260                extras = new Bundle();
2261                extras.putBoolean(Intent.EXTRA_REPLACING,
2262                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2263                break;
2264            }
2265        }
2266        return extras;
2267    }
2268
2269    void scheduleWriteSettingsLocked() {
2270        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2271            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2272        }
2273    }
2274
2275    void scheduleWritePackageListLocked(int userId) {
2276        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2277            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2278            msg.arg1 = userId;
2279            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2280        }
2281    }
2282
2283    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2284        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2285        scheduleWritePackageRestrictionsLocked(userId);
2286    }
2287
2288    void scheduleWritePackageRestrictionsLocked(int userId) {
2289        final int[] userIds = (userId == UserHandle.USER_ALL)
2290                ? sUserManager.getUserIds() : new int[]{userId};
2291        for (int nextUserId : userIds) {
2292            if (!sUserManager.exists(nextUserId)) return;
2293            mDirtyUsers.add(nextUserId);
2294            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2295                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2296            }
2297        }
2298    }
2299
2300    public static PackageManagerService main(Context context, Installer installer,
2301            boolean factoryTest, boolean onlyCore) {
2302        // Self-check for initial settings.
2303        PackageManagerServiceCompilerMapping.checkProperties();
2304
2305        PackageManagerService m = new PackageManagerService(context, installer,
2306                factoryTest, onlyCore);
2307        m.enableSystemUserPackages();
2308        ServiceManager.addService("package", m);
2309        final PackageManagerNative pmn = m.new PackageManagerNative();
2310        ServiceManager.addService("package_native", pmn);
2311        return m;
2312    }
2313
2314    private void enableSystemUserPackages() {
2315        if (!UserManager.isSplitSystemUser()) {
2316            return;
2317        }
2318        // For system user, enable apps based on the following conditions:
2319        // - app is whitelisted or belong to one of these groups:
2320        //   -- system app which has no launcher icons
2321        //   -- system app which has INTERACT_ACROSS_USERS permission
2322        //   -- system IME app
2323        // - app is not in the blacklist
2324        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2325        Set<String> enableApps = new ArraySet<>();
2326        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2327                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2328                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2329        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2330        enableApps.addAll(wlApps);
2331        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2332                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2333        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2334        enableApps.removeAll(blApps);
2335        Log.i(TAG, "Applications installed for system user: " + enableApps);
2336        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2337                UserHandle.SYSTEM);
2338        final int allAppsSize = allAps.size();
2339        synchronized (mPackages) {
2340            for (int i = 0; i < allAppsSize; i++) {
2341                String pName = allAps.get(i);
2342                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2343                // Should not happen, but we shouldn't be failing if it does
2344                if (pkgSetting == null) {
2345                    continue;
2346                }
2347                boolean install = enableApps.contains(pName);
2348                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2349                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2350                            + " for system user");
2351                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2352                }
2353            }
2354            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2355        }
2356    }
2357
2358    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2359        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2360                Context.DISPLAY_SERVICE);
2361        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2362    }
2363
2364    /**
2365     * Requests that files preopted on a secondary system partition be copied to the data partition
2366     * if possible.  Note that the actual copying of the files is accomplished by init for security
2367     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2368     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2369     */
2370    private static void requestCopyPreoptedFiles() {
2371        final int WAIT_TIME_MS = 100;
2372        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2373        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2374            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2375            // We will wait for up to 100 seconds.
2376            final long timeStart = SystemClock.uptimeMillis();
2377            final long timeEnd = timeStart + 100 * 1000;
2378            long timeNow = timeStart;
2379            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2380                try {
2381                    Thread.sleep(WAIT_TIME_MS);
2382                } catch (InterruptedException e) {
2383                    // Do nothing
2384                }
2385                timeNow = SystemClock.uptimeMillis();
2386                if (timeNow > timeEnd) {
2387                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2388                    Slog.wtf(TAG, "cppreopt did not finish!");
2389                    break;
2390                }
2391            }
2392
2393            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2394        }
2395    }
2396
2397    public PackageManagerService(Context context, Installer installer,
2398            boolean factoryTest, boolean onlyCore) {
2399        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2400        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2401        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2402                SystemClock.uptimeMillis());
2403
2404        if (mSdkVersion <= 0) {
2405            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2406        }
2407
2408        mContext = context;
2409
2410        mPermissionReviewRequired = context.getResources().getBoolean(
2411                R.bool.config_permissionReviewRequired);
2412
2413        mFactoryTest = factoryTest;
2414        mOnlyCore = onlyCore;
2415        mMetrics = new DisplayMetrics();
2416        mSettings = new Settings(mPackages);
2417        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2418                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2419        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2420                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2421        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2422                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2423        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2424                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2425        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2426                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2427        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2428                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2429
2430        String separateProcesses = SystemProperties.get("debug.separate_processes");
2431        if (separateProcesses != null && separateProcesses.length() > 0) {
2432            if ("*".equals(separateProcesses)) {
2433                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2434                mSeparateProcesses = null;
2435                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2436            } else {
2437                mDefParseFlags = 0;
2438                mSeparateProcesses = separateProcesses.split(",");
2439                Slog.w(TAG, "Running with debug.separate_processes: "
2440                        + separateProcesses);
2441            }
2442        } else {
2443            mDefParseFlags = 0;
2444            mSeparateProcesses = null;
2445        }
2446
2447        mInstaller = installer;
2448        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2449                "*dexopt*");
2450        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2451        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2452
2453        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2454                FgThread.get().getLooper());
2455
2456        getDefaultDisplayMetrics(context, mMetrics);
2457
2458        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2459        SystemConfig systemConfig = SystemConfig.getInstance();
2460        mGlobalGids = systemConfig.getGlobalGids();
2461        mSystemPermissions = systemConfig.getSystemPermissions();
2462        mAvailableFeatures = systemConfig.getAvailableFeatures();
2463        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2464
2465        mProtectedPackages = new ProtectedPackages(mContext);
2466
2467        synchronized (mInstallLock) {
2468        // writer
2469        synchronized (mPackages) {
2470            mHandlerThread = new ServiceThread(TAG,
2471                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2472            mHandlerThread.start();
2473            mHandler = new PackageHandler(mHandlerThread.getLooper());
2474            mProcessLoggingHandler = new ProcessLoggingHandler();
2475            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2476
2477            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2478            mInstantAppRegistry = new InstantAppRegistry(this);
2479
2480            File dataDir = Environment.getDataDirectory();
2481            mAppInstallDir = new File(dataDir, "app");
2482            mAppLib32InstallDir = new File(dataDir, "app-lib");
2483            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2484            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2485            sUserManager = new UserManagerService(context, this,
2486                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2487
2488            // Propagate permission configuration in to package manager.
2489            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2490                    = systemConfig.getPermissions();
2491            for (int i=0; i<permConfig.size(); i++) {
2492                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2493                BasePermission bp = mSettings.mPermissions.get(perm.name);
2494                if (bp == null) {
2495                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2496                    mSettings.mPermissions.put(perm.name, bp);
2497                }
2498                if (perm.gids != null) {
2499                    bp.setGids(perm.gids, perm.perUser);
2500                }
2501            }
2502
2503            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2504            final int builtInLibCount = libConfig.size();
2505            for (int i = 0; i < builtInLibCount; i++) {
2506                String name = libConfig.keyAt(i);
2507                String path = libConfig.valueAt(i);
2508                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2509                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2510            }
2511
2512            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2513
2514            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2515            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2516            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2517
2518            // Clean up orphaned packages for which the code path doesn't exist
2519            // and they are an update to a system app - caused by bug/32321269
2520            final int packageSettingCount = mSettings.mPackages.size();
2521            for (int i = packageSettingCount - 1; i >= 0; i--) {
2522                PackageSetting ps = mSettings.mPackages.valueAt(i);
2523                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2524                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2525                    mSettings.mPackages.removeAt(i);
2526                    mSettings.enableSystemPackageLPw(ps.name);
2527                }
2528            }
2529
2530            if (mFirstBoot) {
2531                requestCopyPreoptedFiles();
2532            }
2533
2534            String customResolverActivity = Resources.getSystem().getString(
2535                    R.string.config_customResolverActivity);
2536            if (TextUtils.isEmpty(customResolverActivity)) {
2537                customResolverActivity = null;
2538            } else {
2539                mCustomResolverComponentName = ComponentName.unflattenFromString(
2540                        customResolverActivity);
2541            }
2542
2543            long startTime = SystemClock.uptimeMillis();
2544
2545            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2546                    startTime);
2547
2548            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2549            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2550
2551            if (bootClassPath == null) {
2552                Slog.w(TAG, "No BOOTCLASSPATH found!");
2553            }
2554
2555            if (systemServerClassPath == null) {
2556                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2557            }
2558
2559            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2560
2561            final VersionInfo ver = mSettings.getInternalVersion();
2562            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2563            if (mIsUpgrade) {
2564                logCriticalInfo(Log.INFO,
2565                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2566            }
2567
2568            // when upgrading from pre-M, promote system app permissions from install to runtime
2569            mPromoteSystemApps =
2570                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2571
2572            // When upgrading from pre-N, we need to handle package extraction like first boot,
2573            // as there is no profiling data available.
2574            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2575
2576            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2577
2578            // save off the names of pre-existing system packages prior to scanning; we don't
2579            // want to automatically grant runtime permissions for new system apps
2580            if (mPromoteSystemApps) {
2581                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2582                while (pkgSettingIter.hasNext()) {
2583                    PackageSetting ps = pkgSettingIter.next();
2584                    if (isSystemApp(ps)) {
2585                        mExistingSystemPackages.add(ps.name);
2586                    }
2587                }
2588            }
2589
2590            mCacheDir = preparePackageParserCache(mIsUpgrade);
2591
2592            // Set flag to monitor and not change apk file paths when
2593            // scanning install directories.
2594            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2595
2596            if (mIsUpgrade || mFirstBoot) {
2597                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2598            }
2599
2600            // Collect vendor overlay packages. (Do this before scanning any apps.)
2601            // For security and version matching reason, only consider
2602            // overlay packages if they reside in the right directory.
2603            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2604                    | PackageParser.PARSE_IS_SYSTEM
2605                    | PackageParser.PARSE_IS_SYSTEM_DIR
2606                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2607
2608            mParallelPackageParserCallback.findStaticOverlayPackages();
2609
2610            // Find base frameworks (resource packages without code).
2611            scanDirTracedLI(frameworkDir, mDefParseFlags
2612                    | PackageParser.PARSE_IS_SYSTEM
2613                    | PackageParser.PARSE_IS_SYSTEM_DIR
2614                    | PackageParser.PARSE_IS_PRIVILEGED,
2615                    scanFlags | SCAN_NO_DEX, 0);
2616
2617            // Collected privileged system packages.
2618            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2619            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2620                    | PackageParser.PARSE_IS_SYSTEM
2621                    | PackageParser.PARSE_IS_SYSTEM_DIR
2622                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2623
2624            // Collect ordinary system packages.
2625            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2626            scanDirTracedLI(systemAppDir, mDefParseFlags
2627                    | PackageParser.PARSE_IS_SYSTEM
2628                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2629
2630            // Collect all vendor packages.
2631            File vendorAppDir = new File("/vendor/app");
2632            try {
2633                vendorAppDir = vendorAppDir.getCanonicalFile();
2634            } catch (IOException e) {
2635                // failed to look up canonical path, continue with original one
2636            }
2637            scanDirTracedLI(vendorAppDir, mDefParseFlags
2638                    | PackageParser.PARSE_IS_SYSTEM
2639                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2640
2641            // Collect all OEM packages.
2642            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2643            scanDirTracedLI(oemAppDir, mDefParseFlags
2644                    | PackageParser.PARSE_IS_SYSTEM
2645                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2646
2647            // Prune any system packages that no longer exist.
2648            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2649            // Stub packages must either be replaced with full versions in the /data
2650            // partition or be disabled.
2651            final List<String> stubSystemApps = new ArrayList<>();
2652            if (!mOnlyCore) {
2653                // do this first before mucking with mPackages for the "expecting better" case
2654                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2655                while (pkgIterator.hasNext()) {
2656                    final PackageParser.Package pkg = pkgIterator.next();
2657                    if (pkg.isStub) {
2658                        stubSystemApps.add(pkg.packageName);
2659                    }
2660                }
2661
2662                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2663                while (psit.hasNext()) {
2664                    PackageSetting ps = psit.next();
2665
2666                    /*
2667                     * If this is not a system app, it can't be a
2668                     * disable system app.
2669                     */
2670                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2671                        continue;
2672                    }
2673
2674                    /*
2675                     * If the package is scanned, it's not erased.
2676                     */
2677                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2678                    if (scannedPkg != null) {
2679                        /*
2680                         * If the system app is both scanned and in the
2681                         * disabled packages list, then it must have been
2682                         * added via OTA. Remove it from the currently
2683                         * scanned package so the previously user-installed
2684                         * application can be scanned.
2685                         */
2686                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2687                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2688                                    + ps.name + "; removing system app.  Last known codePath="
2689                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2690                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2691                                    + scannedPkg.mVersionCode);
2692                            removePackageLI(scannedPkg, true);
2693                            mExpectingBetter.put(ps.name, ps.codePath);
2694                        }
2695
2696                        continue;
2697                    }
2698
2699                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2700                        psit.remove();
2701                        logCriticalInfo(Log.WARN, "System package " + ps.name
2702                                + " no longer exists; it's data will be wiped");
2703                        // Actual deletion of code and data will be handled by later
2704                        // reconciliation step
2705                    } else {
2706                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2707                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2708                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2709                        }
2710                    }
2711                }
2712            }
2713
2714            //look for any incomplete package installations
2715            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2716            for (int i = 0; i < deletePkgsList.size(); i++) {
2717                // Actual deletion of code and data will be handled by later
2718                // reconciliation step
2719                final String packageName = deletePkgsList.get(i).name;
2720                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2721                synchronized (mPackages) {
2722                    mSettings.removePackageLPw(packageName);
2723                }
2724            }
2725
2726            //delete tmp files
2727            deleteTempPackageFiles();
2728
2729            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2730
2731            // Remove any shared userIDs that have no associated packages
2732            mSettings.pruneSharedUsersLPw();
2733            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2734            final int systemPackagesCount = mPackages.size();
2735            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2736                    + " ms, packageCount: " + systemPackagesCount
2737                    + " , timePerPackage: "
2738                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2739                    + " , cached: " + cachedSystemApps);
2740            if (mIsUpgrade && systemPackagesCount > 0) {
2741                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2742                        ((int) systemScanTime) / systemPackagesCount);
2743            }
2744            if (!mOnlyCore) {
2745                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2746                        SystemClock.uptimeMillis());
2747                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2748
2749                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2750                        | PackageParser.PARSE_FORWARD_LOCK,
2751                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2752
2753                // Remove disable package settings for updated system apps that were
2754                // removed via an OTA. If the update is no longer present, remove the
2755                // app completely. Otherwise, revoke their system privileges.
2756                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2757                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2758                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2759
2760                    final String msg;
2761                    if (deletedPkg == null) {
2762                        // should have found an update, but, we didn't; remove everything
2763                        msg = "Updated system package " + deletedAppName
2764                                + " no longer exists; removing its data";
2765                        // Actual deletion of code and data will be handled by later
2766                        // reconciliation step
2767                    } else {
2768                        // found an update; revoke system privileges
2769                        msg = "Updated system package + " + deletedAppName
2770                                + " no longer exists; revoking system privileges";
2771
2772                        // Don't do anything if a stub is removed from the system image. If
2773                        // we were to remove the uncompressed version from the /data partition,
2774                        // this is where it'd be done.
2775
2776                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2777                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2778                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2779                    }
2780                    logCriticalInfo(Log.WARN, msg);
2781                }
2782
2783                /*
2784                 * Make sure all system apps that we expected to appear on
2785                 * the userdata partition actually showed up. If they never
2786                 * appeared, crawl back and revive the system version.
2787                 */
2788                for (int i = 0; i < mExpectingBetter.size(); i++) {
2789                    final String packageName = mExpectingBetter.keyAt(i);
2790                    if (!mPackages.containsKey(packageName)) {
2791                        final File scanFile = mExpectingBetter.valueAt(i);
2792
2793                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2794                                + " but never showed up; reverting to system");
2795
2796                        int reparseFlags = mDefParseFlags;
2797                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2798                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2799                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2800                                    | PackageParser.PARSE_IS_PRIVILEGED;
2801                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2802                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2803                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2804                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2805                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2806                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2807                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2808                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2809                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2810                        } else {
2811                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2812                            continue;
2813                        }
2814
2815                        mSettings.enableSystemPackageLPw(packageName);
2816
2817                        try {
2818                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2819                        } catch (PackageManagerException e) {
2820                            Slog.e(TAG, "Failed to parse original system package: "
2821                                    + e.getMessage());
2822                        }
2823                    }
2824                }
2825
2826                // Uncompress and install any stubbed system applications.
2827                // This must be done last to ensure all stubs are replaced or disabled.
2828                decompressSystemApplications(stubSystemApps, scanFlags);
2829
2830                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2831                                - cachedSystemApps;
2832
2833                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2834                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2835                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2836                        + " ms, packageCount: " + dataPackagesCount
2837                        + " , timePerPackage: "
2838                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2839                        + " , cached: " + cachedNonSystemApps);
2840                if (mIsUpgrade && dataPackagesCount > 0) {
2841                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2842                            ((int) dataScanTime) / dataPackagesCount);
2843                }
2844            }
2845            mExpectingBetter.clear();
2846
2847            // Resolve the storage manager.
2848            mStorageManagerPackage = getStorageManagerPackageName();
2849
2850            // Resolve protected action filters. Only the setup wizard is allowed to
2851            // have a high priority filter for these actions.
2852            mSetupWizardPackage = getSetupWizardPackageName();
2853            if (mProtectedFilters.size() > 0) {
2854                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2855                    Slog.i(TAG, "No setup wizard;"
2856                        + " All protected intents capped to priority 0");
2857                }
2858                for (ActivityIntentInfo filter : mProtectedFilters) {
2859                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2860                        if (DEBUG_FILTERS) {
2861                            Slog.i(TAG, "Found setup wizard;"
2862                                + " allow priority " + filter.getPriority() + ";"
2863                                + " package: " + filter.activity.info.packageName
2864                                + " activity: " + filter.activity.className
2865                                + " priority: " + filter.getPriority());
2866                        }
2867                        // skip setup wizard; allow it to keep the high priority filter
2868                        continue;
2869                    }
2870                    if (DEBUG_FILTERS) {
2871                        Slog.i(TAG, "Protected action; cap priority to 0;"
2872                                + " package: " + filter.activity.info.packageName
2873                                + " activity: " + filter.activity.className
2874                                + " origPrio: " + filter.getPriority());
2875                    }
2876                    filter.setPriority(0);
2877                }
2878            }
2879            mDeferProtectedFilters = false;
2880            mProtectedFilters.clear();
2881
2882            // Now that we know all of the shared libraries, update all clients to have
2883            // the correct library paths.
2884            updateAllSharedLibrariesLPw(null);
2885
2886            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2887                // NOTE: We ignore potential failures here during a system scan (like
2888                // the rest of the commands above) because there's precious little we
2889                // can do about it. A settings error is reported, though.
2890                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2891            }
2892
2893            // Now that we know all the packages we are keeping,
2894            // read and update their last usage times.
2895            mPackageUsage.read(mPackages);
2896            mCompilerStats.read();
2897
2898            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2899                    SystemClock.uptimeMillis());
2900            Slog.i(TAG, "Time to scan packages: "
2901                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2902                    + " seconds");
2903
2904            // If the platform SDK has changed since the last time we booted,
2905            // we need to re-grant app permission to catch any new ones that
2906            // appear.  This is really a hack, and means that apps can in some
2907            // cases get permissions that the user didn't initially explicitly
2908            // allow...  it would be nice to have some better way to handle
2909            // this situation.
2910            int updateFlags = UPDATE_PERMISSIONS_ALL;
2911            if (ver.sdkVersion != mSdkVersion) {
2912                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2913                        + mSdkVersion + "; regranting permissions for internal storage");
2914                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2915            }
2916            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2917            ver.sdkVersion = mSdkVersion;
2918
2919            // If this is the first boot or an update from pre-M, and it is a normal
2920            // boot, then we need to initialize the default preferred apps across
2921            // all defined users.
2922            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2923                for (UserInfo user : sUserManager.getUsers(true)) {
2924                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2925                    applyFactoryDefaultBrowserLPw(user.id);
2926                    primeDomainVerificationsLPw(user.id);
2927                }
2928            }
2929
2930            // Prepare storage for system user really early during boot,
2931            // since core system apps like SettingsProvider and SystemUI
2932            // can't wait for user to start
2933            final int storageFlags;
2934            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2935                storageFlags = StorageManager.FLAG_STORAGE_DE;
2936            } else {
2937                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2938            }
2939            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2940                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2941                    true /* onlyCoreApps */);
2942            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2943                BootTimingsTraceLog traceLog = new BootTimingsTraceLog("SystemServerTimingAsync",
2944                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2945                traceLog.traceBegin("AppDataFixup");
2946                try {
2947                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2948                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2949                } catch (InstallerException e) {
2950                    Slog.w(TAG, "Trouble fixing GIDs", e);
2951                }
2952                traceLog.traceEnd();
2953
2954                traceLog.traceBegin("AppDataPrepare");
2955                if (deferPackages == null || deferPackages.isEmpty()) {
2956                    return;
2957                }
2958                int count = 0;
2959                for (String pkgName : deferPackages) {
2960                    PackageParser.Package pkg = null;
2961                    synchronized (mPackages) {
2962                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2963                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2964                            pkg = ps.pkg;
2965                        }
2966                    }
2967                    if (pkg != null) {
2968                        synchronized (mInstallLock) {
2969                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2970                                    true /* maybeMigrateAppData */);
2971                        }
2972                        count++;
2973                    }
2974                }
2975                traceLog.traceEnd();
2976                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2977            }, "prepareAppData");
2978
2979            // If this is first boot after an OTA, and a normal boot, then
2980            // we need to clear code cache directories.
2981            // Note that we do *not* clear the application profiles. These remain valid
2982            // across OTAs and are used to drive profile verification (post OTA) and
2983            // profile compilation (without waiting to collect a fresh set of profiles).
2984            if (mIsUpgrade && !onlyCore) {
2985                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2986                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2987                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2988                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2989                        // No apps are running this early, so no need to freeze
2990                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2991                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2992                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2993                    }
2994                }
2995                ver.fingerprint = Build.FINGERPRINT;
2996            }
2997
2998            checkDefaultBrowser();
2999
3000            // clear only after permissions and other defaults have been updated
3001            mExistingSystemPackages.clear();
3002            mPromoteSystemApps = false;
3003
3004            // All the changes are done during package scanning.
3005            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3006
3007            // can downgrade to reader
3008            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3009            mSettings.writeLPr();
3010            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3011            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3012                    SystemClock.uptimeMillis());
3013
3014            if (!mOnlyCore) {
3015                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3016                mRequiredInstallerPackage = getRequiredInstallerLPr();
3017                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3018                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3019                if (mIntentFilterVerifierComponent != null) {
3020                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3021                            mIntentFilterVerifierComponent);
3022                } else {
3023                    mIntentFilterVerifier = null;
3024                }
3025                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3026                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3027                        SharedLibraryInfo.VERSION_UNDEFINED);
3028                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3029                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3030                        SharedLibraryInfo.VERSION_UNDEFINED);
3031            } else {
3032                mRequiredVerifierPackage = null;
3033                mRequiredInstallerPackage = null;
3034                mRequiredUninstallerPackage = null;
3035                mIntentFilterVerifierComponent = null;
3036                mIntentFilterVerifier = null;
3037                mServicesSystemSharedLibraryPackageName = null;
3038                mSharedSystemSharedLibraryPackageName = null;
3039            }
3040
3041            mInstallerService = new PackageInstallerService(context, this);
3042            final Pair<ComponentName, String> instantAppResolverComponent =
3043                    getInstantAppResolverLPr();
3044            if (instantAppResolverComponent != null) {
3045                if (DEBUG_EPHEMERAL) {
3046                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3047                }
3048                mInstantAppResolverConnection = new EphemeralResolverConnection(
3049                        mContext, instantAppResolverComponent.first,
3050                        instantAppResolverComponent.second);
3051                mInstantAppResolverSettingsComponent =
3052                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3053            } else {
3054                mInstantAppResolverConnection = null;
3055                mInstantAppResolverSettingsComponent = null;
3056            }
3057            updateInstantAppInstallerLocked(null);
3058
3059            // Read and update the usage of dex files.
3060            // Do this at the end of PM init so that all the packages have their
3061            // data directory reconciled.
3062            // At this point we know the code paths of the packages, so we can validate
3063            // the disk file and build the internal cache.
3064            // The usage file is expected to be small so loading and verifying it
3065            // should take a fairly small time compare to the other activities (e.g. package
3066            // scanning).
3067            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3068            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3069            for (int userId : currentUserIds) {
3070                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3071            }
3072            mDexManager.load(userPackages);
3073            if (mIsUpgrade) {
3074                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3075                        (int) (SystemClock.uptimeMillis() - startTime));
3076            }
3077        } // synchronized (mPackages)
3078        } // synchronized (mInstallLock)
3079
3080        // Now after opening every single application zip, make sure they
3081        // are all flushed.  Not really needed, but keeps things nice and
3082        // tidy.
3083        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3084        Runtime.getRuntime().gc();
3085        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3086
3087        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3088        FallbackCategoryProvider.loadFallbacks();
3089        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3090
3091        // The initial scanning above does many calls into installd while
3092        // holding the mPackages lock, but we're mostly interested in yelling
3093        // once we have a booted system.
3094        mInstaller.setWarnIfHeld(mPackages);
3095
3096        // Expose private service for system components to use.
3097        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3098        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3099    }
3100
3101    /**
3102     * Uncompress and install stub applications.
3103     * <p>In order to save space on the system partition, some applications are shipped in a
3104     * compressed form. In addition the compressed bits for the full application, the
3105     * system image contains a tiny stub comprised of only the Android manifest.
3106     * <p>During the first boot, attempt to uncompress and install the full application. If
3107     * the application can't be installed for any reason, disable the stub and prevent
3108     * uncompressing the full application during future boots.
3109     * <p>In order to forcefully attempt an installation of a full application, go to app
3110     * settings and enable the application.
3111     */
3112    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3113        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3114            final String pkgName = stubSystemApps.get(i);
3115            // skip if the system package is already disabled
3116            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3117                stubSystemApps.remove(i);
3118                continue;
3119            }
3120            // skip if the package isn't installed (?!); this should never happen
3121            final PackageParser.Package pkg = mPackages.get(pkgName);
3122            if (pkg == null) {
3123                stubSystemApps.remove(i);
3124                continue;
3125            }
3126            // skip if the package has been disabled by the user
3127            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3128            if (ps != null) {
3129                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3130                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3131                    stubSystemApps.remove(i);
3132                    continue;
3133                }
3134            }
3135
3136            if (DEBUG_COMPRESSION) {
3137                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3138            }
3139
3140            // uncompress the binary to its eventual destination on /data
3141            final File scanFile = decompressPackage(pkg);
3142            if (scanFile == null) {
3143                continue;
3144            }
3145
3146            // install the package to replace the stub on /system
3147            try {
3148                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3149                removePackageLI(pkg, true /*chatty*/);
3150                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3151                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3152                        UserHandle.USER_SYSTEM, "android");
3153                stubSystemApps.remove(i);
3154                continue;
3155            } catch (PackageManagerException e) {
3156                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3157            }
3158
3159            // any failed attempt to install the package will be cleaned up later
3160        }
3161
3162        // disable any stub still left; these failed to install the full application
3163        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3164            final String pkgName = stubSystemApps.get(i);
3165            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3166            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3167                    UserHandle.USER_SYSTEM, "android");
3168            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3169        }
3170    }
3171
3172    private int decompressFile(File srcFile, File dstFile) throws ErrnoException {
3173        if (DEBUG_COMPRESSION) {
3174            Slog.i(TAG, "Decompress file"
3175                    + "; src: " + srcFile.getAbsolutePath()
3176                    + ", dst: " + dstFile.getAbsolutePath());
3177        }
3178        try (
3179                InputStream fileIn = new GZIPInputStream(new FileInputStream(srcFile));
3180                OutputStream fileOut = new FileOutputStream(dstFile, false /*append*/);
3181        ) {
3182            Streams.copy(fileIn, fileOut);
3183            Os.chmod(dstFile.getAbsolutePath(), 0644);
3184            return PackageManager.INSTALL_SUCCEEDED;
3185        } catch (IOException e) {
3186            logCriticalInfo(Log.ERROR, "Failed to decompress file"
3187                    + "; src: " + srcFile.getAbsolutePath()
3188                    + ", dst: " + dstFile.getAbsolutePath());
3189        }
3190        return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3191    }
3192
3193    private File[] getCompressedFiles(String codePath) {
3194        return new File(codePath).listFiles(new FilenameFilter() {
3195            @Override
3196            public boolean accept(File dir, String name) {
3197                return name.toLowerCase().endsWith(COMPRESSED_EXTENSION);
3198            }
3199        });
3200    }
3201
3202    private boolean compressedFileExists(String codePath) {
3203        final File[] compressedFiles = getCompressedFiles(codePath);
3204        return compressedFiles != null && compressedFiles.length > 0;
3205    }
3206
3207    /**
3208     * Decompresses the given package on the system image onto
3209     * the /data partition.
3210     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3211     */
3212    private File decompressPackage(PackageParser.Package pkg) {
3213        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3214        if (compressedFiles == null || compressedFiles.length == 0) {
3215            if (DEBUG_COMPRESSION) {
3216                Slog.i(TAG, "No files to decompress");
3217            }
3218            return null;
3219        }
3220        final File dstCodePath =
3221                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3222        int ret = PackageManager.INSTALL_SUCCEEDED;
3223        try {
3224            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3225            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3226            for (File srcFile : compressedFiles) {
3227                final String srcFileName = srcFile.getName();
3228                final String dstFileName = srcFileName.substring(
3229                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3230                final File dstFile = new File(dstCodePath, dstFileName);
3231                ret = decompressFile(srcFile, dstFile);
3232                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3233                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3234                            + "; pkg: " + pkg.packageName
3235                            + ", file: " + dstFileName);
3236                    break;
3237                }
3238            }
3239        } catch (ErrnoException e) {
3240            logCriticalInfo(Log.ERROR, "Failed to decompress"
3241                    + "; pkg: " + pkg.packageName
3242                    + ", err: " + e.errno);
3243        }
3244        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3245            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3246            NativeLibraryHelper.Handle handle = null;
3247            try {
3248                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3249                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3250                        null /*abiOverride*/);
3251            } catch (IOException e) {
3252                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3253                        + "; pkg: " + pkg.packageName);
3254                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3255            } finally {
3256                IoUtils.closeQuietly(handle);
3257            }
3258        }
3259        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3260            if (dstCodePath == null || !dstCodePath.exists()) {
3261                return null;
3262            }
3263            removeCodePathLI(dstCodePath);
3264            return null;
3265        }
3266        return dstCodePath;
3267    }
3268
3269    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3270        // we're only interested in updating the installer appliction when 1) it's not
3271        // already set or 2) the modified package is the installer
3272        if (mInstantAppInstallerActivity != null
3273                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3274                        .equals(modifiedPackage)) {
3275            return;
3276        }
3277        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3278    }
3279
3280    private static File preparePackageParserCache(boolean isUpgrade) {
3281        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3282            return null;
3283        }
3284
3285        // Disable package parsing on eng builds to allow for faster incremental development.
3286        if (Build.IS_ENG) {
3287            return null;
3288        }
3289
3290        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3291            Slog.i(TAG, "Disabling package parser cache due to system property.");
3292            return null;
3293        }
3294
3295        // The base directory for the package parser cache lives under /data/system/.
3296        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3297                "package_cache");
3298        if (cacheBaseDir == null) {
3299            return null;
3300        }
3301
3302        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3303        // This also serves to "GC" unused entries when the package cache version changes (which
3304        // can only happen during upgrades).
3305        if (isUpgrade) {
3306            FileUtils.deleteContents(cacheBaseDir);
3307        }
3308
3309
3310        // Return the versioned package cache directory. This is something like
3311        // "/data/system/package_cache/1"
3312        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3313
3314        // The following is a workaround to aid development on non-numbered userdebug
3315        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3316        // the system partition is newer.
3317        //
3318        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3319        // that starts with "eng." to signify that this is an engineering build and not
3320        // destined for release.
3321        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3322            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3323
3324            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3325            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3326            // in general and should not be used for production changes. In this specific case,
3327            // we know that they will work.
3328            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3329            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3330                FileUtils.deleteContents(cacheBaseDir);
3331                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3332            }
3333        }
3334
3335        return cacheDir;
3336    }
3337
3338    @Override
3339    public boolean isFirstBoot() {
3340        // allow instant applications
3341        return mFirstBoot;
3342    }
3343
3344    @Override
3345    public boolean isOnlyCoreApps() {
3346        // allow instant applications
3347        return mOnlyCore;
3348    }
3349
3350    @Override
3351    public boolean isUpgrade() {
3352        // allow instant applications
3353        return mIsUpgrade;
3354    }
3355
3356    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3357        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3358
3359        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3360                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3361                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3362        if (matches.size() == 1) {
3363            return matches.get(0).getComponentInfo().packageName;
3364        } else if (matches.size() == 0) {
3365            Log.e(TAG, "There should probably be a verifier, but, none were found");
3366            return null;
3367        }
3368        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3369    }
3370
3371    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3372        synchronized (mPackages) {
3373            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3374            if (libraryEntry == null) {
3375                throw new IllegalStateException("Missing required shared library:" + name);
3376            }
3377            return libraryEntry.apk;
3378        }
3379    }
3380
3381    private @NonNull String getRequiredInstallerLPr() {
3382        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3383        intent.addCategory(Intent.CATEGORY_DEFAULT);
3384        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3385
3386        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3387                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3388                UserHandle.USER_SYSTEM);
3389        if (matches.size() == 1) {
3390            ResolveInfo resolveInfo = matches.get(0);
3391            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3392                throw new RuntimeException("The installer must be a privileged app");
3393            }
3394            return matches.get(0).getComponentInfo().packageName;
3395        } else {
3396            throw new RuntimeException("There must be exactly one installer; found " + matches);
3397        }
3398    }
3399
3400    private @NonNull String getRequiredUninstallerLPr() {
3401        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3402        intent.addCategory(Intent.CATEGORY_DEFAULT);
3403        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3404
3405        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3406                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3407                UserHandle.USER_SYSTEM);
3408        if (resolveInfo == null ||
3409                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3410            throw new RuntimeException("There must be exactly one uninstaller; found "
3411                    + resolveInfo);
3412        }
3413        return resolveInfo.getComponentInfo().packageName;
3414    }
3415
3416    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3417        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3418
3419        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3420                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3421                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3422        ResolveInfo best = null;
3423        final int N = matches.size();
3424        for (int i = 0; i < N; i++) {
3425            final ResolveInfo cur = matches.get(i);
3426            final String packageName = cur.getComponentInfo().packageName;
3427            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3428                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3429                continue;
3430            }
3431
3432            if (best == null || cur.priority > best.priority) {
3433                best = cur;
3434            }
3435        }
3436
3437        if (best != null) {
3438            return best.getComponentInfo().getComponentName();
3439        }
3440        Slog.w(TAG, "Intent filter verifier not found");
3441        return null;
3442    }
3443
3444    @Override
3445    public @Nullable ComponentName getInstantAppResolverComponent() {
3446        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3447            return null;
3448        }
3449        synchronized (mPackages) {
3450            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3451            if (instantAppResolver == null) {
3452                return null;
3453            }
3454            return instantAppResolver.first;
3455        }
3456    }
3457
3458    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3459        final String[] packageArray =
3460                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3461        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3462            if (DEBUG_EPHEMERAL) {
3463                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3464            }
3465            return null;
3466        }
3467
3468        final int callingUid = Binder.getCallingUid();
3469        final int resolveFlags =
3470                MATCH_DIRECT_BOOT_AWARE
3471                | MATCH_DIRECT_BOOT_UNAWARE
3472                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3473        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3474        final Intent resolverIntent = new Intent(actionName);
3475        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3476                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3477        // temporarily look for the old action
3478        if (resolvers.size() == 0) {
3479            if (DEBUG_EPHEMERAL) {
3480                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3481            }
3482            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3483            resolverIntent.setAction(actionName);
3484            resolvers = queryIntentServicesInternal(resolverIntent, null,
3485                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3486        }
3487        final int N = resolvers.size();
3488        if (N == 0) {
3489            if (DEBUG_EPHEMERAL) {
3490                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3491            }
3492            return null;
3493        }
3494
3495        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3496        for (int i = 0; i < N; i++) {
3497            final ResolveInfo info = resolvers.get(i);
3498
3499            if (info.serviceInfo == null) {
3500                continue;
3501            }
3502
3503            final String packageName = info.serviceInfo.packageName;
3504            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3505                if (DEBUG_EPHEMERAL) {
3506                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3507                            + " pkg: " + packageName + ", info:" + info);
3508                }
3509                continue;
3510            }
3511
3512            if (DEBUG_EPHEMERAL) {
3513                Slog.v(TAG, "Ephemeral resolver found;"
3514                        + " pkg: " + packageName + ", info:" + info);
3515            }
3516            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3517        }
3518        if (DEBUG_EPHEMERAL) {
3519            Slog.v(TAG, "Ephemeral resolver NOT found");
3520        }
3521        return null;
3522    }
3523
3524    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3525        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3526        intent.addCategory(Intent.CATEGORY_DEFAULT);
3527        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3528
3529        final int resolveFlags =
3530                MATCH_DIRECT_BOOT_AWARE
3531                | MATCH_DIRECT_BOOT_UNAWARE
3532                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3533        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3534                resolveFlags, UserHandle.USER_SYSTEM);
3535        // temporarily look for the old action
3536        if (matches.isEmpty()) {
3537            if (DEBUG_EPHEMERAL) {
3538                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3539            }
3540            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3541            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3542                    resolveFlags, UserHandle.USER_SYSTEM);
3543        }
3544        Iterator<ResolveInfo> iter = matches.iterator();
3545        while (iter.hasNext()) {
3546            final ResolveInfo rInfo = iter.next();
3547            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3548            if (ps != null) {
3549                final PermissionsState permissionsState = ps.getPermissionsState();
3550                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3551                    continue;
3552                }
3553            }
3554            iter.remove();
3555        }
3556        if (matches.size() == 0) {
3557            return null;
3558        } else if (matches.size() == 1) {
3559            return (ActivityInfo) matches.get(0).getComponentInfo();
3560        } else {
3561            throw new RuntimeException(
3562                    "There must be at most one ephemeral installer; found " + matches);
3563        }
3564    }
3565
3566    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3567            @NonNull ComponentName resolver) {
3568        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3569                .addCategory(Intent.CATEGORY_DEFAULT)
3570                .setPackage(resolver.getPackageName());
3571        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3572        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3573                UserHandle.USER_SYSTEM);
3574        // temporarily look for the old action
3575        if (matches.isEmpty()) {
3576            if (DEBUG_EPHEMERAL) {
3577                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3578            }
3579            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3580            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3581                    UserHandle.USER_SYSTEM);
3582        }
3583        if (matches.isEmpty()) {
3584            return null;
3585        }
3586        return matches.get(0).getComponentInfo().getComponentName();
3587    }
3588
3589    private void primeDomainVerificationsLPw(int userId) {
3590        if (DEBUG_DOMAIN_VERIFICATION) {
3591            Slog.d(TAG, "Priming domain verifications in user " + userId);
3592        }
3593
3594        SystemConfig systemConfig = SystemConfig.getInstance();
3595        ArraySet<String> packages = systemConfig.getLinkedApps();
3596
3597        for (String packageName : packages) {
3598            PackageParser.Package pkg = mPackages.get(packageName);
3599            if (pkg != null) {
3600                if (!pkg.isSystemApp()) {
3601                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3602                    continue;
3603                }
3604
3605                ArraySet<String> domains = null;
3606                for (PackageParser.Activity a : pkg.activities) {
3607                    for (ActivityIntentInfo filter : a.intents) {
3608                        if (hasValidDomains(filter)) {
3609                            if (domains == null) {
3610                                domains = new ArraySet<String>();
3611                            }
3612                            domains.addAll(filter.getHostsList());
3613                        }
3614                    }
3615                }
3616
3617                if (domains != null && domains.size() > 0) {
3618                    if (DEBUG_DOMAIN_VERIFICATION) {
3619                        Slog.v(TAG, "      + " + packageName);
3620                    }
3621                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3622                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3623                    // and then 'always' in the per-user state actually used for intent resolution.
3624                    final IntentFilterVerificationInfo ivi;
3625                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3626                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3627                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3628                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3629                } else {
3630                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3631                            + "' does not handle web links");
3632                }
3633            } else {
3634                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3635            }
3636        }
3637
3638        scheduleWritePackageRestrictionsLocked(userId);
3639        scheduleWriteSettingsLocked();
3640    }
3641
3642    private void applyFactoryDefaultBrowserLPw(int userId) {
3643        // The default browser app's package name is stored in a string resource,
3644        // with a product-specific overlay used for vendor customization.
3645        String browserPkg = mContext.getResources().getString(
3646                com.android.internal.R.string.default_browser);
3647        if (!TextUtils.isEmpty(browserPkg)) {
3648            // non-empty string => required to be a known package
3649            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3650            if (ps == null) {
3651                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3652                browserPkg = null;
3653            } else {
3654                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3655            }
3656        }
3657
3658        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3659        // default.  If there's more than one, just leave everything alone.
3660        if (browserPkg == null) {
3661            calculateDefaultBrowserLPw(userId);
3662        }
3663    }
3664
3665    private void calculateDefaultBrowserLPw(int userId) {
3666        List<String> allBrowsers = resolveAllBrowserApps(userId);
3667        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3668        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3669    }
3670
3671    private List<String> resolveAllBrowserApps(int userId) {
3672        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3673        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3674                PackageManager.MATCH_ALL, userId);
3675
3676        final int count = list.size();
3677        List<String> result = new ArrayList<String>(count);
3678        for (int i=0; i<count; i++) {
3679            ResolveInfo info = list.get(i);
3680            if (info.activityInfo == null
3681                    || !info.handleAllWebDataURI
3682                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3683                    || result.contains(info.activityInfo.packageName)) {
3684                continue;
3685            }
3686            result.add(info.activityInfo.packageName);
3687        }
3688
3689        return result;
3690    }
3691
3692    private boolean packageIsBrowser(String packageName, int userId) {
3693        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3694                PackageManager.MATCH_ALL, userId);
3695        final int N = list.size();
3696        for (int i = 0; i < N; i++) {
3697            ResolveInfo info = list.get(i);
3698            if (packageName.equals(info.activityInfo.packageName)) {
3699                return true;
3700            }
3701        }
3702        return false;
3703    }
3704
3705    private void checkDefaultBrowser() {
3706        final int myUserId = UserHandle.myUserId();
3707        final String packageName = getDefaultBrowserPackageName(myUserId);
3708        if (packageName != null) {
3709            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3710            if (info == null) {
3711                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3712                synchronized (mPackages) {
3713                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3714                }
3715            }
3716        }
3717    }
3718
3719    @Override
3720    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3721            throws RemoteException {
3722        try {
3723            return super.onTransact(code, data, reply, flags);
3724        } catch (RuntimeException e) {
3725            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3726                Slog.wtf(TAG, "Package Manager Crash", e);
3727            }
3728            throw e;
3729        }
3730    }
3731
3732    static int[] appendInts(int[] cur, int[] add) {
3733        if (add == null) return cur;
3734        if (cur == null) return add;
3735        final int N = add.length;
3736        for (int i=0; i<N; i++) {
3737            cur = appendInt(cur, add[i]);
3738        }
3739        return cur;
3740    }
3741
3742    /**
3743     * Returns whether or not a full application can see an instant application.
3744     * <p>
3745     * Currently, there are three cases in which this can occur:
3746     * <ol>
3747     * <li>The calling application is a "special" process. The special
3748     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3749     *     and {@code 0}</li>
3750     * <li>The calling application has the permission
3751     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3752     * <li>The calling application is the default launcher on the
3753     *     system partition.</li>
3754     * </ol>
3755     */
3756    private boolean canViewInstantApps(int callingUid, int userId) {
3757        if (callingUid == Process.SYSTEM_UID
3758                || callingUid == Process.SHELL_UID
3759                || callingUid == Process.ROOT_UID) {
3760            return true;
3761        }
3762        if (mContext.checkCallingOrSelfPermission(
3763                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3764            return true;
3765        }
3766        if (mContext.checkCallingOrSelfPermission(
3767                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3768            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3769            if (homeComponent != null
3770                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3771                return true;
3772            }
3773        }
3774        return false;
3775    }
3776
3777    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3778        if (!sUserManager.exists(userId)) return null;
3779        if (ps == null) {
3780            return null;
3781        }
3782        PackageParser.Package p = ps.pkg;
3783        if (p == null) {
3784            return null;
3785        }
3786        final int callingUid = Binder.getCallingUid();
3787        // Filter out ephemeral app metadata:
3788        //   * The system/shell/root can see metadata for any app
3789        //   * An installed app can see metadata for 1) other installed apps
3790        //     and 2) ephemeral apps that have explicitly interacted with it
3791        //   * Ephemeral apps can only see their own data and exposed installed apps
3792        //   * Holding a signature permission allows seeing instant apps
3793        if (filterAppAccessLPr(ps, callingUid, userId)) {
3794            return null;
3795        }
3796
3797        final PermissionsState permissionsState = ps.getPermissionsState();
3798
3799        // Compute GIDs only if requested
3800        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3801                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3802        // Compute granted permissions only if package has requested permissions
3803        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3804                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3805        final PackageUserState state = ps.readUserState(userId);
3806
3807        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3808                && ps.isSystem()) {
3809            flags |= MATCH_ANY_USER;
3810        }
3811
3812        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3813                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3814
3815        if (packageInfo == null) {
3816            return null;
3817        }
3818
3819        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3820                resolveExternalPackageNameLPr(p);
3821
3822        return packageInfo;
3823    }
3824
3825    @Override
3826    public void checkPackageStartable(String packageName, int userId) {
3827        final int callingUid = Binder.getCallingUid();
3828        if (getInstantAppPackageName(callingUid) != null) {
3829            throw new SecurityException("Instant applications don't have access to this method");
3830        }
3831        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3832        synchronized (mPackages) {
3833            final PackageSetting ps = mSettings.mPackages.get(packageName);
3834            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3835                throw new SecurityException("Package " + packageName + " was not found!");
3836            }
3837
3838            if (!ps.getInstalled(userId)) {
3839                throw new SecurityException(
3840                        "Package " + packageName + " was not installed for user " + userId + "!");
3841            }
3842
3843            if (mSafeMode && !ps.isSystem()) {
3844                throw new SecurityException("Package " + packageName + " not a system app!");
3845            }
3846
3847            if (mFrozenPackages.contains(packageName)) {
3848                throw new SecurityException("Package " + packageName + " is currently frozen!");
3849            }
3850
3851            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3852                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3853                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3854            }
3855        }
3856    }
3857
3858    @Override
3859    public boolean isPackageAvailable(String packageName, int userId) {
3860        if (!sUserManager.exists(userId)) return false;
3861        final int callingUid = Binder.getCallingUid();
3862        enforceCrossUserPermission(callingUid, userId,
3863                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3864        synchronized (mPackages) {
3865            PackageParser.Package p = mPackages.get(packageName);
3866            if (p != null) {
3867                final PackageSetting ps = (PackageSetting) p.mExtras;
3868                if (filterAppAccessLPr(ps, callingUid, userId)) {
3869                    return false;
3870                }
3871                if (ps != null) {
3872                    final PackageUserState state = ps.readUserState(userId);
3873                    if (state != null) {
3874                        return PackageParser.isAvailable(state);
3875                    }
3876                }
3877            }
3878        }
3879        return false;
3880    }
3881
3882    @Override
3883    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3884        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3885                flags, Binder.getCallingUid(), userId);
3886    }
3887
3888    @Override
3889    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3890            int flags, int userId) {
3891        return getPackageInfoInternal(versionedPackage.getPackageName(),
3892                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3893    }
3894
3895    /**
3896     * Important: The provided filterCallingUid is used exclusively to filter out packages
3897     * that can be seen based on user state. It's typically the original caller uid prior
3898     * to clearing. Because it can only be provided by trusted code, it's value can be
3899     * trusted and will be used as-is; unlike userId which will be validated by this method.
3900     */
3901    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3902            int flags, int filterCallingUid, int userId) {
3903        if (!sUserManager.exists(userId)) return null;
3904        flags = updateFlagsForPackage(flags, userId, packageName);
3905        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3906                false /* requireFullPermission */, false /* checkShell */, "get package info");
3907
3908        // reader
3909        synchronized (mPackages) {
3910            // Normalize package name to handle renamed packages and static libs
3911            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3912
3913            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3914            if (matchFactoryOnly) {
3915                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3916                if (ps != null) {
3917                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3918                        return null;
3919                    }
3920                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3921                        return null;
3922                    }
3923                    return generatePackageInfo(ps, flags, userId);
3924                }
3925            }
3926
3927            PackageParser.Package p = mPackages.get(packageName);
3928            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3929                return null;
3930            }
3931            if (DEBUG_PACKAGE_INFO)
3932                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3933            if (p != null) {
3934                final PackageSetting ps = (PackageSetting) p.mExtras;
3935                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3936                    return null;
3937                }
3938                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3939                    return null;
3940                }
3941                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3942            }
3943            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3944                final PackageSetting ps = mSettings.mPackages.get(packageName);
3945                if (ps == null) return null;
3946                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3947                    return null;
3948                }
3949                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3950                    return null;
3951                }
3952                return generatePackageInfo(ps, flags, userId);
3953            }
3954        }
3955        return null;
3956    }
3957
3958    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3959        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3960            return true;
3961        }
3962        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3963            return true;
3964        }
3965        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3966            return true;
3967        }
3968        return false;
3969    }
3970
3971    private boolean isComponentVisibleToInstantApp(
3972            @Nullable ComponentName component, @ComponentType int type) {
3973        if (type == TYPE_ACTIVITY) {
3974            final PackageParser.Activity activity = mActivities.mActivities.get(component);
3975            return activity != null
3976                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3977                    : false;
3978        } else if (type == TYPE_RECEIVER) {
3979            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
3980            return activity != null
3981                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3982                    : false;
3983        } else if (type == TYPE_SERVICE) {
3984            final PackageParser.Service service = mServices.mServices.get(component);
3985            return service != null
3986                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3987                    : false;
3988        } else if (type == TYPE_PROVIDER) {
3989            final PackageParser.Provider provider = mProviders.mProviders.get(component);
3990            return provider != null
3991                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3992                    : false;
3993        } else if (type == TYPE_UNKNOWN) {
3994            return isComponentVisibleToInstantApp(component);
3995        }
3996        return false;
3997    }
3998
3999    /**
4000     * Returns whether or not access to the application should be filtered.
4001     * <p>
4002     * Access may be limited based upon whether the calling or target applications
4003     * are instant applications.
4004     *
4005     * @see #canAccessInstantApps(int)
4006     */
4007    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4008            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4009        // if we're in an isolated process, get the real calling UID
4010        if (Process.isIsolated(callingUid)) {
4011            callingUid = mIsolatedOwners.get(callingUid);
4012        }
4013        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4014        final boolean callerIsInstantApp = instantAppPkgName != null;
4015        if (ps == null) {
4016            if (callerIsInstantApp) {
4017                // pretend the application exists, but, needs to be filtered
4018                return true;
4019            }
4020            return false;
4021        }
4022        // if the target and caller are the same application, don't filter
4023        if (isCallerSameApp(ps.name, callingUid)) {
4024            return false;
4025        }
4026        if (callerIsInstantApp) {
4027            // request for a specific component; if it hasn't been explicitly exposed, filter
4028            if (component != null) {
4029                return !isComponentVisibleToInstantApp(component, componentType);
4030            }
4031            // request for application; if no components have been explicitly exposed, filter
4032            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
4033        }
4034        if (ps.getInstantApp(userId)) {
4035            // caller can see all components of all instant applications, don't filter
4036            if (canViewInstantApps(callingUid, userId)) {
4037                return false;
4038            }
4039            // request for a specific instant application component, filter
4040            if (component != null) {
4041                return true;
4042            }
4043            // request for an instant application; if the caller hasn't been granted access, filter
4044            return !mInstantAppRegistry.isInstantAccessGranted(
4045                    userId, UserHandle.getAppId(callingUid), ps.appId);
4046        }
4047        return false;
4048    }
4049
4050    /**
4051     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4052     */
4053    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4054        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4055    }
4056
4057    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4058            int flags) {
4059        // Callers can access only the libs they depend on, otherwise they need to explicitly
4060        // ask for the shared libraries given the caller is allowed to access all static libs.
4061        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4062            // System/shell/root get to see all static libs
4063            final int appId = UserHandle.getAppId(uid);
4064            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4065                    || appId == Process.ROOT_UID) {
4066                return false;
4067            }
4068        }
4069
4070        // No package means no static lib as it is always on internal storage
4071        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4072            return false;
4073        }
4074
4075        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4076                ps.pkg.staticSharedLibVersion);
4077        if (libEntry == null) {
4078            return false;
4079        }
4080
4081        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4082        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4083        if (uidPackageNames == null) {
4084            return true;
4085        }
4086
4087        for (String uidPackageName : uidPackageNames) {
4088            if (ps.name.equals(uidPackageName)) {
4089                return false;
4090            }
4091            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4092            if (uidPs != null) {
4093                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4094                        libEntry.info.getName());
4095                if (index < 0) {
4096                    continue;
4097                }
4098                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
4099                    return false;
4100                }
4101            }
4102        }
4103        return true;
4104    }
4105
4106    @Override
4107    public String[] currentToCanonicalPackageNames(String[] names) {
4108        final int callingUid = Binder.getCallingUid();
4109        if (getInstantAppPackageName(callingUid) != null) {
4110            return names;
4111        }
4112        final String[] out = new String[names.length];
4113        // reader
4114        synchronized (mPackages) {
4115            final int callingUserId = UserHandle.getUserId(callingUid);
4116            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4117            for (int i=names.length-1; i>=0; i--) {
4118                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4119                boolean translateName = false;
4120                if (ps != null && ps.realName != null) {
4121                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4122                    translateName = !targetIsInstantApp
4123                            || canViewInstantApps
4124                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4125                                    UserHandle.getAppId(callingUid), ps.appId);
4126                }
4127                out[i] = translateName ? ps.realName : names[i];
4128            }
4129        }
4130        return out;
4131    }
4132
4133    @Override
4134    public String[] canonicalToCurrentPackageNames(String[] names) {
4135        final int callingUid = Binder.getCallingUid();
4136        if (getInstantAppPackageName(callingUid) != null) {
4137            return names;
4138        }
4139        final String[] out = new String[names.length];
4140        // reader
4141        synchronized (mPackages) {
4142            final int callingUserId = UserHandle.getUserId(callingUid);
4143            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4144            for (int i=names.length-1; i>=0; i--) {
4145                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4146                boolean translateName = false;
4147                if (cur != null) {
4148                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4149                    final boolean targetIsInstantApp =
4150                            ps != null && ps.getInstantApp(callingUserId);
4151                    translateName = !targetIsInstantApp
4152                            || canViewInstantApps
4153                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4154                                    UserHandle.getAppId(callingUid), ps.appId);
4155                }
4156                out[i] = translateName ? cur : names[i];
4157            }
4158        }
4159        return out;
4160    }
4161
4162    @Override
4163    public int getPackageUid(String packageName, int flags, int userId) {
4164        if (!sUserManager.exists(userId)) return -1;
4165        final int callingUid = Binder.getCallingUid();
4166        flags = updateFlagsForPackage(flags, userId, packageName);
4167        enforceCrossUserPermission(callingUid, userId,
4168                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4169
4170        // reader
4171        synchronized (mPackages) {
4172            final PackageParser.Package p = mPackages.get(packageName);
4173            if (p != null && p.isMatch(flags)) {
4174                PackageSetting ps = (PackageSetting) p.mExtras;
4175                if (filterAppAccessLPr(ps, callingUid, userId)) {
4176                    return -1;
4177                }
4178                return UserHandle.getUid(userId, p.applicationInfo.uid);
4179            }
4180            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4181                final PackageSetting ps = mSettings.mPackages.get(packageName);
4182                if (ps != null && ps.isMatch(flags)
4183                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4184                    return UserHandle.getUid(userId, ps.appId);
4185                }
4186            }
4187        }
4188
4189        return -1;
4190    }
4191
4192    @Override
4193    public int[] getPackageGids(String packageName, int flags, int userId) {
4194        if (!sUserManager.exists(userId)) return null;
4195        final int callingUid = Binder.getCallingUid();
4196        flags = updateFlagsForPackage(flags, userId, packageName);
4197        enforceCrossUserPermission(callingUid, userId,
4198                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4199
4200        // reader
4201        synchronized (mPackages) {
4202            final PackageParser.Package p = mPackages.get(packageName);
4203            if (p != null && p.isMatch(flags)) {
4204                PackageSetting ps = (PackageSetting) p.mExtras;
4205                if (filterAppAccessLPr(ps, callingUid, userId)) {
4206                    return null;
4207                }
4208                // TODO: Shouldn't this be checking for package installed state for userId and
4209                // return null?
4210                return ps.getPermissionsState().computeGids(userId);
4211            }
4212            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4213                final PackageSetting ps = mSettings.mPackages.get(packageName);
4214                if (ps != null && ps.isMatch(flags)
4215                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4216                    return ps.getPermissionsState().computeGids(userId);
4217                }
4218            }
4219        }
4220
4221        return null;
4222    }
4223
4224    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
4225        if (bp.perm != null) {
4226            return PackageParser.generatePermissionInfo(bp.perm, flags);
4227        }
4228        PermissionInfo pi = new PermissionInfo();
4229        pi.name = bp.name;
4230        pi.packageName = bp.sourcePackage;
4231        pi.nonLocalizedLabel = bp.name;
4232        pi.protectionLevel = bp.protectionLevel;
4233        return pi;
4234    }
4235
4236    @Override
4237    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4238        final int callingUid = Binder.getCallingUid();
4239        if (getInstantAppPackageName(callingUid) != null) {
4240            return null;
4241        }
4242        // reader
4243        synchronized (mPackages) {
4244            final BasePermission p = mSettings.mPermissions.get(name);
4245            if (p == null) {
4246                return null;
4247            }
4248            // If the caller is an app that targets pre 26 SDK drop protection flags.
4249            final PermissionInfo permissionInfo = generatePermissionInfo(p, flags);
4250            if (permissionInfo != null) {
4251                permissionInfo.protectionLevel = adjustPermissionProtectionFlagsLPr(
4252                        permissionInfo.protectionLevel, packageName, callingUid);
4253            }
4254            return permissionInfo;
4255        }
4256    }
4257
4258    private int adjustPermissionProtectionFlagsLPr(int protectionLevel,
4259            String packageName, int uid) {
4260        // Signature permission flags area always reported
4261        final int protectionLevelMasked = protectionLevel
4262                & (PermissionInfo.PROTECTION_NORMAL
4263                | PermissionInfo.PROTECTION_DANGEROUS
4264                | PermissionInfo.PROTECTION_SIGNATURE);
4265        if (protectionLevelMasked == PermissionInfo.PROTECTION_SIGNATURE) {
4266            return protectionLevel;
4267        }
4268
4269        // System sees all flags.
4270        final int appId = UserHandle.getAppId(uid);
4271        if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID
4272                || appId == Process.SHELL_UID) {
4273            return protectionLevel;
4274        }
4275
4276        // Normalize package name to handle renamed packages and static libs
4277        packageName = resolveInternalPackageNameLPr(packageName,
4278                PackageManager.VERSION_CODE_HIGHEST);
4279
4280        // Apps that target O see flags for all protection levels.
4281        final PackageSetting ps = mSettings.mPackages.get(packageName);
4282        if (ps == null) {
4283            return protectionLevel;
4284        }
4285        if (ps.appId != appId) {
4286            return protectionLevel;
4287        }
4288
4289        final PackageParser.Package pkg = mPackages.get(packageName);
4290        if (pkg == null) {
4291            return protectionLevel;
4292        }
4293        if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
4294            return protectionLevelMasked;
4295        }
4296
4297        return protectionLevel;
4298    }
4299
4300    @Override
4301    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
4302            int flags) {
4303        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4304            return null;
4305        }
4306        // reader
4307        synchronized (mPackages) {
4308            if (group != null && !mPermissionGroups.containsKey(group)) {
4309                // This is thrown as NameNotFoundException
4310                return null;
4311            }
4312
4313            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4314            for (BasePermission p : mSettings.mPermissions.values()) {
4315                if (group == null) {
4316                    if (p.perm == null || p.perm.info.group == null) {
4317                        out.add(generatePermissionInfo(p, flags));
4318                    }
4319                } else {
4320                    if (p.perm != null && group.equals(p.perm.info.group)) {
4321                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
4322                    }
4323                }
4324            }
4325            return new ParceledListSlice<>(out);
4326        }
4327    }
4328
4329    @Override
4330    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4331        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4332            return null;
4333        }
4334        // reader
4335        synchronized (mPackages) {
4336            return PackageParser.generatePermissionGroupInfo(
4337                    mPermissionGroups.get(name), flags);
4338        }
4339    }
4340
4341    @Override
4342    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4343        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4344            return ParceledListSlice.emptyList();
4345        }
4346        // reader
4347        synchronized (mPackages) {
4348            final int N = mPermissionGroups.size();
4349            ArrayList<PermissionGroupInfo> out
4350                    = new ArrayList<PermissionGroupInfo>(N);
4351            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4352                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4353            }
4354            return new ParceledListSlice<>(out);
4355        }
4356    }
4357
4358    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4359            int filterCallingUid, int userId) {
4360        if (!sUserManager.exists(userId)) return null;
4361        PackageSetting ps = mSettings.mPackages.get(packageName);
4362        if (ps != null) {
4363            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4364                return null;
4365            }
4366            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4367                return null;
4368            }
4369            if (ps.pkg == null) {
4370                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4371                if (pInfo != null) {
4372                    return pInfo.applicationInfo;
4373                }
4374                return null;
4375            }
4376            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4377                    ps.readUserState(userId), userId);
4378            if (ai != null) {
4379                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4380            }
4381            return ai;
4382        }
4383        return null;
4384    }
4385
4386    @Override
4387    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4388        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4389    }
4390
4391    /**
4392     * Important: The provided filterCallingUid is used exclusively to filter out applications
4393     * that can be seen based on user state. It's typically the original caller uid prior
4394     * to clearing. Because it can only be provided by trusted code, it's value can be
4395     * trusted and will be used as-is; unlike userId which will be validated by this method.
4396     */
4397    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4398            int filterCallingUid, int userId) {
4399        if (!sUserManager.exists(userId)) return null;
4400        flags = updateFlagsForApplication(flags, userId, packageName);
4401        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4402                false /* requireFullPermission */, false /* checkShell */, "get application info");
4403
4404        // writer
4405        synchronized (mPackages) {
4406            // Normalize package name to handle renamed packages and static libs
4407            packageName = resolveInternalPackageNameLPr(packageName,
4408                    PackageManager.VERSION_CODE_HIGHEST);
4409
4410            PackageParser.Package p = mPackages.get(packageName);
4411            if (DEBUG_PACKAGE_INFO) Log.v(
4412                    TAG, "getApplicationInfo " + packageName
4413                    + ": " + p);
4414            if (p != null) {
4415                PackageSetting ps = mSettings.mPackages.get(packageName);
4416                if (ps == null) return null;
4417                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4418                    return null;
4419                }
4420                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4421                    return null;
4422                }
4423                // Note: isEnabledLP() does not apply here - always return info
4424                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4425                        p, flags, ps.readUserState(userId), userId);
4426                if (ai != null) {
4427                    ai.packageName = resolveExternalPackageNameLPr(p);
4428                }
4429                return ai;
4430            }
4431            if ("android".equals(packageName)||"system".equals(packageName)) {
4432                return mAndroidApplication;
4433            }
4434            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4435                // Already generates the external package name
4436                return generateApplicationInfoFromSettingsLPw(packageName,
4437                        flags, filterCallingUid, userId);
4438            }
4439        }
4440        return null;
4441    }
4442
4443    private String normalizePackageNameLPr(String packageName) {
4444        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4445        return normalizedPackageName != null ? normalizedPackageName : packageName;
4446    }
4447
4448    @Override
4449    public void deletePreloadsFileCache() {
4450        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4451            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4452        }
4453        File dir = Environment.getDataPreloadsFileCacheDirectory();
4454        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4455        FileUtils.deleteContents(dir);
4456    }
4457
4458    @Override
4459    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4460            final int storageFlags, final IPackageDataObserver observer) {
4461        mContext.enforceCallingOrSelfPermission(
4462                android.Manifest.permission.CLEAR_APP_CACHE, null);
4463        mHandler.post(() -> {
4464            boolean success = false;
4465            try {
4466                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4467                success = true;
4468            } catch (IOException e) {
4469                Slog.w(TAG, e);
4470            }
4471            if (observer != null) {
4472                try {
4473                    observer.onRemoveCompleted(null, success);
4474                } catch (RemoteException e) {
4475                    Slog.w(TAG, e);
4476                }
4477            }
4478        });
4479    }
4480
4481    @Override
4482    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4483            final int storageFlags, final IntentSender pi) {
4484        mContext.enforceCallingOrSelfPermission(
4485                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4486        mHandler.post(() -> {
4487            boolean success = false;
4488            try {
4489                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4490                success = true;
4491            } catch (IOException e) {
4492                Slog.w(TAG, e);
4493            }
4494            if (pi != null) {
4495                try {
4496                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4497                } catch (SendIntentException e) {
4498                    Slog.w(TAG, e);
4499                }
4500            }
4501        });
4502    }
4503
4504    /**
4505     * Blocking call to clear various types of cached data across the system
4506     * until the requested bytes are available.
4507     */
4508    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4509        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4510        final File file = storage.findPathForUuid(volumeUuid);
4511        if (file.getUsableSpace() >= bytes) return;
4512
4513        if (ENABLE_FREE_CACHE_V2) {
4514            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4515                    volumeUuid);
4516            final boolean aggressive = (storageFlags
4517                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4518            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4519
4520            // 1. Pre-flight to determine if we have any chance to succeed
4521            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4522            if (internalVolume && (aggressive || SystemProperties
4523                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4524                deletePreloadsFileCache();
4525                if (file.getUsableSpace() >= bytes) return;
4526            }
4527
4528            // 3. Consider parsed APK data (aggressive only)
4529            if (internalVolume && aggressive) {
4530                FileUtils.deleteContents(mCacheDir);
4531                if (file.getUsableSpace() >= bytes) return;
4532            }
4533
4534            // 4. Consider cached app data (above quotas)
4535            try {
4536                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4537                        Installer.FLAG_FREE_CACHE_V2);
4538            } catch (InstallerException ignored) {
4539            }
4540            if (file.getUsableSpace() >= bytes) return;
4541
4542            // 5. Consider shared libraries with refcount=0 and age>min cache period
4543            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4544                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4545                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4546                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4547                return;
4548            }
4549
4550            // 6. Consider dexopt output (aggressive only)
4551            // TODO: Implement
4552
4553            // 7. Consider installed instant apps unused longer than min cache period
4554            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4555                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4556                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4557                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4558                return;
4559            }
4560
4561            // 8. Consider cached app data (below quotas)
4562            try {
4563                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4564                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4565            } catch (InstallerException ignored) {
4566            }
4567            if (file.getUsableSpace() >= bytes) return;
4568
4569            // 9. Consider DropBox entries
4570            // TODO: Implement
4571
4572            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4573            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4574                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4575                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4576                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4577                return;
4578            }
4579        } else {
4580            try {
4581                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4582            } catch (InstallerException ignored) {
4583            }
4584            if (file.getUsableSpace() >= bytes) return;
4585        }
4586
4587        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4588    }
4589
4590    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4591            throws IOException {
4592        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4593        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4594
4595        List<VersionedPackage> packagesToDelete = null;
4596        final long now = System.currentTimeMillis();
4597
4598        synchronized (mPackages) {
4599            final int[] allUsers = sUserManager.getUserIds();
4600            final int libCount = mSharedLibraries.size();
4601            for (int i = 0; i < libCount; i++) {
4602                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4603                if (versionedLib == null) {
4604                    continue;
4605                }
4606                final int versionCount = versionedLib.size();
4607                for (int j = 0; j < versionCount; j++) {
4608                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4609                    // Skip packages that are not static shared libs.
4610                    if (!libInfo.isStatic()) {
4611                        break;
4612                    }
4613                    // Important: We skip static shared libs used for some user since
4614                    // in such a case we need to keep the APK on the device. The check for
4615                    // a lib being used for any user is performed by the uninstall call.
4616                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4617                    // Resolve the package name - we use synthetic package names internally
4618                    final String internalPackageName = resolveInternalPackageNameLPr(
4619                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4620                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4621                    // Skip unused static shared libs cached less than the min period
4622                    // to prevent pruning a lib needed by a subsequently installed package.
4623                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4624                        continue;
4625                    }
4626                    if (packagesToDelete == null) {
4627                        packagesToDelete = new ArrayList<>();
4628                    }
4629                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4630                            declaringPackage.getVersionCode()));
4631                }
4632            }
4633        }
4634
4635        if (packagesToDelete != null) {
4636            final int packageCount = packagesToDelete.size();
4637            for (int i = 0; i < packageCount; i++) {
4638                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4639                // Delete the package synchronously (will fail of the lib used for any user).
4640                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4641                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4642                                == PackageManager.DELETE_SUCCEEDED) {
4643                    if (volume.getUsableSpace() >= neededSpace) {
4644                        return true;
4645                    }
4646                }
4647            }
4648        }
4649
4650        return false;
4651    }
4652
4653    /**
4654     * Update given flags based on encryption status of current user.
4655     */
4656    private int updateFlags(int flags, int userId) {
4657        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4658                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4659            // Caller expressed an explicit opinion about what encryption
4660            // aware/unaware components they want to see, so fall through and
4661            // give them what they want
4662        } else {
4663            // Caller expressed no opinion, so match based on user state
4664            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4665                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4666            } else {
4667                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4668            }
4669        }
4670        return flags;
4671    }
4672
4673    private UserManagerInternal getUserManagerInternal() {
4674        if (mUserManagerInternal == null) {
4675            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4676        }
4677        return mUserManagerInternal;
4678    }
4679
4680    private DeviceIdleController.LocalService getDeviceIdleController() {
4681        if (mDeviceIdleController == null) {
4682            mDeviceIdleController =
4683                    LocalServices.getService(DeviceIdleController.LocalService.class);
4684        }
4685        return mDeviceIdleController;
4686    }
4687
4688    /**
4689     * Update given flags when being used to request {@link PackageInfo}.
4690     */
4691    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4692        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4693        boolean triaged = true;
4694        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4695                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4696            // Caller is asking for component details, so they'd better be
4697            // asking for specific encryption matching behavior, or be triaged
4698            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4699                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4700                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4701                triaged = false;
4702            }
4703        }
4704        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4705                | PackageManager.MATCH_SYSTEM_ONLY
4706                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4707            triaged = false;
4708        }
4709        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4710            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4711                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4712                    + Debug.getCallers(5));
4713        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4714                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4715            // If the caller wants all packages and has a restricted profile associated with it,
4716            // then match all users. This is to make sure that launchers that need to access work
4717            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4718            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4719            flags |= PackageManager.MATCH_ANY_USER;
4720        }
4721        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4722            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4723                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4724        }
4725        return updateFlags(flags, userId);
4726    }
4727
4728    /**
4729     * Update given flags when being used to request {@link ApplicationInfo}.
4730     */
4731    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4732        return updateFlagsForPackage(flags, userId, cookie);
4733    }
4734
4735    /**
4736     * Update given flags when being used to request {@link ComponentInfo}.
4737     */
4738    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4739        if (cookie instanceof Intent) {
4740            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4741                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4742            }
4743        }
4744
4745        boolean triaged = true;
4746        // Caller is asking for component details, so they'd better be
4747        // asking for specific encryption matching behavior, or be triaged
4748        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4749                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4750                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4751            triaged = false;
4752        }
4753        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4754            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4755                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4756        }
4757
4758        return updateFlags(flags, userId);
4759    }
4760
4761    /**
4762     * Update given intent when being used to request {@link ResolveInfo}.
4763     */
4764    private Intent updateIntentForResolve(Intent intent) {
4765        if (intent.getSelector() != null) {
4766            intent = intent.getSelector();
4767        }
4768        if (DEBUG_PREFERRED) {
4769            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4770        }
4771        return intent;
4772    }
4773
4774    /**
4775     * Update given flags when being used to request {@link ResolveInfo}.
4776     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4777     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4778     * flag set. However, this flag is only honoured in three circumstances:
4779     * <ul>
4780     * <li>when called from a system process</li>
4781     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4782     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4783     * action and a {@code android.intent.category.BROWSABLE} category</li>
4784     * </ul>
4785     */
4786    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4787        return updateFlagsForResolve(flags, userId, intent, callingUid,
4788                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4789    }
4790    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4791            boolean wantInstantApps) {
4792        return updateFlagsForResolve(flags, userId, intent, callingUid,
4793                wantInstantApps, false /*onlyExposedExplicitly*/);
4794    }
4795    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4796            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4797        // Safe mode means we shouldn't match any third-party components
4798        if (mSafeMode) {
4799            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4800        }
4801        if (getInstantAppPackageName(callingUid) != null) {
4802            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4803            if (onlyExposedExplicitly) {
4804                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4805            }
4806            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4807            flags |= PackageManager.MATCH_INSTANT;
4808        } else {
4809            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4810            final boolean allowMatchInstant =
4811                    (wantInstantApps
4812                            && Intent.ACTION_VIEW.equals(intent.getAction())
4813                            && hasWebURI(intent))
4814                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4815            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4816                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4817            if (!allowMatchInstant) {
4818                flags &= ~PackageManager.MATCH_INSTANT;
4819            }
4820        }
4821        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4822    }
4823
4824    @Override
4825    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4826        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4827    }
4828
4829    /**
4830     * Important: The provided filterCallingUid is used exclusively to filter out activities
4831     * that can be seen based on user state. It's typically the original caller uid prior
4832     * to clearing. Because it can only be provided by trusted code, it's value can be
4833     * trusted and will be used as-is; unlike userId which will be validated by this method.
4834     */
4835    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4836            int filterCallingUid, int userId) {
4837        if (!sUserManager.exists(userId)) return null;
4838        flags = updateFlagsForComponent(flags, userId, component);
4839        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4840                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4841        synchronized (mPackages) {
4842            PackageParser.Activity a = mActivities.mActivities.get(component);
4843
4844            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4845            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4846                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4847                if (ps == null) return null;
4848                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4849                    return null;
4850                }
4851                return PackageParser.generateActivityInfo(
4852                        a, flags, ps.readUserState(userId), userId);
4853            }
4854            if (mResolveComponentName.equals(component)) {
4855                return PackageParser.generateActivityInfo(
4856                        mResolveActivity, flags, new PackageUserState(), userId);
4857            }
4858        }
4859        return null;
4860    }
4861
4862    @Override
4863    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4864            String resolvedType) {
4865        synchronized (mPackages) {
4866            if (component.equals(mResolveComponentName)) {
4867                // The resolver supports EVERYTHING!
4868                return true;
4869            }
4870            final int callingUid = Binder.getCallingUid();
4871            final int callingUserId = UserHandle.getUserId(callingUid);
4872            PackageParser.Activity a = mActivities.mActivities.get(component);
4873            if (a == null) {
4874                return false;
4875            }
4876            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4877            if (ps == null) {
4878                return false;
4879            }
4880            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4881                return false;
4882            }
4883            for (int i=0; i<a.intents.size(); i++) {
4884                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4885                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4886                    return true;
4887                }
4888            }
4889            return false;
4890        }
4891    }
4892
4893    @Override
4894    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4895        if (!sUserManager.exists(userId)) return null;
4896        final int callingUid = Binder.getCallingUid();
4897        flags = updateFlagsForComponent(flags, userId, component);
4898        enforceCrossUserPermission(callingUid, userId,
4899                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4900        synchronized (mPackages) {
4901            PackageParser.Activity a = mReceivers.mActivities.get(component);
4902            if (DEBUG_PACKAGE_INFO) Log.v(
4903                TAG, "getReceiverInfo " + component + ": " + a);
4904            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4905                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4906                if (ps == null) return null;
4907                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4908                    return null;
4909                }
4910                return PackageParser.generateActivityInfo(
4911                        a, flags, ps.readUserState(userId), userId);
4912            }
4913        }
4914        return null;
4915    }
4916
4917    @Override
4918    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4919            int flags, int userId) {
4920        if (!sUserManager.exists(userId)) return null;
4921        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4922        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4923            return null;
4924        }
4925
4926        flags = updateFlagsForPackage(flags, userId, null);
4927
4928        final boolean canSeeStaticLibraries =
4929                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4930                        == PERMISSION_GRANTED
4931                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4932                        == PERMISSION_GRANTED
4933                || canRequestPackageInstallsInternal(packageName,
4934                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4935                        false  /* throwIfPermNotDeclared*/)
4936                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4937                        == PERMISSION_GRANTED;
4938
4939        synchronized (mPackages) {
4940            List<SharedLibraryInfo> result = null;
4941
4942            final int libCount = mSharedLibraries.size();
4943            for (int i = 0; i < libCount; i++) {
4944                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4945                if (versionedLib == null) {
4946                    continue;
4947                }
4948
4949                final int versionCount = versionedLib.size();
4950                for (int j = 0; j < versionCount; j++) {
4951                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4952                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4953                        break;
4954                    }
4955                    final long identity = Binder.clearCallingIdentity();
4956                    try {
4957                        PackageInfo packageInfo = getPackageInfoVersioned(
4958                                libInfo.getDeclaringPackage(), flags
4959                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4960                        if (packageInfo == null) {
4961                            continue;
4962                        }
4963                    } finally {
4964                        Binder.restoreCallingIdentity(identity);
4965                    }
4966
4967                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4968                            libInfo.getVersion(), libInfo.getType(),
4969                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4970                            flags, userId));
4971
4972                    if (result == null) {
4973                        result = new ArrayList<>();
4974                    }
4975                    result.add(resLibInfo);
4976                }
4977            }
4978
4979            return result != null ? new ParceledListSlice<>(result) : null;
4980        }
4981    }
4982
4983    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4984            SharedLibraryInfo libInfo, int flags, int userId) {
4985        List<VersionedPackage> versionedPackages = null;
4986        final int packageCount = mSettings.mPackages.size();
4987        for (int i = 0; i < packageCount; i++) {
4988            PackageSetting ps = mSettings.mPackages.valueAt(i);
4989
4990            if (ps == null) {
4991                continue;
4992            }
4993
4994            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4995                continue;
4996            }
4997
4998            final String libName = libInfo.getName();
4999            if (libInfo.isStatic()) {
5000                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
5001                if (libIdx < 0) {
5002                    continue;
5003                }
5004                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
5005                    continue;
5006                }
5007                if (versionedPackages == null) {
5008                    versionedPackages = new ArrayList<>();
5009                }
5010                // If the dependent is a static shared lib, use the public package name
5011                String dependentPackageName = ps.name;
5012                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
5013                    dependentPackageName = ps.pkg.manifestPackageName;
5014                }
5015                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
5016            } else if (ps.pkg != null) {
5017                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5018                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5019                    if (versionedPackages == null) {
5020                        versionedPackages = new ArrayList<>();
5021                    }
5022                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5023                }
5024            }
5025        }
5026
5027        return versionedPackages;
5028    }
5029
5030    @Override
5031    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5032        if (!sUserManager.exists(userId)) return null;
5033        final int callingUid = Binder.getCallingUid();
5034        flags = updateFlagsForComponent(flags, userId, component);
5035        enforceCrossUserPermission(callingUid, userId,
5036                false /* requireFullPermission */, false /* checkShell */, "get service info");
5037        synchronized (mPackages) {
5038            PackageParser.Service s = mServices.mServices.get(component);
5039            if (DEBUG_PACKAGE_INFO) Log.v(
5040                TAG, "getServiceInfo " + component + ": " + s);
5041            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5042                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5043                if (ps == null) return null;
5044                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5045                    return null;
5046                }
5047                return PackageParser.generateServiceInfo(
5048                        s, flags, ps.readUserState(userId), userId);
5049            }
5050        }
5051        return null;
5052    }
5053
5054    @Override
5055    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5056        if (!sUserManager.exists(userId)) return null;
5057        final int callingUid = Binder.getCallingUid();
5058        flags = updateFlagsForComponent(flags, userId, component);
5059        enforceCrossUserPermission(callingUid, userId,
5060                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5061        synchronized (mPackages) {
5062            PackageParser.Provider p = mProviders.mProviders.get(component);
5063            if (DEBUG_PACKAGE_INFO) Log.v(
5064                TAG, "getProviderInfo " + component + ": " + p);
5065            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5066                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5067                if (ps == null) return null;
5068                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5069                    return null;
5070                }
5071                return PackageParser.generateProviderInfo(
5072                        p, flags, ps.readUserState(userId), userId);
5073            }
5074        }
5075        return null;
5076    }
5077
5078    @Override
5079    public String[] getSystemSharedLibraryNames() {
5080        // allow instant applications
5081        synchronized (mPackages) {
5082            Set<String> libs = null;
5083            final int libCount = mSharedLibraries.size();
5084            for (int i = 0; i < libCount; i++) {
5085                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5086                if (versionedLib == null) {
5087                    continue;
5088                }
5089                final int versionCount = versionedLib.size();
5090                for (int j = 0; j < versionCount; j++) {
5091                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5092                    if (!libEntry.info.isStatic()) {
5093                        if (libs == null) {
5094                            libs = new ArraySet<>();
5095                        }
5096                        libs.add(libEntry.info.getName());
5097                        break;
5098                    }
5099                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5100                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5101                            UserHandle.getUserId(Binder.getCallingUid()),
5102                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5103                        if (libs == null) {
5104                            libs = new ArraySet<>();
5105                        }
5106                        libs.add(libEntry.info.getName());
5107                        break;
5108                    }
5109                }
5110            }
5111
5112            if (libs != null) {
5113                String[] libsArray = new String[libs.size()];
5114                libs.toArray(libsArray);
5115                return libsArray;
5116            }
5117
5118            return null;
5119        }
5120    }
5121
5122    @Override
5123    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5124        // allow instant applications
5125        synchronized (mPackages) {
5126            return mServicesSystemSharedLibraryPackageName;
5127        }
5128    }
5129
5130    @Override
5131    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5132        // allow instant applications
5133        synchronized (mPackages) {
5134            return mSharedSystemSharedLibraryPackageName;
5135        }
5136    }
5137
5138    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5139        for (int i = userList.length - 1; i >= 0; --i) {
5140            final int userId = userList[i];
5141            // don't add instant app to the list of updates
5142            if (pkgSetting.getInstantApp(userId)) {
5143                continue;
5144            }
5145            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5146            if (changedPackages == null) {
5147                changedPackages = new SparseArray<>();
5148                mChangedPackages.put(userId, changedPackages);
5149            }
5150            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5151            if (sequenceNumbers == null) {
5152                sequenceNumbers = new HashMap<>();
5153                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5154            }
5155            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5156            if (sequenceNumber != null) {
5157                changedPackages.remove(sequenceNumber);
5158            }
5159            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5160            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5161        }
5162        mChangedPackagesSequenceNumber++;
5163    }
5164
5165    @Override
5166    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5167        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5168            return null;
5169        }
5170        synchronized (mPackages) {
5171            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5172                return null;
5173            }
5174            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5175            if (changedPackages == null) {
5176                return null;
5177            }
5178            final List<String> packageNames =
5179                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5180            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5181                final String packageName = changedPackages.get(i);
5182                if (packageName != null) {
5183                    packageNames.add(packageName);
5184                }
5185            }
5186            return packageNames.isEmpty()
5187                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5188        }
5189    }
5190
5191    @Override
5192    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5193        // allow instant applications
5194        ArrayList<FeatureInfo> res;
5195        synchronized (mAvailableFeatures) {
5196            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5197            res.addAll(mAvailableFeatures.values());
5198        }
5199        final FeatureInfo fi = new FeatureInfo();
5200        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5201                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5202        res.add(fi);
5203
5204        return new ParceledListSlice<>(res);
5205    }
5206
5207    @Override
5208    public boolean hasSystemFeature(String name, int version) {
5209        // allow instant applications
5210        synchronized (mAvailableFeatures) {
5211            final FeatureInfo feat = mAvailableFeatures.get(name);
5212            if (feat == null) {
5213                return false;
5214            } else {
5215                return feat.version >= version;
5216            }
5217        }
5218    }
5219
5220    @Override
5221    public int checkPermission(String permName, String pkgName, int userId) {
5222        if (!sUserManager.exists(userId)) {
5223            return PackageManager.PERMISSION_DENIED;
5224        }
5225        final int callingUid = Binder.getCallingUid();
5226
5227        synchronized (mPackages) {
5228            final PackageParser.Package p = mPackages.get(pkgName);
5229            if (p != null && p.mExtras != null) {
5230                final PackageSetting ps = (PackageSetting) p.mExtras;
5231                if (filterAppAccessLPr(ps, callingUid, userId)) {
5232                    return PackageManager.PERMISSION_DENIED;
5233                }
5234                final boolean instantApp = ps.getInstantApp(userId);
5235                final PermissionsState permissionsState = ps.getPermissionsState();
5236                if (permissionsState.hasPermission(permName, userId)) {
5237                    if (instantApp) {
5238                        BasePermission bp = mSettings.mPermissions.get(permName);
5239                        if (bp != null && bp.isInstant()) {
5240                            return PackageManager.PERMISSION_GRANTED;
5241                        }
5242                    } else {
5243                        return PackageManager.PERMISSION_GRANTED;
5244                    }
5245                }
5246                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5247                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5248                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5249                    return PackageManager.PERMISSION_GRANTED;
5250                }
5251            }
5252        }
5253
5254        return PackageManager.PERMISSION_DENIED;
5255    }
5256
5257    @Override
5258    public int checkUidPermission(String permName, int uid) {
5259        final int callingUid = Binder.getCallingUid();
5260        final int callingUserId = UserHandle.getUserId(callingUid);
5261        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5262        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
5263        final int userId = UserHandle.getUserId(uid);
5264        if (!sUserManager.exists(userId)) {
5265            return PackageManager.PERMISSION_DENIED;
5266        }
5267
5268        synchronized (mPackages) {
5269            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5270            if (obj != null) {
5271                if (obj instanceof SharedUserSetting) {
5272                    if (isCallerInstantApp) {
5273                        return PackageManager.PERMISSION_DENIED;
5274                    }
5275                } else if (obj instanceof PackageSetting) {
5276                    final PackageSetting ps = (PackageSetting) obj;
5277                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5278                        return PackageManager.PERMISSION_DENIED;
5279                    }
5280                }
5281                final SettingBase settingBase = (SettingBase) obj;
5282                final PermissionsState permissionsState = settingBase.getPermissionsState();
5283                if (permissionsState.hasPermission(permName, userId)) {
5284                    if (isUidInstantApp) {
5285                        BasePermission bp = mSettings.mPermissions.get(permName);
5286                        if (bp != null && bp.isInstant()) {
5287                            return PackageManager.PERMISSION_GRANTED;
5288                        }
5289                    } else {
5290                        return PackageManager.PERMISSION_GRANTED;
5291                    }
5292                }
5293                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5294                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5295                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5296                    return PackageManager.PERMISSION_GRANTED;
5297                }
5298            } else {
5299                ArraySet<String> perms = mSystemPermissions.get(uid);
5300                if (perms != null) {
5301                    if (perms.contains(permName)) {
5302                        return PackageManager.PERMISSION_GRANTED;
5303                    }
5304                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5305                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5306                        return PackageManager.PERMISSION_GRANTED;
5307                    }
5308                }
5309            }
5310        }
5311
5312        return PackageManager.PERMISSION_DENIED;
5313    }
5314
5315    @Override
5316    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5317        if (UserHandle.getCallingUserId() != userId) {
5318            mContext.enforceCallingPermission(
5319                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5320                    "isPermissionRevokedByPolicy for user " + userId);
5321        }
5322
5323        if (checkPermission(permission, packageName, userId)
5324                == PackageManager.PERMISSION_GRANTED) {
5325            return false;
5326        }
5327
5328        final int callingUid = Binder.getCallingUid();
5329        if (getInstantAppPackageName(callingUid) != null) {
5330            if (!isCallerSameApp(packageName, callingUid)) {
5331                return false;
5332            }
5333        } else {
5334            if (isInstantApp(packageName, userId)) {
5335                return false;
5336            }
5337        }
5338
5339        final long identity = Binder.clearCallingIdentity();
5340        try {
5341            final int flags = getPermissionFlags(permission, packageName, userId);
5342            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5343        } finally {
5344            Binder.restoreCallingIdentity(identity);
5345        }
5346    }
5347
5348    @Override
5349    public String getPermissionControllerPackageName() {
5350        synchronized (mPackages) {
5351            return mRequiredInstallerPackage;
5352        }
5353    }
5354
5355    /**
5356     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
5357     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
5358     * @param checkShell whether to prevent shell from access if there's a debugging restriction
5359     * @param message the message to log on security exception
5360     */
5361    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
5362            boolean checkShell, String message) {
5363        if (userId < 0) {
5364            throw new IllegalArgumentException("Invalid userId " + userId);
5365        }
5366        if (checkShell) {
5367            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
5368        }
5369        if (userId == UserHandle.getUserId(callingUid)) return;
5370        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5371            if (requireFullPermission) {
5372                mContext.enforceCallingOrSelfPermission(
5373                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5374            } else {
5375                try {
5376                    mContext.enforceCallingOrSelfPermission(
5377                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5378                } catch (SecurityException se) {
5379                    mContext.enforceCallingOrSelfPermission(
5380                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5381                }
5382            }
5383        }
5384    }
5385
5386    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5387        if (callingUid == Process.SHELL_UID) {
5388            if (userHandle >= 0
5389                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
5390                throw new SecurityException("Shell does not have permission to access user "
5391                        + userHandle);
5392            } else if (userHandle < 0) {
5393                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5394                        + Debug.getCallers(3));
5395            }
5396        }
5397    }
5398
5399    private BasePermission findPermissionTreeLP(String permName) {
5400        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
5401            if (permName.startsWith(bp.name) &&
5402                    permName.length() > bp.name.length() &&
5403                    permName.charAt(bp.name.length()) == '.') {
5404                return bp;
5405            }
5406        }
5407        return null;
5408    }
5409
5410    private BasePermission checkPermissionTreeLP(String permName) {
5411        if (permName != null) {
5412            BasePermission bp = findPermissionTreeLP(permName);
5413            if (bp != null) {
5414                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
5415                    return bp;
5416                }
5417                throw new SecurityException("Calling uid "
5418                        + Binder.getCallingUid()
5419                        + " is not allowed to add to permission tree "
5420                        + bp.name + " owned by uid " + bp.uid);
5421            }
5422        }
5423        throw new SecurityException("No permission tree found for " + permName);
5424    }
5425
5426    static boolean compareStrings(CharSequence s1, CharSequence s2) {
5427        if (s1 == null) {
5428            return s2 == null;
5429        }
5430        if (s2 == null) {
5431            return false;
5432        }
5433        if (s1.getClass() != s2.getClass()) {
5434            return false;
5435        }
5436        return s1.equals(s2);
5437    }
5438
5439    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5440        if (pi1.icon != pi2.icon) return false;
5441        if (pi1.logo != pi2.logo) return false;
5442        if (pi1.protectionLevel != pi2.protectionLevel) return false;
5443        if (!compareStrings(pi1.name, pi2.name)) return false;
5444        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5445        // We'll take care of setting this one.
5446        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5447        // These are not currently stored in settings.
5448        //if (!compareStrings(pi1.group, pi2.group)) return false;
5449        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5450        //if (pi1.labelRes != pi2.labelRes) return false;
5451        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5452        return true;
5453    }
5454
5455    int permissionInfoFootprint(PermissionInfo info) {
5456        int size = info.name.length();
5457        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5458        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5459        return size;
5460    }
5461
5462    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5463        int size = 0;
5464        for (BasePermission perm : mSettings.mPermissions.values()) {
5465            if (perm.uid == tree.uid) {
5466                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5467            }
5468        }
5469        return size;
5470    }
5471
5472    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5473        // We calculate the max size of permissions defined by this uid and throw
5474        // if that plus the size of 'info' would exceed our stated maximum.
5475        if (tree.uid != Process.SYSTEM_UID) {
5476            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5477            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5478                throw new SecurityException("Permission tree size cap exceeded");
5479            }
5480        }
5481    }
5482
5483    boolean addPermissionLocked(PermissionInfo info, boolean async) {
5484        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5485            throw new SecurityException("Instant apps can't add permissions");
5486        }
5487        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5488            throw new SecurityException("Label must be specified in permission");
5489        }
5490        BasePermission tree = checkPermissionTreeLP(info.name);
5491        BasePermission bp = mSettings.mPermissions.get(info.name);
5492        boolean added = bp == null;
5493        boolean changed = true;
5494        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5495        if (added) {
5496            enforcePermissionCapLocked(info, tree);
5497            bp = new BasePermission(info.name, tree.sourcePackage,
5498                    BasePermission.TYPE_DYNAMIC);
5499        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5500            throw new SecurityException(
5501                    "Not allowed to modify non-dynamic permission "
5502                    + info.name);
5503        } else {
5504            if (bp.protectionLevel == fixedLevel
5505                    && bp.perm.owner.equals(tree.perm.owner)
5506                    && bp.uid == tree.uid
5507                    && comparePermissionInfos(bp.perm.info, info)) {
5508                changed = false;
5509            }
5510        }
5511        bp.protectionLevel = fixedLevel;
5512        info = new PermissionInfo(info);
5513        info.protectionLevel = fixedLevel;
5514        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5515        bp.perm.info.packageName = tree.perm.info.packageName;
5516        bp.uid = tree.uid;
5517        if (added) {
5518            mSettings.mPermissions.put(info.name, bp);
5519        }
5520        if (changed) {
5521            if (!async) {
5522                mSettings.writeLPr();
5523            } else {
5524                scheduleWriteSettingsLocked();
5525            }
5526        }
5527        return added;
5528    }
5529
5530    @Override
5531    public boolean addPermission(PermissionInfo info) {
5532        synchronized (mPackages) {
5533            return addPermissionLocked(info, false);
5534        }
5535    }
5536
5537    @Override
5538    public boolean addPermissionAsync(PermissionInfo info) {
5539        synchronized (mPackages) {
5540            return addPermissionLocked(info, true);
5541        }
5542    }
5543
5544    @Override
5545    public void removePermission(String name) {
5546        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5547            throw new SecurityException("Instant applications don't have access to this method");
5548        }
5549        synchronized (mPackages) {
5550            checkPermissionTreeLP(name);
5551            BasePermission bp = mSettings.mPermissions.get(name);
5552            if (bp != null) {
5553                if (bp.type != BasePermission.TYPE_DYNAMIC) {
5554                    throw new SecurityException(
5555                            "Not allowed to modify non-dynamic permission "
5556                            + name);
5557                }
5558                mSettings.mPermissions.remove(name);
5559                mSettings.writeLPr();
5560            }
5561        }
5562    }
5563
5564    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5565            PackageParser.Package pkg, BasePermission bp) {
5566        int index = pkg.requestedPermissions.indexOf(bp.name);
5567        if (index == -1) {
5568            throw new SecurityException("Package " + pkg.packageName
5569                    + " has not requested permission " + bp.name);
5570        }
5571        if (!bp.isRuntime() && !bp.isDevelopment()) {
5572            throw new SecurityException("Permission " + bp.name
5573                    + " is not a changeable permission type");
5574        }
5575    }
5576
5577    @Override
5578    public void grantRuntimePermission(String packageName, String name, final int userId) {
5579        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5580    }
5581
5582    private void grantRuntimePermission(String packageName, String name, final int userId,
5583            boolean overridePolicy) {
5584        if (!sUserManager.exists(userId)) {
5585            Log.e(TAG, "No such user:" + userId);
5586            return;
5587        }
5588        final int callingUid = Binder.getCallingUid();
5589
5590        mContext.enforceCallingOrSelfPermission(
5591                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5592                "grantRuntimePermission");
5593
5594        enforceCrossUserPermission(callingUid, userId,
5595                true /* requireFullPermission */, true /* checkShell */,
5596                "grantRuntimePermission");
5597
5598        final int uid;
5599        final PackageSetting ps;
5600
5601        synchronized (mPackages) {
5602            final PackageParser.Package pkg = mPackages.get(packageName);
5603            if (pkg == null) {
5604                throw new IllegalArgumentException("Unknown package: " + packageName);
5605            }
5606            final BasePermission bp = mSettings.mPermissions.get(name);
5607            if (bp == null) {
5608                throw new IllegalArgumentException("Unknown permission: " + name);
5609            }
5610            ps = (PackageSetting) pkg.mExtras;
5611            if (ps == null
5612                    || filterAppAccessLPr(ps, callingUid, userId)) {
5613                throw new IllegalArgumentException("Unknown package: " + packageName);
5614            }
5615
5616            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5617
5618            // If a permission review is required for legacy apps we represent
5619            // their permissions as always granted runtime ones since we need
5620            // to keep the review required permission flag per user while an
5621            // install permission's state is shared across all users.
5622            if (mPermissionReviewRequired
5623                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5624                    && bp.isRuntime()) {
5625                return;
5626            }
5627
5628            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5629
5630            final PermissionsState permissionsState = ps.getPermissionsState();
5631
5632            final int flags = permissionsState.getPermissionFlags(name, userId);
5633            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5634                throw new SecurityException("Cannot grant system fixed permission "
5635                        + name + " for package " + packageName);
5636            }
5637            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5638                throw new SecurityException("Cannot grant policy fixed permission "
5639                        + name + " for package " + packageName);
5640            }
5641
5642            if (bp.isDevelopment()) {
5643                // Development permissions must be handled specially, since they are not
5644                // normal runtime permissions.  For now they apply to all users.
5645                if (permissionsState.grantInstallPermission(bp) !=
5646                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5647                    scheduleWriteSettingsLocked();
5648                }
5649                return;
5650            }
5651
5652            if (ps.getInstantApp(userId) && !bp.isInstant()) {
5653                throw new SecurityException("Cannot grant non-ephemeral permission"
5654                        + name + " for package " + packageName);
5655            }
5656
5657            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5658                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5659                return;
5660            }
5661
5662            final int result = permissionsState.grantRuntimePermission(bp, userId);
5663            switch (result) {
5664                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5665                    return;
5666                }
5667
5668                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5669                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5670                    mHandler.post(new Runnable() {
5671                        @Override
5672                        public void run() {
5673                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5674                        }
5675                    });
5676                }
5677                break;
5678            }
5679
5680            if (bp.isRuntime()) {
5681                logPermissionGranted(mContext, name, packageName);
5682            }
5683
5684            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5685
5686            // Not critical if that is lost - app has to request again.
5687            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5688        }
5689
5690        // Only need to do this if user is initialized. Otherwise it's a new user
5691        // and there are no processes running as the user yet and there's no need
5692        // to make an expensive call to remount processes for the changed permissions.
5693        if (READ_EXTERNAL_STORAGE.equals(name)
5694                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5695            final long token = Binder.clearCallingIdentity();
5696            try {
5697                if (sUserManager.isInitialized(userId)) {
5698                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5699                            StorageManagerInternal.class);
5700                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5701                }
5702            } finally {
5703                Binder.restoreCallingIdentity(token);
5704            }
5705        }
5706    }
5707
5708    @Override
5709    public void revokeRuntimePermission(String packageName, String name, int userId) {
5710        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5711    }
5712
5713    private void revokeRuntimePermission(String packageName, String name, int userId,
5714            boolean overridePolicy) {
5715        if (!sUserManager.exists(userId)) {
5716            Log.e(TAG, "No such user:" + userId);
5717            return;
5718        }
5719
5720        mContext.enforceCallingOrSelfPermission(
5721                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5722                "revokeRuntimePermission");
5723
5724        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5725                true /* requireFullPermission */, true /* checkShell */,
5726                "revokeRuntimePermission");
5727
5728        final int appId;
5729
5730        synchronized (mPackages) {
5731            final PackageParser.Package pkg = mPackages.get(packageName);
5732            if (pkg == null) {
5733                throw new IllegalArgumentException("Unknown package: " + packageName);
5734            }
5735            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5736            if (ps == null
5737                    || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
5738                throw new IllegalArgumentException("Unknown package: " + packageName);
5739            }
5740            final BasePermission bp = mSettings.mPermissions.get(name);
5741            if (bp == null) {
5742                throw new IllegalArgumentException("Unknown permission: " + name);
5743            }
5744
5745            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5746
5747            // If a permission review is required for legacy apps we represent
5748            // their permissions as always granted runtime ones since we need
5749            // to keep the review required permission flag per user while an
5750            // install permission's state is shared across all users.
5751            if (mPermissionReviewRequired
5752                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5753                    && bp.isRuntime()) {
5754                return;
5755            }
5756
5757            final PermissionsState permissionsState = ps.getPermissionsState();
5758
5759            final int flags = permissionsState.getPermissionFlags(name, userId);
5760            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5761                throw new SecurityException("Cannot revoke system fixed permission "
5762                        + name + " for package " + packageName);
5763            }
5764            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5765                throw new SecurityException("Cannot revoke policy fixed permission "
5766                        + name + " for package " + packageName);
5767            }
5768
5769            if (bp.isDevelopment()) {
5770                // Development permissions must be handled specially, since they are not
5771                // normal runtime permissions.  For now they apply to all users.
5772                if (permissionsState.revokeInstallPermission(bp) !=
5773                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5774                    scheduleWriteSettingsLocked();
5775                }
5776                return;
5777            }
5778
5779            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5780                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5781                return;
5782            }
5783
5784            if (bp.isRuntime()) {
5785                logPermissionRevoked(mContext, name, packageName);
5786            }
5787
5788            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5789
5790            // Critical, after this call app should never have the permission.
5791            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5792
5793            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5794        }
5795
5796        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5797    }
5798
5799    /**
5800     * Get the first event id for the permission.
5801     *
5802     * <p>There are four events for each permission: <ul>
5803     *     <li>Request permission: first id + 0</li>
5804     *     <li>Grant permission: first id + 1</li>
5805     *     <li>Request for permission denied: first id + 2</li>
5806     *     <li>Revoke permission: first id + 3</li>
5807     * </ul></p>
5808     *
5809     * @param name name of the permission
5810     *
5811     * @return The first event id for the permission
5812     */
5813    private static int getBaseEventId(@NonNull String name) {
5814        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5815
5816        if (eventIdIndex == -1) {
5817            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5818                    || Build.IS_USER) {
5819                Log.i(TAG, "Unknown permission " + name);
5820
5821                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5822            } else {
5823                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5824                //
5825                // Also update
5826                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5827                // - metrics_constants.proto
5828                throw new IllegalStateException("Unknown permission " + name);
5829            }
5830        }
5831
5832        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5833    }
5834
5835    /**
5836     * Log that a permission was revoked.
5837     *
5838     * @param context Context of the caller
5839     * @param name name of the permission
5840     * @param packageName package permission if for
5841     */
5842    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5843            @NonNull String packageName) {
5844        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5845    }
5846
5847    /**
5848     * Log that a permission request was granted.
5849     *
5850     * @param context Context of the caller
5851     * @param name name of the permission
5852     * @param packageName package permission if for
5853     */
5854    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5855            @NonNull String packageName) {
5856        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5857    }
5858
5859    @Override
5860    public void resetRuntimePermissions() {
5861        mContext.enforceCallingOrSelfPermission(
5862                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5863                "revokeRuntimePermission");
5864
5865        int callingUid = Binder.getCallingUid();
5866        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5867            mContext.enforceCallingOrSelfPermission(
5868                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5869                    "resetRuntimePermissions");
5870        }
5871
5872        synchronized (mPackages) {
5873            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5874            for (int userId : UserManagerService.getInstance().getUserIds()) {
5875                final int packageCount = mPackages.size();
5876                for (int i = 0; i < packageCount; i++) {
5877                    PackageParser.Package pkg = mPackages.valueAt(i);
5878                    if (!(pkg.mExtras instanceof PackageSetting)) {
5879                        continue;
5880                    }
5881                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5882                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5883                }
5884            }
5885        }
5886    }
5887
5888    @Override
5889    public int getPermissionFlags(String name, String packageName, int userId) {
5890        if (!sUserManager.exists(userId)) {
5891            return 0;
5892        }
5893
5894        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5895
5896        final int callingUid = Binder.getCallingUid();
5897        enforceCrossUserPermission(callingUid, userId,
5898                true /* requireFullPermission */, false /* checkShell */,
5899                "getPermissionFlags");
5900
5901        synchronized (mPackages) {
5902            final PackageParser.Package pkg = mPackages.get(packageName);
5903            if (pkg == null) {
5904                return 0;
5905            }
5906            final BasePermission bp = mSettings.mPermissions.get(name);
5907            if (bp == null) {
5908                return 0;
5909            }
5910            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5911            if (ps == null
5912                    || filterAppAccessLPr(ps, callingUid, userId)) {
5913                return 0;
5914            }
5915            PermissionsState permissionsState = ps.getPermissionsState();
5916            return permissionsState.getPermissionFlags(name, userId);
5917        }
5918    }
5919
5920    @Override
5921    public void updatePermissionFlags(String name, String packageName, int flagMask,
5922            int flagValues, int userId) {
5923        if (!sUserManager.exists(userId)) {
5924            return;
5925        }
5926
5927        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5928
5929        final int callingUid = Binder.getCallingUid();
5930        enforceCrossUserPermission(callingUid, userId,
5931                true /* requireFullPermission */, true /* checkShell */,
5932                "updatePermissionFlags");
5933
5934        // Only the system can change these flags and nothing else.
5935        if (getCallingUid() != Process.SYSTEM_UID) {
5936            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5937            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5938            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5939            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5940            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5941        }
5942
5943        synchronized (mPackages) {
5944            final PackageParser.Package pkg = mPackages.get(packageName);
5945            if (pkg == null) {
5946                throw new IllegalArgumentException("Unknown package: " + packageName);
5947            }
5948            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5949            if (ps == null
5950                    || filterAppAccessLPr(ps, callingUid, userId)) {
5951                throw new IllegalArgumentException("Unknown package: " + packageName);
5952            }
5953
5954            final BasePermission bp = mSettings.mPermissions.get(name);
5955            if (bp == null) {
5956                throw new IllegalArgumentException("Unknown permission: " + name);
5957            }
5958
5959            PermissionsState permissionsState = ps.getPermissionsState();
5960
5961            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5962
5963            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5964                // Install and runtime permissions are stored in different places,
5965                // so figure out what permission changed and persist the change.
5966                if (permissionsState.getInstallPermissionState(name) != null) {
5967                    scheduleWriteSettingsLocked();
5968                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5969                        || hadState) {
5970                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5971                }
5972            }
5973        }
5974    }
5975
5976    /**
5977     * Update the permission flags for all packages and runtime permissions of a user in order
5978     * to allow device or profile owner to remove POLICY_FIXED.
5979     */
5980    @Override
5981    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5982        if (!sUserManager.exists(userId)) {
5983            return;
5984        }
5985
5986        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5987
5988        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5989                true /* requireFullPermission */, true /* checkShell */,
5990                "updatePermissionFlagsForAllApps");
5991
5992        // Only the system can change system fixed flags.
5993        if (getCallingUid() != Process.SYSTEM_UID) {
5994            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5995            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5996        }
5997
5998        synchronized (mPackages) {
5999            boolean changed = false;
6000            final int packageCount = mPackages.size();
6001            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
6002                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
6003                final PackageSetting ps = (PackageSetting) pkg.mExtras;
6004                if (ps == null) {
6005                    continue;
6006                }
6007                PermissionsState permissionsState = ps.getPermissionsState();
6008                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
6009                        userId, flagMask, flagValues);
6010            }
6011            if (changed) {
6012                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
6013            }
6014        }
6015    }
6016
6017    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
6018        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
6019                != PackageManager.PERMISSION_GRANTED
6020            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
6021                != PackageManager.PERMISSION_GRANTED) {
6022            throw new SecurityException(message + " requires "
6023                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
6024                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
6025        }
6026    }
6027
6028    @Override
6029    public boolean shouldShowRequestPermissionRationale(String permissionName,
6030            String packageName, int userId) {
6031        if (UserHandle.getCallingUserId() != userId) {
6032            mContext.enforceCallingPermission(
6033                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
6034                    "canShowRequestPermissionRationale for user " + userId);
6035        }
6036
6037        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
6038        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
6039            return false;
6040        }
6041
6042        if (checkPermission(permissionName, packageName, userId)
6043                == PackageManager.PERMISSION_GRANTED) {
6044            return false;
6045        }
6046
6047        final int flags;
6048
6049        final long identity = Binder.clearCallingIdentity();
6050        try {
6051            flags = getPermissionFlags(permissionName,
6052                    packageName, userId);
6053        } finally {
6054            Binder.restoreCallingIdentity(identity);
6055        }
6056
6057        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
6058                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
6059                | PackageManager.FLAG_PERMISSION_USER_FIXED;
6060
6061        if ((flags & fixedFlags) != 0) {
6062            return false;
6063        }
6064
6065        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
6066    }
6067
6068    @Override
6069    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6070        mContext.enforceCallingOrSelfPermission(
6071                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
6072                "addOnPermissionsChangeListener");
6073
6074        synchronized (mPackages) {
6075            mOnPermissionChangeListeners.addListenerLocked(listener);
6076        }
6077    }
6078
6079    @Override
6080    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6081        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6082            throw new SecurityException("Instant applications don't have access to this method");
6083        }
6084        synchronized (mPackages) {
6085            mOnPermissionChangeListeners.removeListenerLocked(listener);
6086        }
6087    }
6088
6089    @Override
6090    public boolean isProtectedBroadcast(String actionName) {
6091        // allow instant applications
6092        synchronized (mProtectedBroadcasts) {
6093            if (mProtectedBroadcasts.contains(actionName)) {
6094                return true;
6095            } else if (actionName != null) {
6096                // TODO: remove these terrible hacks
6097                if (actionName.startsWith("android.net.netmon.lingerExpired")
6098                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
6099                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
6100                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
6101                    return true;
6102                }
6103            }
6104        }
6105        return false;
6106    }
6107
6108    @Override
6109    public int checkSignatures(String pkg1, String pkg2) {
6110        synchronized (mPackages) {
6111            final PackageParser.Package p1 = mPackages.get(pkg1);
6112            final PackageParser.Package p2 = mPackages.get(pkg2);
6113            if (p1 == null || p1.mExtras == null
6114                    || p2 == null || p2.mExtras == null) {
6115                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6116            }
6117            final int callingUid = Binder.getCallingUid();
6118            final int callingUserId = UserHandle.getUserId(callingUid);
6119            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
6120            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
6121            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
6122                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
6123                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6124            }
6125            return compareSignatures(p1.mSignatures, p2.mSignatures);
6126        }
6127    }
6128
6129    @Override
6130    public int checkUidSignatures(int uid1, int uid2) {
6131        final int callingUid = Binder.getCallingUid();
6132        final int callingUserId = UserHandle.getUserId(callingUid);
6133        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6134        // Map to base uids.
6135        uid1 = UserHandle.getAppId(uid1);
6136        uid2 = UserHandle.getAppId(uid2);
6137        // reader
6138        synchronized (mPackages) {
6139            Signature[] s1;
6140            Signature[] s2;
6141            Object obj = mSettings.getUserIdLPr(uid1);
6142            if (obj != null) {
6143                if (obj instanceof SharedUserSetting) {
6144                    if (isCallerInstantApp) {
6145                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6146                    }
6147                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
6148                } else if (obj instanceof PackageSetting) {
6149                    final PackageSetting ps = (PackageSetting) obj;
6150                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6151                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6152                    }
6153                    s1 = ps.signatures.mSignatures;
6154                } else {
6155                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6156                }
6157            } else {
6158                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6159            }
6160            obj = mSettings.getUserIdLPr(uid2);
6161            if (obj != null) {
6162                if (obj instanceof SharedUserSetting) {
6163                    if (isCallerInstantApp) {
6164                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6165                    }
6166                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
6167                } else if (obj instanceof PackageSetting) {
6168                    final PackageSetting ps = (PackageSetting) obj;
6169                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6170                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6171                    }
6172                    s2 = ps.signatures.mSignatures;
6173                } else {
6174                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6175                }
6176            } else {
6177                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6178            }
6179            return compareSignatures(s1, s2);
6180        }
6181    }
6182
6183    /**
6184     * This method should typically only be used when granting or revoking
6185     * permissions, since the app may immediately restart after this call.
6186     * <p>
6187     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
6188     * guard your work against the app being relaunched.
6189     */
6190    private void killUid(int appId, int userId, String reason) {
6191        final long identity = Binder.clearCallingIdentity();
6192        try {
6193            IActivityManager am = ActivityManager.getService();
6194            if (am != null) {
6195                try {
6196                    am.killUid(appId, userId, reason);
6197                } catch (RemoteException e) {
6198                    /* ignore - same process */
6199                }
6200            }
6201        } finally {
6202            Binder.restoreCallingIdentity(identity);
6203        }
6204    }
6205
6206    /**
6207     * Compares two sets of signatures. Returns:
6208     * <br />
6209     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
6210     * <br />
6211     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
6212     * <br />
6213     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
6214     * <br />
6215     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
6216     * <br />
6217     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
6218     */
6219    static int compareSignatures(Signature[] s1, Signature[] s2) {
6220        if (s1 == null) {
6221            return s2 == null
6222                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
6223                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
6224        }
6225
6226        if (s2 == null) {
6227            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
6228        }
6229
6230        if (s1.length != s2.length) {
6231            return PackageManager.SIGNATURE_NO_MATCH;
6232        }
6233
6234        // Since both signature sets are of size 1, we can compare without HashSets.
6235        if (s1.length == 1) {
6236            return s1[0].equals(s2[0]) ?
6237                    PackageManager.SIGNATURE_MATCH :
6238                    PackageManager.SIGNATURE_NO_MATCH;
6239        }
6240
6241        ArraySet<Signature> set1 = new ArraySet<Signature>();
6242        for (Signature sig : s1) {
6243            set1.add(sig);
6244        }
6245        ArraySet<Signature> set2 = new ArraySet<Signature>();
6246        for (Signature sig : s2) {
6247            set2.add(sig);
6248        }
6249        // Make sure s2 contains all signatures in s1.
6250        if (set1.equals(set2)) {
6251            return PackageManager.SIGNATURE_MATCH;
6252        }
6253        return PackageManager.SIGNATURE_NO_MATCH;
6254    }
6255
6256    /**
6257     * If the database version for this type of package (internal storage or
6258     * external storage) is less than the version where package signatures
6259     * were updated, return true.
6260     */
6261    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6262        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6263        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
6264    }
6265
6266    /**
6267     * Used for backward compatibility to make sure any packages with
6268     * certificate chains get upgraded to the new style. {@code existingSigs}
6269     * will be in the old format (since they were stored on disk from before the
6270     * system upgrade) and {@code scannedSigs} will be in the newer format.
6271     */
6272    private int compareSignaturesCompat(PackageSignatures existingSigs,
6273            PackageParser.Package scannedPkg) {
6274        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
6275            return PackageManager.SIGNATURE_NO_MATCH;
6276        }
6277
6278        ArraySet<Signature> existingSet = new ArraySet<Signature>();
6279        for (Signature sig : existingSigs.mSignatures) {
6280            existingSet.add(sig);
6281        }
6282        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
6283        for (Signature sig : scannedPkg.mSignatures) {
6284            try {
6285                Signature[] chainSignatures = sig.getChainSignatures();
6286                for (Signature chainSig : chainSignatures) {
6287                    scannedCompatSet.add(chainSig);
6288                }
6289            } catch (CertificateEncodingException e) {
6290                scannedCompatSet.add(sig);
6291            }
6292        }
6293        /*
6294         * Make sure the expanded scanned set contains all signatures in the
6295         * existing one.
6296         */
6297        if (scannedCompatSet.equals(existingSet)) {
6298            // Migrate the old signatures to the new scheme.
6299            existingSigs.assignSignatures(scannedPkg.mSignatures);
6300            // The new KeySets will be re-added later in the scanning process.
6301            synchronized (mPackages) {
6302                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
6303            }
6304            return PackageManager.SIGNATURE_MATCH;
6305        }
6306        return PackageManager.SIGNATURE_NO_MATCH;
6307    }
6308
6309    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6310        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6311        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6312    }
6313
6314    private int compareSignaturesRecover(PackageSignatures existingSigs,
6315            PackageParser.Package scannedPkg) {
6316        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
6317            return PackageManager.SIGNATURE_NO_MATCH;
6318        }
6319
6320        String msg = null;
6321        try {
6322            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
6323                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
6324                        + scannedPkg.packageName);
6325                return PackageManager.SIGNATURE_MATCH;
6326            }
6327        } catch (CertificateException e) {
6328            msg = e.getMessage();
6329        }
6330
6331        logCriticalInfo(Log.INFO,
6332                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
6333        return PackageManager.SIGNATURE_NO_MATCH;
6334    }
6335
6336    @Override
6337    public List<String> getAllPackages() {
6338        final int callingUid = Binder.getCallingUid();
6339        final int callingUserId = UserHandle.getUserId(callingUid);
6340        synchronized (mPackages) {
6341            if (canViewInstantApps(callingUid, callingUserId)) {
6342                return new ArrayList<String>(mPackages.keySet());
6343            }
6344            final String instantAppPkgName = getInstantAppPackageName(callingUid);
6345            final List<String> result = new ArrayList<>();
6346            if (instantAppPkgName != null) {
6347                // caller is an instant application; filter unexposed applications
6348                for (PackageParser.Package pkg : mPackages.values()) {
6349                    if (!pkg.visibleToInstantApps) {
6350                        continue;
6351                    }
6352                    result.add(pkg.packageName);
6353                }
6354            } else {
6355                // caller is a normal application; filter instant applications
6356                for (PackageParser.Package pkg : mPackages.values()) {
6357                    final PackageSetting ps =
6358                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6359                    if (ps != null
6360                            && ps.getInstantApp(callingUserId)
6361                            && !mInstantAppRegistry.isInstantAccessGranted(
6362                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6363                        continue;
6364                    }
6365                    result.add(pkg.packageName);
6366                }
6367            }
6368            return result;
6369        }
6370    }
6371
6372    @Override
6373    public String[] getPackagesForUid(int uid) {
6374        final int callingUid = Binder.getCallingUid();
6375        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6376        final int userId = UserHandle.getUserId(uid);
6377        uid = UserHandle.getAppId(uid);
6378        // reader
6379        synchronized (mPackages) {
6380            Object obj = mSettings.getUserIdLPr(uid);
6381            if (obj instanceof SharedUserSetting) {
6382                if (isCallerInstantApp) {
6383                    return null;
6384                }
6385                final SharedUserSetting sus = (SharedUserSetting) obj;
6386                final int N = sus.packages.size();
6387                String[] res = new String[N];
6388                final Iterator<PackageSetting> it = sus.packages.iterator();
6389                int i = 0;
6390                while (it.hasNext()) {
6391                    PackageSetting ps = it.next();
6392                    if (ps.getInstalled(userId)) {
6393                        res[i++] = ps.name;
6394                    } else {
6395                        res = ArrayUtils.removeElement(String.class, res, res[i]);
6396                    }
6397                }
6398                return res;
6399            } else if (obj instanceof PackageSetting) {
6400                final PackageSetting ps = (PackageSetting) obj;
6401                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6402                    return new String[]{ps.name};
6403                }
6404            }
6405        }
6406        return null;
6407    }
6408
6409    @Override
6410    public String getNameForUid(int uid) {
6411        final int callingUid = Binder.getCallingUid();
6412        if (getInstantAppPackageName(callingUid) != null) {
6413            return null;
6414        }
6415        synchronized (mPackages) {
6416            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6417            if (obj instanceof SharedUserSetting) {
6418                final SharedUserSetting sus = (SharedUserSetting) obj;
6419                return sus.name + ":" + sus.userId;
6420            } else if (obj instanceof PackageSetting) {
6421                final PackageSetting ps = (PackageSetting) obj;
6422                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6423                    return null;
6424                }
6425                return ps.name;
6426            }
6427            return null;
6428        }
6429    }
6430
6431    @Override
6432    public String[] getNamesForUids(int[] uids) {
6433        if (uids == null || uids.length == 0) {
6434            return null;
6435        }
6436        final int callingUid = Binder.getCallingUid();
6437        if (getInstantAppPackageName(callingUid) != null) {
6438            return null;
6439        }
6440        final String[] names = new String[uids.length];
6441        synchronized (mPackages) {
6442            for (int i = uids.length - 1; i >= 0; i--) {
6443                final int uid = uids[i];
6444                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6445                if (obj instanceof SharedUserSetting) {
6446                    final SharedUserSetting sus = (SharedUserSetting) obj;
6447                    names[i] = "shared:" + sus.name;
6448                } else if (obj instanceof PackageSetting) {
6449                    final PackageSetting ps = (PackageSetting) obj;
6450                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6451                        names[i] = null;
6452                    } else {
6453                        names[i] = ps.name;
6454                    }
6455                } else {
6456                    names[i] = null;
6457                }
6458            }
6459        }
6460        return names;
6461    }
6462
6463    @Override
6464    public int getUidForSharedUser(String sharedUserName) {
6465        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6466            return -1;
6467        }
6468        if (sharedUserName == null) {
6469            return -1;
6470        }
6471        // reader
6472        synchronized (mPackages) {
6473            SharedUserSetting suid;
6474            try {
6475                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6476                if (suid != null) {
6477                    return suid.userId;
6478                }
6479            } catch (PackageManagerException ignore) {
6480                // can't happen, but, still need to catch it
6481            }
6482            return -1;
6483        }
6484    }
6485
6486    @Override
6487    public int getFlagsForUid(int uid) {
6488        final int callingUid = Binder.getCallingUid();
6489        if (getInstantAppPackageName(callingUid) != null) {
6490            return 0;
6491        }
6492        synchronized (mPackages) {
6493            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6494            if (obj instanceof SharedUserSetting) {
6495                final SharedUserSetting sus = (SharedUserSetting) obj;
6496                return sus.pkgFlags;
6497            } else if (obj instanceof PackageSetting) {
6498                final PackageSetting ps = (PackageSetting) obj;
6499                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6500                    return 0;
6501                }
6502                return ps.pkgFlags;
6503            }
6504        }
6505        return 0;
6506    }
6507
6508    @Override
6509    public int getPrivateFlagsForUid(int uid) {
6510        final int callingUid = Binder.getCallingUid();
6511        if (getInstantAppPackageName(callingUid) != null) {
6512            return 0;
6513        }
6514        synchronized (mPackages) {
6515            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6516            if (obj instanceof SharedUserSetting) {
6517                final SharedUserSetting sus = (SharedUserSetting) obj;
6518                return sus.pkgPrivateFlags;
6519            } else if (obj instanceof PackageSetting) {
6520                final PackageSetting ps = (PackageSetting) obj;
6521                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6522                    return 0;
6523                }
6524                return ps.pkgPrivateFlags;
6525            }
6526        }
6527        return 0;
6528    }
6529
6530    @Override
6531    public boolean isUidPrivileged(int uid) {
6532        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6533            return false;
6534        }
6535        uid = UserHandle.getAppId(uid);
6536        // reader
6537        synchronized (mPackages) {
6538            Object obj = mSettings.getUserIdLPr(uid);
6539            if (obj instanceof SharedUserSetting) {
6540                final SharedUserSetting sus = (SharedUserSetting) obj;
6541                final Iterator<PackageSetting> it = sus.packages.iterator();
6542                while (it.hasNext()) {
6543                    if (it.next().isPrivileged()) {
6544                        return true;
6545                    }
6546                }
6547            } else if (obj instanceof PackageSetting) {
6548                final PackageSetting ps = (PackageSetting) obj;
6549                return ps.isPrivileged();
6550            }
6551        }
6552        return false;
6553    }
6554
6555    @Override
6556    public String[] getAppOpPermissionPackages(String permissionName) {
6557        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6558            return null;
6559        }
6560        synchronized (mPackages) {
6561            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6562            if (pkgs == null) {
6563                return null;
6564            }
6565            return pkgs.toArray(new String[pkgs.size()]);
6566        }
6567    }
6568
6569    @Override
6570    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6571            int flags, int userId) {
6572        return resolveIntentInternal(
6573                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6574    }
6575
6576    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6577            int flags, int userId, boolean resolveForStart) {
6578        try {
6579            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6580
6581            if (!sUserManager.exists(userId)) return null;
6582            final int callingUid = Binder.getCallingUid();
6583            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6584            enforceCrossUserPermission(callingUid, userId,
6585                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6586
6587            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6588            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6589                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
6590            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6591
6592            final ResolveInfo bestChoice =
6593                    chooseBestActivity(intent, resolvedType, flags, query, userId);
6594            return bestChoice;
6595        } finally {
6596            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6597        }
6598    }
6599
6600    @Override
6601    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6602        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6603            throw new SecurityException(
6604                    "findPersistentPreferredActivity can only be run by the system");
6605        }
6606        if (!sUserManager.exists(userId)) {
6607            return null;
6608        }
6609        final int callingUid = Binder.getCallingUid();
6610        intent = updateIntentForResolve(intent);
6611        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6612        final int flags = updateFlagsForResolve(
6613                0, userId, intent, callingUid, false /*includeInstantApps*/);
6614        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6615                userId);
6616        synchronized (mPackages) {
6617            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6618                    userId);
6619        }
6620    }
6621
6622    @Override
6623    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6624            IntentFilter filter, int match, ComponentName activity) {
6625        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6626            return;
6627        }
6628        final int userId = UserHandle.getCallingUserId();
6629        if (DEBUG_PREFERRED) {
6630            Log.v(TAG, "setLastChosenActivity intent=" + intent
6631                + " resolvedType=" + resolvedType
6632                + " flags=" + flags
6633                + " filter=" + filter
6634                + " match=" + match
6635                + " activity=" + activity);
6636            filter.dump(new PrintStreamPrinter(System.out), "    ");
6637        }
6638        intent.setComponent(null);
6639        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6640                userId);
6641        // Find any earlier preferred or last chosen entries and nuke them
6642        findPreferredActivity(intent, resolvedType,
6643                flags, query, 0, false, true, false, userId);
6644        // Add the new activity as the last chosen for this filter
6645        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6646                "Setting last chosen");
6647    }
6648
6649    @Override
6650    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6651        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6652            return null;
6653        }
6654        final int userId = UserHandle.getCallingUserId();
6655        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6656        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6657                userId);
6658        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6659                false, false, false, userId);
6660    }
6661
6662    /**
6663     * Returns whether or not instant apps have been disabled remotely.
6664     */
6665    private boolean isEphemeralDisabled() {
6666        return mEphemeralAppsDisabled;
6667    }
6668
6669    private boolean isInstantAppAllowed(
6670            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6671            boolean skipPackageCheck) {
6672        if (mInstantAppResolverConnection == null) {
6673            return false;
6674        }
6675        if (mInstantAppInstallerActivity == null) {
6676            return false;
6677        }
6678        if (intent.getComponent() != null) {
6679            return false;
6680        }
6681        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6682            return false;
6683        }
6684        if (!skipPackageCheck && intent.getPackage() != null) {
6685            return false;
6686        }
6687        final boolean isWebUri = hasWebURI(intent);
6688        if (!isWebUri || intent.getData().getHost() == null) {
6689            return false;
6690        }
6691        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6692        // Or if there's already an ephemeral app installed that handles the action
6693        synchronized (mPackages) {
6694            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6695            for (int n = 0; n < count; n++) {
6696                final ResolveInfo info = resolvedActivities.get(n);
6697                final String packageName = info.activityInfo.packageName;
6698                final PackageSetting ps = mSettings.mPackages.get(packageName);
6699                if (ps != null) {
6700                    // only check domain verification status if the app is not a browser
6701                    if (!info.handleAllWebDataURI) {
6702                        // Try to get the status from User settings first
6703                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6704                        final int status = (int) (packedStatus >> 32);
6705                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6706                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6707                            if (DEBUG_EPHEMERAL) {
6708                                Slog.v(TAG, "DENY instant app;"
6709                                    + " pkg: " + packageName + ", status: " + status);
6710                            }
6711                            return false;
6712                        }
6713                    }
6714                    if (ps.getInstantApp(userId)) {
6715                        if (DEBUG_EPHEMERAL) {
6716                            Slog.v(TAG, "DENY instant app installed;"
6717                                    + " pkg: " + packageName);
6718                        }
6719                        return false;
6720                    }
6721                }
6722            }
6723        }
6724        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6725        return true;
6726    }
6727
6728    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6729            Intent origIntent, String resolvedType, String callingPackage,
6730            Bundle verificationBundle, int userId) {
6731        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6732                new InstantAppRequest(responseObj, origIntent, resolvedType,
6733                        callingPackage, userId, verificationBundle));
6734        mHandler.sendMessage(msg);
6735    }
6736
6737    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6738            int flags, List<ResolveInfo> query, int userId) {
6739        if (query != null) {
6740            final int N = query.size();
6741            if (N == 1) {
6742                return query.get(0);
6743            } else if (N > 1) {
6744                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6745                // If there is more than one activity with the same priority,
6746                // then let the user decide between them.
6747                ResolveInfo r0 = query.get(0);
6748                ResolveInfo r1 = query.get(1);
6749                if (DEBUG_INTENT_MATCHING || debug) {
6750                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6751                            + r1.activityInfo.name + "=" + r1.priority);
6752                }
6753                // If the first activity has a higher priority, or a different
6754                // default, then it is always desirable to pick it.
6755                if (r0.priority != r1.priority
6756                        || r0.preferredOrder != r1.preferredOrder
6757                        || r0.isDefault != r1.isDefault) {
6758                    return query.get(0);
6759                }
6760                // If we have saved a preference for a preferred activity for
6761                // this Intent, use that.
6762                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6763                        flags, query, r0.priority, true, false, debug, userId);
6764                if (ri != null) {
6765                    return ri;
6766                }
6767                // If we have an ephemeral app, use it
6768                for (int i = 0; i < N; i++) {
6769                    ri = query.get(i);
6770                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6771                        final String packageName = ri.activityInfo.packageName;
6772                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6773                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6774                        final int status = (int)(packedStatus >> 32);
6775                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6776                            return ri;
6777                        }
6778                    }
6779                }
6780                ri = new ResolveInfo(mResolveInfo);
6781                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6782                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6783                // If all of the options come from the same package, show the application's
6784                // label and icon instead of the generic resolver's.
6785                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6786                // and then throw away the ResolveInfo itself, meaning that the caller loses
6787                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6788                // a fallback for this case; we only set the target package's resources on
6789                // the ResolveInfo, not the ActivityInfo.
6790                final String intentPackage = intent.getPackage();
6791                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6792                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6793                    ri.resolvePackageName = intentPackage;
6794                    if (userNeedsBadging(userId)) {
6795                        ri.noResourceId = true;
6796                    } else {
6797                        ri.icon = appi.icon;
6798                    }
6799                    ri.iconResourceId = appi.icon;
6800                    ri.labelRes = appi.labelRes;
6801                }
6802                ri.activityInfo.applicationInfo = new ApplicationInfo(
6803                        ri.activityInfo.applicationInfo);
6804                if (userId != 0) {
6805                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6806                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6807                }
6808                // Make sure that the resolver is displayable in car mode
6809                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6810                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6811                return ri;
6812            }
6813        }
6814        return null;
6815    }
6816
6817    /**
6818     * Return true if the given list is not empty and all of its contents have
6819     * an activityInfo with the given package name.
6820     */
6821    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6822        if (ArrayUtils.isEmpty(list)) {
6823            return false;
6824        }
6825        for (int i = 0, N = list.size(); i < N; i++) {
6826            final ResolveInfo ri = list.get(i);
6827            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6828            if (ai == null || !packageName.equals(ai.packageName)) {
6829                return false;
6830            }
6831        }
6832        return true;
6833    }
6834
6835    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6836            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6837        final int N = query.size();
6838        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6839                .get(userId);
6840        // Get the list of persistent preferred activities that handle the intent
6841        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6842        List<PersistentPreferredActivity> pprefs = ppir != null
6843                ? ppir.queryIntent(intent, resolvedType,
6844                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6845                        userId)
6846                : null;
6847        if (pprefs != null && pprefs.size() > 0) {
6848            final int M = pprefs.size();
6849            for (int i=0; i<M; i++) {
6850                final PersistentPreferredActivity ppa = pprefs.get(i);
6851                if (DEBUG_PREFERRED || debug) {
6852                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6853                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6854                            + "\n  component=" + ppa.mComponent);
6855                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6856                }
6857                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6858                        flags | MATCH_DISABLED_COMPONENTS, userId);
6859                if (DEBUG_PREFERRED || debug) {
6860                    Slog.v(TAG, "Found persistent preferred activity:");
6861                    if (ai != null) {
6862                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6863                    } else {
6864                        Slog.v(TAG, "  null");
6865                    }
6866                }
6867                if (ai == null) {
6868                    // This previously registered persistent preferred activity
6869                    // component is no longer known. Ignore it and do NOT remove it.
6870                    continue;
6871                }
6872                for (int j=0; j<N; j++) {
6873                    final ResolveInfo ri = query.get(j);
6874                    if (!ri.activityInfo.applicationInfo.packageName
6875                            .equals(ai.applicationInfo.packageName)) {
6876                        continue;
6877                    }
6878                    if (!ri.activityInfo.name.equals(ai.name)) {
6879                        continue;
6880                    }
6881                    //  Found a persistent preference that can handle the intent.
6882                    if (DEBUG_PREFERRED || debug) {
6883                        Slog.v(TAG, "Returning persistent preferred activity: " +
6884                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6885                    }
6886                    return ri;
6887                }
6888            }
6889        }
6890        return null;
6891    }
6892
6893    // TODO: handle preferred activities missing while user has amnesia
6894    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6895            List<ResolveInfo> query, int priority, boolean always,
6896            boolean removeMatches, boolean debug, int userId) {
6897        if (!sUserManager.exists(userId)) return null;
6898        final int callingUid = Binder.getCallingUid();
6899        flags = updateFlagsForResolve(
6900                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6901        intent = updateIntentForResolve(intent);
6902        // writer
6903        synchronized (mPackages) {
6904            // Try to find a matching persistent preferred activity.
6905            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6906                    debug, userId);
6907
6908            // If a persistent preferred activity matched, use it.
6909            if (pri != null) {
6910                return pri;
6911            }
6912
6913            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6914            // Get the list of preferred activities that handle the intent
6915            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6916            List<PreferredActivity> prefs = pir != null
6917                    ? pir.queryIntent(intent, resolvedType,
6918                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6919                            userId)
6920                    : null;
6921            if (prefs != null && prefs.size() > 0) {
6922                boolean changed = false;
6923                try {
6924                    // First figure out how good the original match set is.
6925                    // We will only allow preferred activities that came
6926                    // from the same match quality.
6927                    int match = 0;
6928
6929                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6930
6931                    final int N = query.size();
6932                    for (int j=0; j<N; j++) {
6933                        final ResolveInfo ri = query.get(j);
6934                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6935                                + ": 0x" + Integer.toHexString(match));
6936                        if (ri.match > match) {
6937                            match = ri.match;
6938                        }
6939                    }
6940
6941                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6942                            + Integer.toHexString(match));
6943
6944                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6945                    final int M = prefs.size();
6946                    for (int i=0; i<M; i++) {
6947                        final PreferredActivity pa = prefs.get(i);
6948                        if (DEBUG_PREFERRED || debug) {
6949                            Slog.v(TAG, "Checking PreferredActivity ds="
6950                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6951                                    + "\n  component=" + pa.mPref.mComponent);
6952                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6953                        }
6954                        if (pa.mPref.mMatch != match) {
6955                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6956                                    + Integer.toHexString(pa.mPref.mMatch));
6957                            continue;
6958                        }
6959                        // If it's not an "always" type preferred activity and that's what we're
6960                        // looking for, skip it.
6961                        if (always && !pa.mPref.mAlways) {
6962                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6963                            continue;
6964                        }
6965                        final ActivityInfo ai = getActivityInfo(
6966                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6967                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6968                                userId);
6969                        if (DEBUG_PREFERRED || debug) {
6970                            Slog.v(TAG, "Found preferred activity:");
6971                            if (ai != null) {
6972                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6973                            } else {
6974                                Slog.v(TAG, "  null");
6975                            }
6976                        }
6977                        if (ai == null) {
6978                            // This previously registered preferred activity
6979                            // component is no longer known.  Most likely an update
6980                            // to the app was installed and in the new version this
6981                            // component no longer exists.  Clean it up by removing
6982                            // it from the preferred activities list, and skip it.
6983                            Slog.w(TAG, "Removing dangling preferred activity: "
6984                                    + pa.mPref.mComponent);
6985                            pir.removeFilter(pa);
6986                            changed = true;
6987                            continue;
6988                        }
6989                        for (int j=0; j<N; j++) {
6990                            final ResolveInfo ri = query.get(j);
6991                            if (!ri.activityInfo.applicationInfo.packageName
6992                                    .equals(ai.applicationInfo.packageName)) {
6993                                continue;
6994                            }
6995                            if (!ri.activityInfo.name.equals(ai.name)) {
6996                                continue;
6997                            }
6998
6999                            if (removeMatches) {
7000                                pir.removeFilter(pa);
7001                                changed = true;
7002                                if (DEBUG_PREFERRED) {
7003                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
7004                                }
7005                                break;
7006                            }
7007
7008                            // Okay we found a previously set preferred or last chosen app.
7009                            // If the result set is different from when this
7010                            // was created, we need to clear it and re-ask the
7011                            // user their preference, if we're looking for an "always" type entry.
7012                            if (always && !pa.mPref.sameSet(query)) {
7013                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
7014                                        + intent + " type " + resolvedType);
7015                                if (DEBUG_PREFERRED) {
7016                                    Slog.v(TAG, "Removing preferred activity since set changed "
7017                                            + pa.mPref.mComponent);
7018                                }
7019                                pir.removeFilter(pa);
7020                                // Re-add the filter as a "last chosen" entry (!always)
7021                                PreferredActivity lastChosen = new PreferredActivity(
7022                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
7023                                pir.addFilter(lastChosen);
7024                                changed = true;
7025                                return null;
7026                            }
7027
7028                            // Yay! Either the set matched or we're looking for the last chosen
7029                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
7030                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
7031                            return ri;
7032                        }
7033                    }
7034                } finally {
7035                    if (changed) {
7036                        if (DEBUG_PREFERRED) {
7037                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
7038                        }
7039                        scheduleWritePackageRestrictionsLocked(userId);
7040                    }
7041                }
7042            }
7043        }
7044        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
7045        return null;
7046    }
7047
7048    /*
7049     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
7050     */
7051    @Override
7052    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
7053            int targetUserId) {
7054        mContext.enforceCallingOrSelfPermission(
7055                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
7056        List<CrossProfileIntentFilter> matches =
7057                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
7058        if (matches != null) {
7059            int size = matches.size();
7060            for (int i = 0; i < size; i++) {
7061                if (matches.get(i).getTargetUserId() == targetUserId) return true;
7062            }
7063        }
7064        if (hasWebURI(intent)) {
7065            // cross-profile app linking works only towards the parent.
7066            final int callingUid = Binder.getCallingUid();
7067            final UserInfo parent = getProfileParent(sourceUserId);
7068            synchronized(mPackages) {
7069                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
7070                        false /*includeInstantApps*/);
7071                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
7072                        intent, resolvedType, flags, sourceUserId, parent.id);
7073                return xpDomainInfo != null;
7074            }
7075        }
7076        return false;
7077    }
7078
7079    private UserInfo getProfileParent(int userId) {
7080        final long identity = Binder.clearCallingIdentity();
7081        try {
7082            return sUserManager.getProfileParent(userId);
7083        } finally {
7084            Binder.restoreCallingIdentity(identity);
7085        }
7086    }
7087
7088    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
7089            String resolvedType, int userId) {
7090        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
7091        if (resolver != null) {
7092            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
7093        }
7094        return null;
7095    }
7096
7097    @Override
7098    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
7099            String resolvedType, int flags, int userId) {
7100        try {
7101            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
7102
7103            return new ParceledListSlice<>(
7104                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
7105        } finally {
7106            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7107        }
7108    }
7109
7110    /**
7111     * Returns the package name of the calling Uid if it's an instant app. If it isn't
7112     * instant, returns {@code null}.
7113     */
7114    private String getInstantAppPackageName(int callingUid) {
7115        synchronized (mPackages) {
7116            // If the caller is an isolated app use the owner's uid for the lookup.
7117            if (Process.isIsolated(callingUid)) {
7118                callingUid = mIsolatedOwners.get(callingUid);
7119            }
7120            final int appId = UserHandle.getAppId(callingUid);
7121            final Object obj = mSettings.getUserIdLPr(appId);
7122            if (obj instanceof PackageSetting) {
7123                final PackageSetting ps = (PackageSetting) obj;
7124                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
7125                return isInstantApp ? ps.pkg.packageName : null;
7126            }
7127        }
7128        return null;
7129    }
7130
7131    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7132            String resolvedType, int flags, int userId) {
7133        return queryIntentActivitiesInternal(
7134                intent, resolvedType, flags, Binder.getCallingUid(), userId,
7135                false /*resolveForStart*/, true /*allowDynamicSplits*/);
7136    }
7137
7138    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7139            String resolvedType, int flags, int filterCallingUid, int userId,
7140            boolean resolveForStart, boolean allowDynamicSplits) {
7141        if (!sUserManager.exists(userId)) return Collections.emptyList();
7142        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
7143        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7144                false /* requireFullPermission */, false /* checkShell */,
7145                "query intent activities");
7146        final String pkgName = intent.getPackage();
7147        ComponentName comp = intent.getComponent();
7148        if (comp == null) {
7149            if (intent.getSelector() != null) {
7150                intent = intent.getSelector();
7151                comp = intent.getComponent();
7152            }
7153        }
7154
7155        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
7156                comp != null || pkgName != null /*onlyExposedExplicitly*/);
7157        if (comp != null) {
7158            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7159            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
7160            if (ai != null) {
7161                // When specifying an explicit component, we prevent the activity from being
7162                // used when either 1) the calling package is normal and the activity is within
7163                // an ephemeral application or 2) the calling package is ephemeral and the
7164                // activity is not visible to ephemeral applications.
7165                final boolean matchInstantApp =
7166                        (flags & PackageManager.MATCH_INSTANT) != 0;
7167                final boolean matchVisibleToInstantAppOnly =
7168                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7169                final boolean matchExplicitlyVisibleOnly =
7170                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7171                final boolean isCallerInstantApp =
7172                        instantAppPkgName != null;
7173                final boolean isTargetSameInstantApp =
7174                        comp.getPackageName().equals(instantAppPkgName);
7175                final boolean isTargetInstantApp =
7176                        (ai.applicationInfo.privateFlags
7177                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7178                final boolean isTargetVisibleToInstantApp =
7179                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7180                final boolean isTargetExplicitlyVisibleToInstantApp =
7181                        isTargetVisibleToInstantApp
7182                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7183                final boolean isTargetHiddenFromInstantApp =
7184                        !isTargetVisibleToInstantApp
7185                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7186                final boolean blockResolution =
7187                        !isTargetSameInstantApp
7188                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7189                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7190                                        && isTargetHiddenFromInstantApp));
7191                if (!blockResolution) {
7192                    final ResolveInfo ri = new ResolveInfo();
7193                    ri.activityInfo = ai;
7194                    list.add(ri);
7195                }
7196            }
7197            return applyPostResolutionFilter(
7198                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
7199        }
7200
7201        // reader
7202        boolean sortResult = false;
7203        boolean addEphemeral = false;
7204        List<ResolveInfo> result;
7205        final boolean ephemeralDisabled = isEphemeralDisabled();
7206        synchronized (mPackages) {
7207            if (pkgName == null) {
7208                List<CrossProfileIntentFilter> matchingFilters =
7209                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
7210                // Check for results that need to skip the current profile.
7211                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
7212                        resolvedType, flags, userId);
7213                if (xpResolveInfo != null) {
7214                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
7215                    xpResult.add(xpResolveInfo);
7216                    return applyPostResolutionFilter(
7217                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
7218                            allowDynamicSplits, filterCallingUid, userId);
7219                }
7220
7221                // Check for results in the current profile.
7222                result = filterIfNotSystemUser(mActivities.queryIntent(
7223                        intent, resolvedType, flags, userId), userId);
7224                addEphemeral = !ephemeralDisabled
7225                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
7226                // Check for cross profile results.
7227                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
7228                xpResolveInfo = queryCrossProfileIntents(
7229                        matchingFilters, intent, resolvedType, flags, userId,
7230                        hasNonNegativePriorityResult);
7231                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
7232                    boolean isVisibleToUser = filterIfNotSystemUser(
7233                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
7234                    if (isVisibleToUser) {
7235                        result.add(xpResolveInfo);
7236                        sortResult = true;
7237                    }
7238                }
7239                if (hasWebURI(intent)) {
7240                    CrossProfileDomainInfo xpDomainInfo = null;
7241                    final UserInfo parent = getProfileParent(userId);
7242                    if (parent != null) {
7243                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
7244                                flags, userId, parent.id);
7245                    }
7246                    if (xpDomainInfo != null) {
7247                        if (xpResolveInfo != null) {
7248                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
7249                            // in the result.
7250                            result.remove(xpResolveInfo);
7251                        }
7252                        if (result.size() == 0 && !addEphemeral) {
7253                            // No result in current profile, but found candidate in parent user.
7254                            // And we are not going to add emphemeral app, so we can return the
7255                            // result straight away.
7256                            result.add(xpDomainInfo.resolveInfo);
7257                            return applyPostResolutionFilter(result, instantAppPkgName,
7258                                    allowDynamicSplits, filterCallingUid, userId);
7259                        }
7260                    } else if (result.size() <= 1 && !addEphemeral) {
7261                        // No result in parent user and <= 1 result in current profile, and we
7262                        // are not going to add emphemeral app, so we can return the result without
7263                        // further processing.
7264                        return applyPostResolutionFilter(result, instantAppPkgName,
7265                                allowDynamicSplits, filterCallingUid, userId);
7266                    }
7267                    // We have more than one candidate (combining results from current and parent
7268                    // profile), so we need filtering and sorting.
7269                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
7270                            intent, flags, result, xpDomainInfo, userId);
7271                    sortResult = true;
7272                }
7273            } else {
7274                final PackageParser.Package pkg = mPackages.get(pkgName);
7275                result = null;
7276                if (pkg != null) {
7277                    result = filterIfNotSystemUser(
7278                            mActivities.queryIntentForPackage(
7279                                    intent, resolvedType, flags, pkg.activities, userId),
7280                            userId);
7281                }
7282                if (result == null || result.size() == 0) {
7283                    // the caller wants to resolve for a particular package; however, there
7284                    // were no installed results, so, try to find an ephemeral result
7285                    addEphemeral = !ephemeralDisabled
7286                            && isInstantAppAllowed(
7287                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
7288                    if (result == null) {
7289                        result = new ArrayList<>();
7290                    }
7291                }
7292            }
7293        }
7294        if (addEphemeral) {
7295            result = maybeAddInstantAppInstaller(result, intent, resolvedType, flags, userId);
7296        }
7297        if (sortResult) {
7298            Collections.sort(result, mResolvePrioritySorter);
7299        }
7300        return applyPostResolutionFilter(
7301                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
7302    }
7303
7304    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
7305            String resolvedType, int flags, int userId) {
7306        // first, check to see if we've got an instant app already installed
7307        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
7308        ResolveInfo localInstantApp = null;
7309        boolean blockResolution = false;
7310        if (!alreadyResolvedLocally) {
7311            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
7312                    flags
7313                        | PackageManager.GET_RESOLVED_FILTER
7314                        | PackageManager.MATCH_INSTANT
7315                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
7316                    userId);
7317            for (int i = instantApps.size() - 1; i >= 0; --i) {
7318                final ResolveInfo info = instantApps.get(i);
7319                final String packageName = info.activityInfo.packageName;
7320                final PackageSetting ps = mSettings.mPackages.get(packageName);
7321                if (ps.getInstantApp(userId)) {
7322                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7323                    final int status = (int)(packedStatus >> 32);
7324                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7325                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7326                        // there's a local instant application installed, but, the user has
7327                        // chosen to never use it; skip resolution and don't acknowledge
7328                        // an instant application is even available
7329                        if (DEBUG_EPHEMERAL) {
7330                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7331                        }
7332                        blockResolution = true;
7333                        break;
7334                    } else {
7335                        // we have a locally installed instant application; skip resolution
7336                        // but acknowledge there's an instant application available
7337                        if (DEBUG_EPHEMERAL) {
7338                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7339                        }
7340                        localInstantApp = info;
7341                        break;
7342                    }
7343                }
7344            }
7345        }
7346        // no app installed, let's see if one's available
7347        AuxiliaryResolveInfo auxiliaryResponse = null;
7348        if (!blockResolution) {
7349            if (localInstantApp == null) {
7350                // we don't have an instant app locally, resolve externally
7351                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7352                final InstantAppRequest requestObject = new InstantAppRequest(
7353                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
7354                        null /*callingPackage*/, userId, null /*verificationBundle*/);
7355                auxiliaryResponse =
7356                        InstantAppResolver.doInstantAppResolutionPhaseOne(
7357                                mContext, mInstantAppResolverConnection, requestObject);
7358                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7359            } else {
7360                // we have an instant application locally, but, we can't admit that since
7361                // callers shouldn't be able to determine prior browsing. create a dummy
7362                // auxiliary response so the downstream code behaves as if there's an
7363                // instant application available externally. when it comes time to start
7364                // the instant application, we'll do the right thing.
7365                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7366                auxiliaryResponse = new AuxiliaryResolveInfo(
7367                        ai.packageName, null /*splitName*/, null /*failureActivity*/,
7368                        ai.versionCode, null /*failureIntent*/);
7369            }
7370        }
7371        if (auxiliaryResponse != null) {
7372            if (DEBUG_EPHEMERAL) {
7373                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7374            }
7375            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7376            final PackageSetting ps =
7377                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7378            if (ps != null) {
7379                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7380                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7381                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
7382                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7383                // make sure this resolver is the default
7384                ephemeralInstaller.isDefault = true;
7385                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7386                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7387                // add a non-generic filter
7388                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
7389                ephemeralInstaller.filter.addDataPath(
7390                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7391                ephemeralInstaller.isInstantAppAvailable = true;
7392                result.add(ephemeralInstaller);
7393            }
7394        }
7395        return result;
7396    }
7397
7398    private static class CrossProfileDomainInfo {
7399        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7400        ResolveInfo resolveInfo;
7401        /* Best domain verification status of the activities found in the other profile */
7402        int bestDomainVerificationStatus;
7403    }
7404
7405    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7406            String resolvedType, int flags, int sourceUserId, int parentUserId) {
7407        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7408                sourceUserId)) {
7409            return null;
7410        }
7411        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7412                resolvedType, flags, parentUserId);
7413
7414        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7415            return null;
7416        }
7417        CrossProfileDomainInfo result = null;
7418        int size = resultTargetUser.size();
7419        for (int i = 0; i < size; i++) {
7420            ResolveInfo riTargetUser = resultTargetUser.get(i);
7421            // Intent filter verification is only for filters that specify a host. So don't return
7422            // those that handle all web uris.
7423            if (riTargetUser.handleAllWebDataURI) {
7424                continue;
7425            }
7426            String packageName = riTargetUser.activityInfo.packageName;
7427            PackageSetting ps = mSettings.mPackages.get(packageName);
7428            if (ps == null) {
7429                continue;
7430            }
7431            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7432            int status = (int)(verificationState >> 32);
7433            if (result == null) {
7434                result = new CrossProfileDomainInfo();
7435                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7436                        sourceUserId, parentUserId);
7437                result.bestDomainVerificationStatus = status;
7438            } else {
7439                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7440                        result.bestDomainVerificationStatus);
7441            }
7442        }
7443        // Don't consider matches with status NEVER across profiles.
7444        if (result != null && result.bestDomainVerificationStatus
7445                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7446            return null;
7447        }
7448        return result;
7449    }
7450
7451    /**
7452     * Verification statuses are ordered from the worse to the best, except for
7453     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7454     */
7455    private int bestDomainVerificationStatus(int status1, int status2) {
7456        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7457            return status2;
7458        }
7459        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7460            return status1;
7461        }
7462        return (int) MathUtils.max(status1, status2);
7463    }
7464
7465    private boolean isUserEnabled(int userId) {
7466        long callingId = Binder.clearCallingIdentity();
7467        try {
7468            UserInfo userInfo = sUserManager.getUserInfo(userId);
7469            return userInfo != null && userInfo.isEnabled();
7470        } finally {
7471            Binder.restoreCallingIdentity(callingId);
7472        }
7473    }
7474
7475    /**
7476     * Filter out activities with systemUserOnly flag set, when current user is not System.
7477     *
7478     * @return filtered list
7479     */
7480    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7481        if (userId == UserHandle.USER_SYSTEM) {
7482            return resolveInfos;
7483        }
7484        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7485            ResolveInfo info = resolveInfos.get(i);
7486            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7487                resolveInfos.remove(i);
7488            }
7489        }
7490        return resolveInfos;
7491    }
7492
7493    /**
7494     * Filters out ephemeral activities.
7495     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7496     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7497     *
7498     * @param resolveInfos The pre-filtered list of resolved activities
7499     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7500     *          is performed.
7501     * @return A filtered list of resolved activities.
7502     */
7503    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7504            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) {
7505        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7506            final ResolveInfo info = resolveInfos.get(i);
7507            // allow activities that are defined in the provided package
7508            if (allowDynamicSplits
7509                    && info.activityInfo.splitName != null
7510                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7511                            info.activityInfo.splitName)) {
7512                // requested activity is defined in a split that hasn't been installed yet.
7513                // add the installer to the resolve list
7514                if (DEBUG_INSTALL) {
7515                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
7516                }
7517                final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7518                final ComponentName installFailureActivity = findInstallFailureActivity(
7519                        info.activityInfo.packageName,  filterCallingUid, userId);
7520                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7521                        info.activityInfo.packageName, info.activityInfo.splitName,
7522                        installFailureActivity,
7523                        info.activityInfo.applicationInfo.versionCode,
7524                        null /*failureIntent*/);
7525                // make sure this resolver is the default
7526                installerInfo.isDefault = true;
7527                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7528                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7529                // add a non-generic filter
7530                installerInfo.filter = new IntentFilter();
7531                // load resources from the correct package
7532                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7533                resolveInfos.set(i, installerInfo);
7534                continue;
7535            }
7536            // caller is a full app, don't need to apply any other filtering
7537            if (ephemeralPkgName == null) {
7538                continue;
7539            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
7540                // caller is same app; don't need to apply any other filtering
7541                continue;
7542            }
7543            // allow activities that have been explicitly exposed to ephemeral apps
7544            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7545            if (!isEphemeralApp
7546                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7547                continue;
7548            }
7549            resolveInfos.remove(i);
7550        }
7551        return resolveInfos;
7552    }
7553
7554    /**
7555     * Returns the activity component that can handle install failures.
7556     * <p>By default, the instant application installer handles failures. However, an
7557     * application may want to handle failures on its own. Applications do this by
7558     * creating an activity with an intent filter that handles the action
7559     * {@link Intent#ACTION_INSTALL_FAILURE}.
7560     */
7561    private @Nullable ComponentName findInstallFailureActivity(
7562            String packageName, int filterCallingUid, int userId) {
7563        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
7564        failureActivityIntent.setPackage(packageName);
7565        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
7566        final List<ResolveInfo> result = queryIntentActivitiesInternal(
7567                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
7568                false /*resolveForStart*/, false /*allowDynamicSplits*/);
7569        final int NR = result.size();
7570        if (NR > 0) {
7571            for (int i = 0; i < NR; i++) {
7572                final ResolveInfo info = result.get(i);
7573                if (info.activityInfo.splitName != null) {
7574                    continue;
7575                }
7576                return new ComponentName(packageName, info.activityInfo.name);
7577            }
7578        }
7579        return null;
7580    }
7581
7582    /**
7583     * @param resolveInfos list of resolve infos in descending priority order
7584     * @return if the list contains a resolve info with non-negative priority
7585     */
7586    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7587        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7588    }
7589
7590    private static boolean hasWebURI(Intent intent) {
7591        if (intent.getData() == null) {
7592            return false;
7593        }
7594        final String scheme = intent.getScheme();
7595        if (TextUtils.isEmpty(scheme)) {
7596            return false;
7597        }
7598        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7599    }
7600
7601    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7602            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7603            int userId) {
7604        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7605
7606        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7607            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7608                    candidates.size());
7609        }
7610
7611        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7612        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7613        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7614        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7615        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7616        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7617
7618        synchronized (mPackages) {
7619            final int count = candidates.size();
7620            // First, try to use linked apps. Partition the candidates into four lists:
7621            // one for the final results, one for the "do not use ever", one for "undefined status"
7622            // and finally one for "browser app type".
7623            for (int n=0; n<count; n++) {
7624                ResolveInfo info = candidates.get(n);
7625                String packageName = info.activityInfo.packageName;
7626                PackageSetting ps = mSettings.mPackages.get(packageName);
7627                if (ps != null) {
7628                    // Add to the special match all list (Browser use case)
7629                    if (info.handleAllWebDataURI) {
7630                        matchAllList.add(info);
7631                        continue;
7632                    }
7633                    // Try to get the status from User settings first
7634                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7635                    int status = (int)(packedStatus >> 32);
7636                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7637                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7638                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7639                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7640                                    + " : linkgen=" + linkGeneration);
7641                        }
7642                        // Use link-enabled generation as preferredOrder, i.e.
7643                        // prefer newly-enabled over earlier-enabled.
7644                        info.preferredOrder = linkGeneration;
7645                        alwaysList.add(info);
7646                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7647                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7648                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7649                        }
7650                        neverList.add(info);
7651                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7652                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7653                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7654                        }
7655                        alwaysAskList.add(info);
7656                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7657                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7658                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7659                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7660                        }
7661                        undefinedList.add(info);
7662                    }
7663                }
7664            }
7665
7666            // We'll want to include browser possibilities in a few cases
7667            boolean includeBrowser = false;
7668
7669            // First try to add the "always" resolution(s) for the current user, if any
7670            if (alwaysList.size() > 0) {
7671                result.addAll(alwaysList);
7672            } else {
7673                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7674                result.addAll(undefinedList);
7675                // Maybe add one for the other profile.
7676                if (xpDomainInfo != null && (
7677                        xpDomainInfo.bestDomainVerificationStatus
7678                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7679                    result.add(xpDomainInfo.resolveInfo);
7680                }
7681                includeBrowser = true;
7682            }
7683
7684            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7685            // If there were 'always' entries their preferred order has been set, so we also
7686            // back that off to make the alternatives equivalent
7687            if (alwaysAskList.size() > 0) {
7688                for (ResolveInfo i : result) {
7689                    i.preferredOrder = 0;
7690                }
7691                result.addAll(alwaysAskList);
7692                includeBrowser = true;
7693            }
7694
7695            if (includeBrowser) {
7696                // Also add browsers (all of them or only the default one)
7697                if (DEBUG_DOMAIN_VERIFICATION) {
7698                    Slog.v(TAG, "   ...including browsers in candidate set");
7699                }
7700                if ((matchFlags & MATCH_ALL) != 0) {
7701                    result.addAll(matchAllList);
7702                } else {
7703                    // Browser/generic handling case.  If there's a default browser, go straight
7704                    // to that (but only if there is no other higher-priority match).
7705                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7706                    int maxMatchPrio = 0;
7707                    ResolveInfo defaultBrowserMatch = null;
7708                    final int numCandidates = matchAllList.size();
7709                    for (int n = 0; n < numCandidates; n++) {
7710                        ResolveInfo info = matchAllList.get(n);
7711                        // track the highest overall match priority...
7712                        if (info.priority > maxMatchPrio) {
7713                            maxMatchPrio = info.priority;
7714                        }
7715                        // ...and the highest-priority default browser match
7716                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7717                            if (defaultBrowserMatch == null
7718                                    || (defaultBrowserMatch.priority < info.priority)) {
7719                                if (debug) {
7720                                    Slog.v(TAG, "Considering default browser match " + info);
7721                                }
7722                                defaultBrowserMatch = info;
7723                            }
7724                        }
7725                    }
7726                    if (defaultBrowserMatch != null
7727                            && defaultBrowserMatch.priority >= maxMatchPrio
7728                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7729                    {
7730                        if (debug) {
7731                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7732                        }
7733                        result.add(defaultBrowserMatch);
7734                    } else {
7735                        result.addAll(matchAllList);
7736                    }
7737                }
7738
7739                // If there is nothing selected, add all candidates and remove the ones that the user
7740                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7741                if (result.size() == 0) {
7742                    result.addAll(candidates);
7743                    result.removeAll(neverList);
7744                }
7745            }
7746        }
7747        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7748            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7749                    result.size());
7750            for (ResolveInfo info : result) {
7751                Slog.v(TAG, "  + " + info.activityInfo);
7752            }
7753        }
7754        return result;
7755    }
7756
7757    // Returns a packed value as a long:
7758    //
7759    // high 'int'-sized word: link status: undefined/ask/never/always.
7760    // low 'int'-sized word: relative priority among 'always' results.
7761    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7762        long result = ps.getDomainVerificationStatusForUser(userId);
7763        // if none available, get the master status
7764        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7765            if (ps.getIntentFilterVerificationInfo() != null) {
7766                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7767            }
7768        }
7769        return result;
7770    }
7771
7772    private ResolveInfo querySkipCurrentProfileIntents(
7773            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7774            int flags, int sourceUserId) {
7775        if (matchingFilters != null) {
7776            int size = matchingFilters.size();
7777            for (int i = 0; i < size; i ++) {
7778                CrossProfileIntentFilter filter = matchingFilters.get(i);
7779                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7780                    // Checking if there are activities in the target user that can handle the
7781                    // intent.
7782                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7783                            resolvedType, flags, sourceUserId);
7784                    if (resolveInfo != null) {
7785                        return resolveInfo;
7786                    }
7787                }
7788            }
7789        }
7790        return null;
7791    }
7792
7793    // Return matching ResolveInfo in target user if any.
7794    private ResolveInfo queryCrossProfileIntents(
7795            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7796            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7797        if (matchingFilters != null) {
7798            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7799            // match the same intent. For performance reasons, it is better not to
7800            // run queryIntent twice for the same userId
7801            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7802            int size = matchingFilters.size();
7803            for (int i = 0; i < size; i++) {
7804                CrossProfileIntentFilter filter = matchingFilters.get(i);
7805                int targetUserId = filter.getTargetUserId();
7806                boolean skipCurrentProfile =
7807                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7808                boolean skipCurrentProfileIfNoMatchFound =
7809                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7810                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7811                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7812                    // Checking if there are activities in the target user that can handle the
7813                    // intent.
7814                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7815                            resolvedType, flags, sourceUserId);
7816                    if (resolveInfo != null) return resolveInfo;
7817                    alreadyTriedUserIds.put(targetUserId, true);
7818                }
7819            }
7820        }
7821        return null;
7822    }
7823
7824    /**
7825     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7826     * will forward the intent to the filter's target user.
7827     * Otherwise, returns null.
7828     */
7829    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7830            String resolvedType, int flags, int sourceUserId) {
7831        int targetUserId = filter.getTargetUserId();
7832        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7833                resolvedType, flags, targetUserId);
7834        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7835            // If all the matches in the target profile are suspended, return null.
7836            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7837                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7838                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7839                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7840                            targetUserId);
7841                }
7842            }
7843        }
7844        return null;
7845    }
7846
7847    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7848            int sourceUserId, int targetUserId) {
7849        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7850        long ident = Binder.clearCallingIdentity();
7851        boolean targetIsProfile;
7852        try {
7853            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7854        } finally {
7855            Binder.restoreCallingIdentity(ident);
7856        }
7857        String className;
7858        if (targetIsProfile) {
7859            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7860        } else {
7861            className = FORWARD_INTENT_TO_PARENT;
7862        }
7863        ComponentName forwardingActivityComponentName = new ComponentName(
7864                mAndroidApplication.packageName, className);
7865        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7866                sourceUserId);
7867        if (!targetIsProfile) {
7868            forwardingActivityInfo.showUserIcon = targetUserId;
7869            forwardingResolveInfo.noResourceId = true;
7870        }
7871        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7872        forwardingResolveInfo.priority = 0;
7873        forwardingResolveInfo.preferredOrder = 0;
7874        forwardingResolveInfo.match = 0;
7875        forwardingResolveInfo.isDefault = true;
7876        forwardingResolveInfo.filter = filter;
7877        forwardingResolveInfo.targetUserId = targetUserId;
7878        return forwardingResolveInfo;
7879    }
7880
7881    @Override
7882    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7883            Intent[] specifics, String[] specificTypes, Intent intent,
7884            String resolvedType, int flags, int userId) {
7885        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7886                specificTypes, intent, resolvedType, flags, userId));
7887    }
7888
7889    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7890            Intent[] specifics, String[] specificTypes, Intent intent,
7891            String resolvedType, int flags, int userId) {
7892        if (!sUserManager.exists(userId)) return Collections.emptyList();
7893        final int callingUid = Binder.getCallingUid();
7894        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7895                false /*includeInstantApps*/);
7896        enforceCrossUserPermission(callingUid, userId,
7897                false /*requireFullPermission*/, false /*checkShell*/,
7898                "query intent activity options");
7899        final String resultsAction = intent.getAction();
7900
7901        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7902                | PackageManager.GET_RESOLVED_FILTER, userId);
7903
7904        if (DEBUG_INTENT_MATCHING) {
7905            Log.v(TAG, "Query " + intent + ": " + results);
7906        }
7907
7908        int specificsPos = 0;
7909        int N;
7910
7911        // todo: note that the algorithm used here is O(N^2).  This
7912        // isn't a problem in our current environment, but if we start running
7913        // into situations where we have more than 5 or 10 matches then this
7914        // should probably be changed to something smarter...
7915
7916        // First we go through and resolve each of the specific items
7917        // that were supplied, taking care of removing any corresponding
7918        // duplicate items in the generic resolve list.
7919        if (specifics != null) {
7920            for (int i=0; i<specifics.length; i++) {
7921                final Intent sintent = specifics[i];
7922                if (sintent == null) {
7923                    continue;
7924                }
7925
7926                if (DEBUG_INTENT_MATCHING) {
7927                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7928                }
7929
7930                String action = sintent.getAction();
7931                if (resultsAction != null && resultsAction.equals(action)) {
7932                    // If this action was explicitly requested, then don't
7933                    // remove things that have it.
7934                    action = null;
7935                }
7936
7937                ResolveInfo ri = null;
7938                ActivityInfo ai = null;
7939
7940                ComponentName comp = sintent.getComponent();
7941                if (comp == null) {
7942                    ri = resolveIntent(
7943                        sintent,
7944                        specificTypes != null ? specificTypes[i] : null,
7945                            flags, userId);
7946                    if (ri == null) {
7947                        continue;
7948                    }
7949                    if (ri == mResolveInfo) {
7950                        // ACK!  Must do something better with this.
7951                    }
7952                    ai = ri.activityInfo;
7953                    comp = new ComponentName(ai.applicationInfo.packageName,
7954                            ai.name);
7955                } else {
7956                    ai = getActivityInfo(comp, flags, userId);
7957                    if (ai == null) {
7958                        continue;
7959                    }
7960                }
7961
7962                // Look for any generic query activities that are duplicates
7963                // of this specific one, and remove them from the results.
7964                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7965                N = results.size();
7966                int j;
7967                for (j=specificsPos; j<N; j++) {
7968                    ResolveInfo sri = results.get(j);
7969                    if ((sri.activityInfo.name.equals(comp.getClassName())
7970                            && sri.activityInfo.applicationInfo.packageName.equals(
7971                                    comp.getPackageName()))
7972                        || (action != null && sri.filter.matchAction(action))) {
7973                        results.remove(j);
7974                        if (DEBUG_INTENT_MATCHING) Log.v(
7975                            TAG, "Removing duplicate item from " + j
7976                            + " due to specific " + specificsPos);
7977                        if (ri == null) {
7978                            ri = sri;
7979                        }
7980                        j--;
7981                        N--;
7982                    }
7983                }
7984
7985                // Add this specific item to its proper place.
7986                if (ri == null) {
7987                    ri = new ResolveInfo();
7988                    ri.activityInfo = ai;
7989                }
7990                results.add(specificsPos, ri);
7991                ri.specificIndex = i;
7992                specificsPos++;
7993            }
7994        }
7995
7996        // Now we go through the remaining generic results and remove any
7997        // duplicate actions that are found here.
7998        N = results.size();
7999        for (int i=specificsPos; i<N-1; i++) {
8000            final ResolveInfo rii = results.get(i);
8001            if (rii.filter == null) {
8002                continue;
8003            }
8004
8005            // Iterate over all of the actions of this result's intent
8006            // filter...  typically this should be just one.
8007            final Iterator<String> it = rii.filter.actionsIterator();
8008            if (it == null) {
8009                continue;
8010            }
8011            while (it.hasNext()) {
8012                final String action = it.next();
8013                if (resultsAction != null && resultsAction.equals(action)) {
8014                    // If this action was explicitly requested, then don't
8015                    // remove things that have it.
8016                    continue;
8017                }
8018                for (int j=i+1; j<N; j++) {
8019                    final ResolveInfo rij = results.get(j);
8020                    if (rij.filter != null && rij.filter.hasAction(action)) {
8021                        results.remove(j);
8022                        if (DEBUG_INTENT_MATCHING) Log.v(
8023                            TAG, "Removing duplicate item from " + j
8024                            + " due to action " + action + " at " + i);
8025                        j--;
8026                        N--;
8027                    }
8028                }
8029            }
8030
8031            // If the caller didn't request filter information, drop it now
8032            // so we don't have to marshall/unmarshall it.
8033            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
8034                rii.filter = null;
8035            }
8036        }
8037
8038        // Filter out the caller activity if so requested.
8039        if (caller != null) {
8040            N = results.size();
8041            for (int i=0; i<N; i++) {
8042                ActivityInfo ainfo = results.get(i).activityInfo;
8043                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
8044                        && caller.getClassName().equals(ainfo.name)) {
8045                    results.remove(i);
8046                    break;
8047                }
8048            }
8049        }
8050
8051        // If the caller didn't request filter information,
8052        // drop them now so we don't have to
8053        // marshall/unmarshall it.
8054        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
8055            N = results.size();
8056            for (int i=0; i<N; i++) {
8057                results.get(i).filter = null;
8058            }
8059        }
8060
8061        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
8062        return results;
8063    }
8064
8065    @Override
8066    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
8067            String resolvedType, int flags, int userId) {
8068        return new ParceledListSlice<>(
8069                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
8070                        false /*allowDynamicSplits*/));
8071    }
8072
8073    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
8074            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
8075        if (!sUserManager.exists(userId)) return Collections.emptyList();
8076        final int callingUid = Binder.getCallingUid();
8077        enforceCrossUserPermission(callingUid, userId,
8078                false /*requireFullPermission*/, false /*checkShell*/,
8079                "query intent receivers");
8080        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8081        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8082                false /*includeInstantApps*/);
8083        ComponentName comp = intent.getComponent();
8084        if (comp == null) {
8085            if (intent.getSelector() != null) {
8086                intent = intent.getSelector();
8087                comp = intent.getComponent();
8088            }
8089        }
8090        if (comp != null) {
8091            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8092            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
8093            if (ai != null) {
8094                // When specifying an explicit component, we prevent the activity from being
8095                // used when either 1) the calling package is normal and the activity is within
8096                // an instant application or 2) the calling package is ephemeral and the
8097                // activity is not visible to instant applications.
8098                final boolean matchInstantApp =
8099                        (flags & PackageManager.MATCH_INSTANT) != 0;
8100                final boolean matchVisibleToInstantAppOnly =
8101                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8102                final boolean matchExplicitlyVisibleOnly =
8103                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
8104                final boolean isCallerInstantApp =
8105                        instantAppPkgName != null;
8106                final boolean isTargetSameInstantApp =
8107                        comp.getPackageName().equals(instantAppPkgName);
8108                final boolean isTargetInstantApp =
8109                        (ai.applicationInfo.privateFlags
8110                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8111                final boolean isTargetVisibleToInstantApp =
8112                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
8113                final boolean isTargetExplicitlyVisibleToInstantApp =
8114                        isTargetVisibleToInstantApp
8115                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
8116                final boolean isTargetHiddenFromInstantApp =
8117                        !isTargetVisibleToInstantApp
8118                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
8119                final boolean blockResolution =
8120                        !isTargetSameInstantApp
8121                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8122                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8123                                        && isTargetHiddenFromInstantApp));
8124                if (!blockResolution) {
8125                    ResolveInfo ri = new ResolveInfo();
8126                    ri.activityInfo = ai;
8127                    list.add(ri);
8128                }
8129            }
8130            return applyPostResolutionFilter(
8131                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8132        }
8133
8134        // reader
8135        synchronized (mPackages) {
8136            String pkgName = intent.getPackage();
8137            if (pkgName == null) {
8138                final List<ResolveInfo> result =
8139                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
8140                return applyPostResolutionFilter(
8141                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8142            }
8143            final PackageParser.Package pkg = mPackages.get(pkgName);
8144            if (pkg != null) {
8145                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
8146                        intent, resolvedType, flags, pkg.receivers, userId);
8147                return applyPostResolutionFilter(
8148                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8149            }
8150            return Collections.emptyList();
8151        }
8152    }
8153
8154    @Override
8155    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
8156        final int callingUid = Binder.getCallingUid();
8157        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
8158    }
8159
8160    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
8161            int userId, int callingUid) {
8162        if (!sUserManager.exists(userId)) return null;
8163        flags = updateFlagsForResolve(
8164                flags, userId, intent, callingUid, false /*includeInstantApps*/);
8165        List<ResolveInfo> query = queryIntentServicesInternal(
8166                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
8167        if (query != null) {
8168            if (query.size() >= 1) {
8169                // If there is more than one service with the same priority,
8170                // just arbitrarily pick the first one.
8171                return query.get(0);
8172            }
8173        }
8174        return null;
8175    }
8176
8177    @Override
8178    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
8179            String resolvedType, int flags, int userId) {
8180        final int callingUid = Binder.getCallingUid();
8181        return new ParceledListSlice<>(queryIntentServicesInternal(
8182                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
8183    }
8184
8185    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
8186            String resolvedType, int flags, int userId, int callingUid,
8187            boolean includeInstantApps) {
8188        if (!sUserManager.exists(userId)) return Collections.emptyList();
8189        enforceCrossUserPermission(callingUid, userId,
8190                false /*requireFullPermission*/, false /*checkShell*/,
8191                "query intent receivers");
8192        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8193        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
8194        ComponentName comp = intent.getComponent();
8195        if (comp == null) {
8196            if (intent.getSelector() != null) {
8197                intent = intent.getSelector();
8198                comp = intent.getComponent();
8199            }
8200        }
8201        if (comp != null) {
8202            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8203            final ServiceInfo si = getServiceInfo(comp, flags, userId);
8204            if (si != null) {
8205                // When specifying an explicit component, we prevent the service from being
8206                // used when either 1) the service is in an instant application and the
8207                // caller is not the same instant application or 2) the calling package is
8208                // ephemeral and the activity is not visible to ephemeral applications.
8209                final boolean matchInstantApp =
8210                        (flags & PackageManager.MATCH_INSTANT) != 0;
8211                final boolean matchVisibleToInstantAppOnly =
8212                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8213                final boolean isCallerInstantApp =
8214                        instantAppPkgName != null;
8215                final boolean isTargetSameInstantApp =
8216                        comp.getPackageName().equals(instantAppPkgName);
8217                final boolean isTargetInstantApp =
8218                        (si.applicationInfo.privateFlags
8219                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8220                final boolean isTargetHiddenFromInstantApp =
8221                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8222                final boolean blockResolution =
8223                        !isTargetSameInstantApp
8224                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8225                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8226                                        && isTargetHiddenFromInstantApp));
8227                if (!blockResolution) {
8228                    final ResolveInfo ri = new ResolveInfo();
8229                    ri.serviceInfo = si;
8230                    list.add(ri);
8231                }
8232            }
8233            return list;
8234        }
8235
8236        // reader
8237        synchronized (mPackages) {
8238            String pkgName = intent.getPackage();
8239            if (pkgName == null) {
8240                return applyPostServiceResolutionFilter(
8241                        mServices.queryIntent(intent, resolvedType, flags, userId),
8242                        instantAppPkgName);
8243            }
8244            final PackageParser.Package pkg = mPackages.get(pkgName);
8245            if (pkg != null) {
8246                return applyPostServiceResolutionFilter(
8247                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
8248                                userId),
8249                        instantAppPkgName);
8250            }
8251            return Collections.emptyList();
8252        }
8253    }
8254
8255    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
8256            String instantAppPkgName) {
8257        if (instantAppPkgName == null) {
8258            return resolveInfos;
8259        }
8260        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8261            final ResolveInfo info = resolveInfos.get(i);
8262            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
8263            // allow services that are defined in the provided package
8264            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
8265                if (info.serviceInfo.splitName != null
8266                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
8267                                info.serviceInfo.splitName)) {
8268                    // requested service is defined in a split that hasn't been installed yet.
8269                    // add the installer to the resolve list
8270                    if (DEBUG_EPHEMERAL) {
8271                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8272                    }
8273                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8274                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8275                            info.serviceInfo.packageName, info.serviceInfo.splitName,
8276                            null /*failureActivity*/, info.serviceInfo.applicationInfo.versionCode,
8277                            null /*failureIntent*/);
8278                    // make sure this resolver is the default
8279                    installerInfo.isDefault = true;
8280                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8281                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8282                    // add a non-generic filter
8283                    installerInfo.filter = new IntentFilter();
8284                    // load resources from the correct package
8285                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8286                    resolveInfos.set(i, installerInfo);
8287                }
8288                continue;
8289            }
8290            // allow services that have been explicitly exposed to ephemeral apps
8291            if (!isEphemeralApp
8292                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8293                continue;
8294            }
8295            resolveInfos.remove(i);
8296        }
8297        return resolveInfos;
8298    }
8299
8300    @Override
8301    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
8302            String resolvedType, int flags, int userId) {
8303        return new ParceledListSlice<>(
8304                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
8305    }
8306
8307    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
8308            Intent intent, String resolvedType, int flags, int userId) {
8309        if (!sUserManager.exists(userId)) return Collections.emptyList();
8310        final int callingUid = Binder.getCallingUid();
8311        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8312        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8313                false /*includeInstantApps*/);
8314        ComponentName comp = intent.getComponent();
8315        if (comp == null) {
8316            if (intent.getSelector() != null) {
8317                intent = intent.getSelector();
8318                comp = intent.getComponent();
8319            }
8320        }
8321        if (comp != null) {
8322            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8323            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
8324            if (pi != null) {
8325                // When specifying an explicit component, we prevent the provider from being
8326                // used when either 1) the provider is in an instant application and the
8327                // caller is not the same instant application or 2) the calling package is an
8328                // instant application and the provider is not visible to instant applications.
8329                final boolean matchInstantApp =
8330                        (flags & PackageManager.MATCH_INSTANT) != 0;
8331                final boolean matchVisibleToInstantAppOnly =
8332                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8333                final boolean isCallerInstantApp =
8334                        instantAppPkgName != null;
8335                final boolean isTargetSameInstantApp =
8336                        comp.getPackageName().equals(instantAppPkgName);
8337                final boolean isTargetInstantApp =
8338                        (pi.applicationInfo.privateFlags
8339                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8340                final boolean isTargetHiddenFromInstantApp =
8341                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8342                final boolean blockResolution =
8343                        !isTargetSameInstantApp
8344                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8345                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8346                                        && isTargetHiddenFromInstantApp));
8347                if (!blockResolution) {
8348                    final ResolveInfo ri = new ResolveInfo();
8349                    ri.providerInfo = pi;
8350                    list.add(ri);
8351                }
8352            }
8353            return list;
8354        }
8355
8356        // reader
8357        synchronized (mPackages) {
8358            String pkgName = intent.getPackage();
8359            if (pkgName == null) {
8360                return applyPostContentProviderResolutionFilter(
8361                        mProviders.queryIntent(intent, resolvedType, flags, userId),
8362                        instantAppPkgName);
8363            }
8364            final PackageParser.Package pkg = mPackages.get(pkgName);
8365            if (pkg != null) {
8366                return applyPostContentProviderResolutionFilter(
8367                        mProviders.queryIntentForPackage(
8368                        intent, resolvedType, flags, pkg.providers, userId),
8369                        instantAppPkgName);
8370            }
8371            return Collections.emptyList();
8372        }
8373    }
8374
8375    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8376            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8377        if (instantAppPkgName == null) {
8378            return resolveInfos;
8379        }
8380        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8381            final ResolveInfo info = resolveInfos.get(i);
8382            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8383            // allow providers that are defined in the provided package
8384            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8385                if (info.providerInfo.splitName != null
8386                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8387                                info.providerInfo.splitName)) {
8388                    // requested provider is defined in a split that hasn't been installed yet.
8389                    // add the installer to the resolve list
8390                    if (DEBUG_EPHEMERAL) {
8391                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8392                    }
8393                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8394                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8395                            info.providerInfo.packageName, info.providerInfo.splitName,
8396                            null /*failureActivity*/, info.providerInfo.applicationInfo.versionCode,
8397                            null /*failureIntent*/);
8398                    // make sure this resolver is the default
8399                    installerInfo.isDefault = true;
8400                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8401                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8402                    // add a non-generic filter
8403                    installerInfo.filter = new IntentFilter();
8404                    // load resources from the correct package
8405                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8406                    resolveInfos.set(i, installerInfo);
8407                }
8408                continue;
8409            }
8410            // allow providers that have been explicitly exposed to instant applications
8411            if (!isEphemeralApp
8412                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8413                continue;
8414            }
8415            resolveInfos.remove(i);
8416        }
8417        return resolveInfos;
8418    }
8419
8420    @Override
8421    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8422        final int callingUid = Binder.getCallingUid();
8423        if (getInstantAppPackageName(callingUid) != null) {
8424            return ParceledListSlice.emptyList();
8425        }
8426        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8427        flags = updateFlagsForPackage(flags, userId, null);
8428        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8429        enforceCrossUserPermission(callingUid, userId,
8430                true /* requireFullPermission */, false /* checkShell */,
8431                "get installed packages");
8432
8433        // writer
8434        synchronized (mPackages) {
8435            ArrayList<PackageInfo> list;
8436            if (listUninstalled) {
8437                list = new ArrayList<>(mSettings.mPackages.size());
8438                for (PackageSetting ps : mSettings.mPackages.values()) {
8439                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8440                        continue;
8441                    }
8442                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8443                        return null;
8444                    }
8445                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8446                    if (pi != null) {
8447                        list.add(pi);
8448                    }
8449                }
8450            } else {
8451                list = new ArrayList<>(mPackages.size());
8452                for (PackageParser.Package p : mPackages.values()) {
8453                    final PackageSetting ps = (PackageSetting) p.mExtras;
8454                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8455                        continue;
8456                    }
8457                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8458                        return null;
8459                    }
8460                    final PackageInfo pi = generatePackageInfo((PackageSetting)
8461                            p.mExtras, flags, userId);
8462                    if (pi != null) {
8463                        list.add(pi);
8464                    }
8465                }
8466            }
8467
8468            return new ParceledListSlice<>(list);
8469        }
8470    }
8471
8472    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8473            String[] permissions, boolean[] tmp, int flags, int userId) {
8474        int numMatch = 0;
8475        final PermissionsState permissionsState = ps.getPermissionsState();
8476        for (int i=0; i<permissions.length; i++) {
8477            final String permission = permissions[i];
8478            if (permissionsState.hasPermission(permission, userId)) {
8479                tmp[i] = true;
8480                numMatch++;
8481            } else {
8482                tmp[i] = false;
8483            }
8484        }
8485        if (numMatch == 0) {
8486            return;
8487        }
8488        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8489
8490        // The above might return null in cases of uninstalled apps or install-state
8491        // skew across users/profiles.
8492        if (pi != null) {
8493            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8494                if (numMatch == permissions.length) {
8495                    pi.requestedPermissions = permissions;
8496                } else {
8497                    pi.requestedPermissions = new String[numMatch];
8498                    numMatch = 0;
8499                    for (int i=0; i<permissions.length; i++) {
8500                        if (tmp[i]) {
8501                            pi.requestedPermissions[numMatch] = permissions[i];
8502                            numMatch++;
8503                        }
8504                    }
8505                }
8506            }
8507            list.add(pi);
8508        }
8509    }
8510
8511    @Override
8512    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8513            String[] permissions, int flags, int userId) {
8514        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8515        flags = updateFlagsForPackage(flags, userId, permissions);
8516        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8517                true /* requireFullPermission */, false /* checkShell */,
8518                "get packages holding permissions");
8519        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8520
8521        // writer
8522        synchronized (mPackages) {
8523            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8524            boolean[] tmpBools = new boolean[permissions.length];
8525            if (listUninstalled) {
8526                for (PackageSetting ps : mSettings.mPackages.values()) {
8527                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8528                            userId);
8529                }
8530            } else {
8531                for (PackageParser.Package pkg : mPackages.values()) {
8532                    PackageSetting ps = (PackageSetting)pkg.mExtras;
8533                    if (ps != null) {
8534                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8535                                userId);
8536                    }
8537                }
8538            }
8539
8540            return new ParceledListSlice<PackageInfo>(list);
8541        }
8542    }
8543
8544    @Override
8545    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8546        final int callingUid = Binder.getCallingUid();
8547        if (getInstantAppPackageName(callingUid) != null) {
8548            return ParceledListSlice.emptyList();
8549        }
8550        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8551        flags = updateFlagsForApplication(flags, userId, null);
8552        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8553
8554        // writer
8555        synchronized (mPackages) {
8556            ArrayList<ApplicationInfo> list;
8557            if (listUninstalled) {
8558                list = new ArrayList<>(mSettings.mPackages.size());
8559                for (PackageSetting ps : mSettings.mPackages.values()) {
8560                    ApplicationInfo ai;
8561                    int effectiveFlags = flags;
8562                    if (ps.isSystem()) {
8563                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8564                    }
8565                    if (ps.pkg != null) {
8566                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8567                            continue;
8568                        }
8569                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8570                            return null;
8571                        }
8572                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8573                                ps.readUserState(userId), userId);
8574                        if (ai != null) {
8575                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8576                        }
8577                    } else {
8578                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8579                        // and already converts to externally visible package name
8580                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8581                                callingUid, effectiveFlags, userId);
8582                    }
8583                    if (ai != null) {
8584                        list.add(ai);
8585                    }
8586                }
8587            } else {
8588                list = new ArrayList<>(mPackages.size());
8589                for (PackageParser.Package p : mPackages.values()) {
8590                    if (p.mExtras != null) {
8591                        PackageSetting ps = (PackageSetting) p.mExtras;
8592                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8593                            continue;
8594                        }
8595                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8596                            return null;
8597                        }
8598                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8599                                ps.readUserState(userId), userId);
8600                        if (ai != null) {
8601                            ai.packageName = resolveExternalPackageNameLPr(p);
8602                            list.add(ai);
8603                        }
8604                    }
8605                }
8606            }
8607
8608            return new ParceledListSlice<>(list);
8609        }
8610    }
8611
8612    @Override
8613    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8614        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8615            return null;
8616        }
8617        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8618            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8619                    "getEphemeralApplications");
8620        }
8621        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8622                true /* requireFullPermission */, false /* checkShell */,
8623                "getEphemeralApplications");
8624        synchronized (mPackages) {
8625            List<InstantAppInfo> instantApps = mInstantAppRegistry
8626                    .getInstantAppsLPr(userId);
8627            if (instantApps != null) {
8628                return new ParceledListSlice<>(instantApps);
8629            }
8630        }
8631        return null;
8632    }
8633
8634    @Override
8635    public boolean isInstantApp(String packageName, int userId) {
8636        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8637                true /* requireFullPermission */, false /* checkShell */,
8638                "isInstantApp");
8639        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8640            return false;
8641        }
8642
8643        synchronized (mPackages) {
8644            int callingUid = Binder.getCallingUid();
8645            if (Process.isIsolated(callingUid)) {
8646                callingUid = mIsolatedOwners.get(callingUid);
8647            }
8648            final PackageSetting ps = mSettings.mPackages.get(packageName);
8649            PackageParser.Package pkg = mPackages.get(packageName);
8650            final boolean returnAllowed =
8651                    ps != null
8652                    && (isCallerSameApp(packageName, callingUid)
8653                            || canViewInstantApps(callingUid, userId)
8654                            || mInstantAppRegistry.isInstantAccessGranted(
8655                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8656            if (returnAllowed) {
8657                return ps.getInstantApp(userId);
8658            }
8659        }
8660        return false;
8661    }
8662
8663    @Override
8664    public byte[] getInstantAppCookie(String packageName, int userId) {
8665        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8666            return null;
8667        }
8668
8669        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8670                true /* requireFullPermission */, false /* checkShell */,
8671                "getInstantAppCookie");
8672        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8673            return null;
8674        }
8675        synchronized (mPackages) {
8676            return mInstantAppRegistry.getInstantAppCookieLPw(
8677                    packageName, userId);
8678        }
8679    }
8680
8681    @Override
8682    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8683        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8684            return true;
8685        }
8686
8687        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8688                true /* requireFullPermission */, true /* checkShell */,
8689                "setInstantAppCookie");
8690        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8691            return false;
8692        }
8693        synchronized (mPackages) {
8694            return mInstantAppRegistry.setInstantAppCookieLPw(
8695                    packageName, cookie, userId);
8696        }
8697    }
8698
8699    @Override
8700    public Bitmap getInstantAppIcon(String packageName, int userId) {
8701        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8702            return null;
8703        }
8704
8705        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8706            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8707                    "getInstantAppIcon");
8708        }
8709        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8710                true /* requireFullPermission */, false /* checkShell */,
8711                "getInstantAppIcon");
8712
8713        synchronized (mPackages) {
8714            return mInstantAppRegistry.getInstantAppIconLPw(
8715                    packageName, userId);
8716        }
8717    }
8718
8719    private boolean isCallerSameApp(String packageName, int uid) {
8720        PackageParser.Package pkg = mPackages.get(packageName);
8721        return pkg != null
8722                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8723    }
8724
8725    @Override
8726    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8727        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8728            return ParceledListSlice.emptyList();
8729        }
8730        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8731    }
8732
8733    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8734        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8735
8736        // reader
8737        synchronized (mPackages) {
8738            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8739            final int userId = UserHandle.getCallingUserId();
8740            while (i.hasNext()) {
8741                final PackageParser.Package p = i.next();
8742                if (p.applicationInfo == null) continue;
8743
8744                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8745                        && !p.applicationInfo.isDirectBootAware();
8746                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8747                        && p.applicationInfo.isDirectBootAware();
8748
8749                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8750                        && (!mSafeMode || isSystemApp(p))
8751                        && (matchesUnaware || matchesAware)) {
8752                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8753                    if (ps != null) {
8754                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8755                                ps.readUserState(userId), userId);
8756                        if (ai != null) {
8757                            finalList.add(ai);
8758                        }
8759                    }
8760                }
8761            }
8762        }
8763
8764        return finalList;
8765    }
8766
8767    @Override
8768    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8769        if (!sUserManager.exists(userId)) return null;
8770        flags = updateFlagsForComponent(flags, userId, name);
8771        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8772        // reader
8773        synchronized (mPackages) {
8774            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8775            PackageSetting ps = provider != null
8776                    ? mSettings.mPackages.get(provider.owner.packageName)
8777                    : null;
8778            if (ps != null) {
8779                final boolean isInstantApp = ps.getInstantApp(userId);
8780                // normal application; filter out instant application provider
8781                if (instantAppPkgName == null && isInstantApp) {
8782                    return null;
8783                }
8784                // instant application; filter out other instant applications
8785                if (instantAppPkgName != null
8786                        && isInstantApp
8787                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8788                    return null;
8789                }
8790                // instant application; filter out non-exposed provider
8791                if (instantAppPkgName != null
8792                        && !isInstantApp
8793                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8794                    return null;
8795                }
8796                // provider not enabled
8797                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8798                    return null;
8799                }
8800                return PackageParser.generateProviderInfo(
8801                        provider, flags, ps.readUserState(userId), userId);
8802            }
8803            return null;
8804        }
8805    }
8806
8807    /**
8808     * @deprecated
8809     */
8810    @Deprecated
8811    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8812        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8813            return;
8814        }
8815        // reader
8816        synchronized (mPackages) {
8817            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8818                    .entrySet().iterator();
8819            final int userId = UserHandle.getCallingUserId();
8820            while (i.hasNext()) {
8821                Map.Entry<String, PackageParser.Provider> entry = i.next();
8822                PackageParser.Provider p = entry.getValue();
8823                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8824
8825                if (ps != null && p.syncable
8826                        && (!mSafeMode || (p.info.applicationInfo.flags
8827                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8828                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8829                            ps.readUserState(userId), userId);
8830                    if (info != null) {
8831                        outNames.add(entry.getKey());
8832                        outInfo.add(info);
8833                    }
8834                }
8835            }
8836        }
8837    }
8838
8839    @Override
8840    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8841            int uid, int flags, String metaDataKey) {
8842        final int callingUid = Binder.getCallingUid();
8843        final int userId = processName != null ? UserHandle.getUserId(uid)
8844                : UserHandle.getCallingUserId();
8845        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8846        flags = updateFlagsForComponent(flags, userId, processName);
8847        ArrayList<ProviderInfo> finalList = null;
8848        // reader
8849        synchronized (mPackages) {
8850            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8851            while (i.hasNext()) {
8852                final PackageParser.Provider p = i.next();
8853                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8854                if (ps != null && p.info.authority != null
8855                        && (processName == null
8856                                || (p.info.processName.equals(processName)
8857                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8858                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8859
8860                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8861                    // parameter.
8862                    if (metaDataKey != null
8863                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8864                        continue;
8865                    }
8866                    final ComponentName component =
8867                            new ComponentName(p.info.packageName, p.info.name);
8868                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8869                        continue;
8870                    }
8871                    if (finalList == null) {
8872                        finalList = new ArrayList<ProviderInfo>(3);
8873                    }
8874                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8875                            ps.readUserState(userId), userId);
8876                    if (info != null) {
8877                        finalList.add(info);
8878                    }
8879                }
8880            }
8881        }
8882
8883        if (finalList != null) {
8884            Collections.sort(finalList, mProviderInitOrderSorter);
8885            return new ParceledListSlice<ProviderInfo>(finalList);
8886        }
8887
8888        return ParceledListSlice.emptyList();
8889    }
8890
8891    @Override
8892    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8893        // reader
8894        synchronized (mPackages) {
8895            final int callingUid = Binder.getCallingUid();
8896            final int callingUserId = UserHandle.getUserId(callingUid);
8897            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8898            if (ps == null) return null;
8899            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8900                return null;
8901            }
8902            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8903            return PackageParser.generateInstrumentationInfo(i, flags);
8904        }
8905    }
8906
8907    @Override
8908    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8909            String targetPackage, int flags) {
8910        final int callingUid = Binder.getCallingUid();
8911        final int callingUserId = UserHandle.getUserId(callingUid);
8912        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8913        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8914            return ParceledListSlice.emptyList();
8915        }
8916        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8917    }
8918
8919    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8920            int flags) {
8921        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8922
8923        // reader
8924        synchronized (mPackages) {
8925            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8926            while (i.hasNext()) {
8927                final PackageParser.Instrumentation p = i.next();
8928                if (targetPackage == null
8929                        || targetPackage.equals(p.info.targetPackage)) {
8930                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8931                            flags);
8932                    if (ii != null) {
8933                        finalList.add(ii);
8934                    }
8935                }
8936            }
8937        }
8938
8939        return finalList;
8940    }
8941
8942    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8943        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8944        try {
8945            scanDirLI(dir, parseFlags, scanFlags, currentTime);
8946        } finally {
8947            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8948        }
8949    }
8950
8951    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8952        final File[] files = dir.listFiles();
8953        if (ArrayUtils.isEmpty(files)) {
8954            Log.d(TAG, "No files in app dir " + dir);
8955            return;
8956        }
8957
8958        if (DEBUG_PACKAGE_SCANNING) {
8959            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8960                    + " flags=0x" + Integer.toHexString(parseFlags));
8961        }
8962        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8963                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8964                mParallelPackageParserCallback);
8965
8966        // Submit files for parsing in parallel
8967        int fileCount = 0;
8968        for (File file : files) {
8969            final boolean isPackage = (isApkFile(file) || file.isDirectory())
8970                    && !PackageInstallerService.isStageName(file.getName());
8971            if (!isPackage) {
8972                // Ignore entries which are not packages
8973                continue;
8974            }
8975            parallelPackageParser.submit(file, parseFlags);
8976            fileCount++;
8977        }
8978
8979        // Process results one by one
8980        for (; fileCount > 0; fileCount--) {
8981            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8982            Throwable throwable = parseResult.throwable;
8983            int errorCode = PackageManager.INSTALL_SUCCEEDED;
8984
8985            if (throwable == null) {
8986                // Static shared libraries have synthetic package names
8987                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8988                    renameStaticSharedLibraryPackage(parseResult.pkg);
8989                }
8990                try {
8991                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8992                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8993                                currentTime, null);
8994                    }
8995                } catch (PackageManagerException e) {
8996                    errorCode = e.error;
8997                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8998                }
8999            } else if (throwable instanceof PackageParser.PackageParserException) {
9000                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
9001                        throwable;
9002                errorCode = e.error;
9003                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
9004            } else {
9005                throw new IllegalStateException("Unexpected exception occurred while parsing "
9006                        + parseResult.scanFile, throwable);
9007            }
9008
9009            // Delete invalid userdata apps
9010            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
9011                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
9012                logCriticalInfo(Log.WARN,
9013                        "Deleting invalid package at " + parseResult.scanFile);
9014                removeCodePathLI(parseResult.scanFile);
9015            }
9016        }
9017        parallelPackageParser.close();
9018    }
9019
9020    private static File getSettingsProblemFile() {
9021        File dataDir = Environment.getDataDirectory();
9022        File systemDir = new File(dataDir, "system");
9023        File fname = new File(systemDir, "uiderrors.txt");
9024        return fname;
9025    }
9026
9027    static void reportSettingsProblem(int priority, String msg) {
9028        logCriticalInfo(priority, msg);
9029    }
9030
9031    public static void logCriticalInfo(int priority, String msg) {
9032        Slog.println(priority, TAG, msg);
9033        EventLogTags.writePmCriticalInfo(msg);
9034        try {
9035            File fname = getSettingsProblemFile();
9036            FileOutputStream out = new FileOutputStream(fname, true);
9037            PrintWriter pw = new FastPrintWriter(out);
9038            SimpleDateFormat formatter = new SimpleDateFormat();
9039            String dateString = formatter.format(new Date(System.currentTimeMillis()));
9040            pw.println(dateString + ": " + msg);
9041            pw.close();
9042            FileUtils.setPermissions(
9043                    fname.toString(),
9044                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
9045                    -1, -1);
9046        } catch (java.io.IOException e) {
9047        }
9048    }
9049
9050    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
9051        if (srcFile.isDirectory()) {
9052            final File baseFile = new File(pkg.baseCodePath);
9053            long maxModifiedTime = baseFile.lastModified();
9054            if (pkg.splitCodePaths != null) {
9055                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
9056                    final File splitFile = new File(pkg.splitCodePaths[i]);
9057                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
9058                }
9059            }
9060            return maxModifiedTime;
9061        }
9062        return srcFile.lastModified();
9063    }
9064
9065    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
9066            final int policyFlags) throws PackageManagerException {
9067        // When upgrading from pre-N MR1, verify the package time stamp using the package
9068        // directory and not the APK file.
9069        final long lastModifiedTime = mIsPreNMR1Upgrade
9070                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
9071        if (ps != null
9072                && ps.codePath.equals(srcFile)
9073                && ps.timeStamp == lastModifiedTime
9074                && !isCompatSignatureUpdateNeeded(pkg)
9075                && !isRecoverSignatureUpdateNeeded(pkg)) {
9076            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
9077            KeySetManagerService ksms = mSettings.mKeySetManagerService;
9078            ArraySet<PublicKey> signingKs;
9079            synchronized (mPackages) {
9080                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
9081            }
9082            if (ps.signatures.mSignatures != null
9083                    && ps.signatures.mSignatures.length != 0
9084                    && signingKs != null) {
9085                // Optimization: reuse the existing cached certificates
9086                // if the package appears to be unchanged.
9087                pkg.mSignatures = ps.signatures.mSignatures;
9088                pkg.mSigningKeys = signingKs;
9089                return;
9090            }
9091
9092            Slog.w(TAG, "PackageSetting for " + ps.name
9093                    + " is missing signatures.  Collecting certs again to recover them.");
9094        } else {
9095            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
9096        }
9097
9098        try {
9099            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
9100            PackageParser.collectCertificates(pkg, policyFlags);
9101        } catch (PackageParserException e) {
9102            throw PackageManagerException.from(e);
9103        } finally {
9104            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9105        }
9106    }
9107
9108    /**
9109     *  Traces a package scan.
9110     *  @see #scanPackageLI(File, int, int, long, UserHandle)
9111     */
9112    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
9113            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
9114        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
9115        try {
9116            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
9117        } finally {
9118            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9119        }
9120    }
9121
9122    /**
9123     *  Scans a package and returns the newly parsed package.
9124     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
9125     */
9126    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
9127            long currentTime, UserHandle user) throws PackageManagerException {
9128        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
9129        PackageParser pp = new PackageParser();
9130        pp.setSeparateProcesses(mSeparateProcesses);
9131        pp.setOnlyCoreApps(mOnlyCore);
9132        pp.setDisplayMetrics(mMetrics);
9133        pp.setCallback(mPackageParserCallback);
9134
9135        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
9136            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
9137        }
9138
9139        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
9140        final PackageParser.Package pkg;
9141        try {
9142            pkg = pp.parsePackage(scanFile, parseFlags);
9143        } catch (PackageParserException e) {
9144            throw PackageManagerException.from(e);
9145        } finally {
9146            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9147        }
9148
9149        // Static shared libraries have synthetic package names
9150        if (pkg.applicationInfo.isStaticSharedLibrary()) {
9151            renameStaticSharedLibraryPackage(pkg);
9152        }
9153
9154        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
9155    }
9156
9157    /**
9158     *  Scans a package and returns the newly parsed package.
9159     *  @throws PackageManagerException on a parse error.
9160     */
9161    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
9162            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9163            throws PackageManagerException {
9164        // If the package has children and this is the first dive in the function
9165        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
9166        // packages (parent and children) would be successfully scanned before the
9167        // actual scan since scanning mutates internal state and we want to atomically
9168        // install the package and its children.
9169        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9170            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9171                scanFlags |= SCAN_CHECK_ONLY;
9172            }
9173        } else {
9174            scanFlags &= ~SCAN_CHECK_ONLY;
9175        }
9176
9177        // Scan the parent
9178        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
9179                scanFlags, currentTime, user);
9180
9181        // Scan the children
9182        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9183        for (int i = 0; i < childCount; i++) {
9184            PackageParser.Package childPackage = pkg.childPackages.get(i);
9185            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
9186                    currentTime, user);
9187        }
9188
9189
9190        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9191            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
9192        }
9193
9194        return scannedPkg;
9195    }
9196
9197    /**
9198     *  Scans a package and returns the newly parsed package.
9199     *  @throws PackageManagerException on a parse error.
9200     */
9201    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
9202            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9203            throws PackageManagerException {
9204        PackageSetting ps = null;
9205        PackageSetting updatedPkg;
9206        // reader
9207        synchronized (mPackages) {
9208            // Look to see if we already know about this package.
9209            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
9210            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
9211                // This package has been renamed to its original name.  Let's
9212                // use that.
9213                ps = mSettings.getPackageLPr(oldName);
9214            }
9215            // If there was no original package, see one for the real package name.
9216            if (ps == null) {
9217                ps = mSettings.getPackageLPr(pkg.packageName);
9218            }
9219            // Check to see if this package could be hiding/updating a system
9220            // package.  Must look for it either under the original or real
9221            // package name depending on our state.
9222            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
9223            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
9224
9225            // If this is a package we don't know about on the system partition, we
9226            // may need to remove disabled child packages on the system partition
9227            // or may need to not add child packages if the parent apk is updated
9228            // on the data partition and no longer defines this child package.
9229            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
9230                // If this is a parent package for an updated system app and this system
9231                // app got an OTA update which no longer defines some of the child packages
9232                // we have to prune them from the disabled system packages.
9233                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9234                if (disabledPs != null) {
9235                    final int scannedChildCount = (pkg.childPackages != null)
9236                            ? pkg.childPackages.size() : 0;
9237                    final int disabledChildCount = disabledPs.childPackageNames != null
9238                            ? disabledPs.childPackageNames.size() : 0;
9239                    for (int i = 0; i < disabledChildCount; i++) {
9240                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
9241                        boolean disabledPackageAvailable = false;
9242                        for (int j = 0; j < scannedChildCount; j++) {
9243                            PackageParser.Package childPkg = pkg.childPackages.get(j);
9244                            if (childPkg.packageName.equals(disabledChildPackageName)) {
9245                                disabledPackageAvailable = true;
9246                                break;
9247                            }
9248                         }
9249                         if (!disabledPackageAvailable) {
9250                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
9251                         }
9252                    }
9253                }
9254            }
9255        }
9256
9257        final boolean isUpdatedPkg = updatedPkg != null;
9258        final boolean isUpdatedSystemPkg = isUpdatedPkg
9259                && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0;
9260        boolean isUpdatedPkgBetter = false;
9261        // First check if this is a system package that may involve an update
9262        if (isUpdatedSystemPkg) {
9263            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
9264            // it needs to drop FLAG_PRIVILEGED.
9265            if (locationIsPrivileged(scanFile)) {
9266                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9267            } else {
9268                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9269            }
9270
9271            if (ps != null && !ps.codePath.equals(scanFile)) {
9272                // The path has changed from what was last scanned...  check the
9273                // version of the new path against what we have stored to determine
9274                // what to do.
9275                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
9276                if (pkg.mVersionCode <= ps.versionCode) {
9277                    // The system package has been updated and the code path does not match
9278                    // Ignore entry. Skip it.
9279                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
9280                            + " ignored: updated version " + ps.versionCode
9281                            + " better than this " + pkg.mVersionCode);
9282                    if (!updatedPkg.codePath.equals(scanFile)) {
9283                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
9284                                + ps.name + " changing from " + updatedPkg.codePathString
9285                                + " to " + scanFile);
9286                        updatedPkg.codePath = scanFile;
9287                        updatedPkg.codePathString = scanFile.toString();
9288                        updatedPkg.resourcePath = scanFile;
9289                        updatedPkg.resourcePathString = scanFile.toString();
9290                    }
9291                    updatedPkg.pkg = pkg;
9292                    updatedPkg.versionCode = pkg.mVersionCode;
9293
9294                    // Update the disabled system child packages to point to the package too.
9295                    final int childCount = updatedPkg.childPackageNames != null
9296                            ? updatedPkg.childPackageNames.size() : 0;
9297                    for (int i = 0; i < childCount; i++) {
9298                        String childPackageName = updatedPkg.childPackageNames.get(i);
9299                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
9300                                childPackageName);
9301                        if (updatedChildPkg != null) {
9302                            updatedChildPkg.pkg = pkg;
9303                            updatedChildPkg.versionCode = pkg.mVersionCode;
9304                        }
9305                    }
9306                } else {
9307                    // The current app on the system partition is better than
9308                    // what we have updated to on the data partition; switch
9309                    // back to the system partition version.
9310                    // At this point, its safely assumed that package installation for
9311                    // apps in system partition will go through. If not there won't be a working
9312                    // version of the app
9313                    // writer
9314                    synchronized (mPackages) {
9315                        // Just remove the loaded entries from package lists.
9316                        mPackages.remove(ps.name);
9317                    }
9318
9319                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9320                            + " reverting from " + ps.codePathString
9321                            + ": new version " + pkg.mVersionCode
9322                            + " better than installed " + ps.versionCode);
9323
9324                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9325                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9326                    synchronized (mInstallLock) {
9327                        args.cleanUpResourcesLI();
9328                    }
9329                    synchronized (mPackages) {
9330                        mSettings.enableSystemPackageLPw(ps.name);
9331                    }
9332                    isUpdatedPkgBetter = true;
9333                }
9334            }
9335        }
9336
9337        String resourcePath = null;
9338        String baseResourcePath = null;
9339        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) {
9340            if (ps != null && ps.resourcePathString != null) {
9341                resourcePath = ps.resourcePathString;
9342                baseResourcePath = ps.resourcePathString;
9343            } else {
9344                // Should not happen at all. Just log an error.
9345                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9346            }
9347        } else {
9348            resourcePath = pkg.codePath;
9349            baseResourcePath = pkg.baseCodePath;
9350        }
9351
9352        // Set application objects path explicitly.
9353        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9354        pkg.setApplicationInfoCodePath(pkg.codePath);
9355        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9356        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9357        pkg.setApplicationInfoResourcePath(resourcePath);
9358        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9359        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9360
9361        // throw an exception if we have an update to a system application, but, it's not more
9362        // recent than the package we've already scanned
9363        if (isUpdatedSystemPkg && !isUpdatedPkgBetter) {
9364            throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
9365                    + scanFile + " ignored: updated version " + ps.versionCode
9366                    + " better than this " + pkg.mVersionCode);
9367        }
9368
9369        if (isUpdatedPkg) {
9370            // An updated system app will not have the PARSE_IS_SYSTEM flag set
9371            // initially
9372            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
9373
9374            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
9375            // flag set initially
9376            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9377                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9378            }
9379        }
9380
9381        // Verify certificates against what was last scanned
9382        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
9383
9384        /*
9385         * A new system app appeared, but we already had a non-system one of the
9386         * same name installed earlier.
9387         */
9388        boolean shouldHideSystemApp = false;
9389        if (!isUpdatedPkg && ps != null
9390                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
9391            /*
9392             * Check to make sure the signatures match first. If they don't,
9393             * wipe the installed application and its data.
9394             */
9395            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
9396                    != PackageManager.SIGNATURE_MATCH) {
9397                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
9398                        + " signatures don't match existing userdata copy; removing");
9399                try (PackageFreezer freezer = freezePackage(pkg.packageName,
9400                        "scanPackageInternalLI")) {
9401                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9402                }
9403                ps = null;
9404            } else {
9405                /*
9406                 * If the newly-added system app is an older version than the
9407                 * already installed version, hide it. It will be scanned later
9408                 * and re-added like an update.
9409                 */
9410                if (pkg.mVersionCode <= ps.versionCode) {
9411                    shouldHideSystemApp = true;
9412                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9413                            + " but new version " + pkg.mVersionCode + " better than installed "
9414                            + ps.versionCode + "; hiding system");
9415                } else {
9416                    /*
9417                     * The newly found system app is a newer version that the
9418                     * one previously installed. Simply remove the
9419                     * already-installed application and replace it with our own
9420                     * while keeping the application data.
9421                     */
9422                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9423                            + " reverting from " + ps.codePathString + ": new version "
9424                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
9425                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9426                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9427                    synchronized (mInstallLock) {
9428                        args.cleanUpResourcesLI();
9429                    }
9430                }
9431            }
9432        }
9433
9434        // The apk is forward locked (not public) if its code and resources
9435        // are kept in different files. (except for app in either system or
9436        // vendor path).
9437        // TODO grab this value from PackageSettings
9438        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9439            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9440                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9441            }
9442        }
9443
9444        final int userId = ((user == null) ? 0 : user.getIdentifier());
9445        if (ps != null && ps.getInstantApp(userId)) {
9446            scanFlags |= SCAN_AS_INSTANT_APP;
9447        }
9448        if (ps != null && ps.getVirtulalPreload(userId)) {
9449            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
9450        }
9451
9452        // Note that we invoke the following method only if we are about to unpack an application
9453        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9454                | SCAN_UPDATE_SIGNATURE, currentTime, user);
9455
9456        /*
9457         * If the system app should be overridden by a previously installed
9458         * data, hide the system app now and let the /data/app scan pick it up
9459         * again.
9460         */
9461        if (shouldHideSystemApp) {
9462            synchronized (mPackages) {
9463                mSettings.disableSystemPackageLPw(pkg.packageName, true);
9464            }
9465        }
9466
9467        return scannedPkg;
9468    }
9469
9470    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9471        // Derive the new package synthetic package name
9472        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9473                + pkg.staticSharedLibVersion);
9474    }
9475
9476    private static String fixProcessName(String defProcessName,
9477            String processName) {
9478        if (processName == null) {
9479            return defProcessName;
9480        }
9481        return processName;
9482    }
9483
9484    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9485            throws PackageManagerException {
9486        if (pkgSetting.signatures.mSignatures != null) {
9487            // Already existing package. Make sure signatures match
9488            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9489                    == PackageManager.SIGNATURE_MATCH;
9490            if (!match) {
9491                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9492                        == PackageManager.SIGNATURE_MATCH;
9493            }
9494            if (!match) {
9495                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9496                        == PackageManager.SIGNATURE_MATCH;
9497            }
9498            if (!match) {
9499                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9500                        + pkg.packageName + " signatures do not match the "
9501                        + "previously installed version; ignoring!");
9502            }
9503        }
9504
9505        // Check for shared user signatures
9506        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9507            // Already existing package. Make sure signatures match
9508            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9509                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9510            if (!match) {
9511                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9512                        == PackageManager.SIGNATURE_MATCH;
9513            }
9514            if (!match) {
9515                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9516                        == PackageManager.SIGNATURE_MATCH;
9517            }
9518            if (!match) {
9519                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9520                        "Package " + pkg.packageName
9521                        + " has no signatures that match those in shared user "
9522                        + pkgSetting.sharedUser.name + "; ignoring!");
9523            }
9524        }
9525    }
9526
9527    /**
9528     * Enforces that only the system UID or root's UID can call a method exposed
9529     * via Binder.
9530     *
9531     * @param message used as message if SecurityException is thrown
9532     * @throws SecurityException if the caller is not system or root
9533     */
9534    private static final void enforceSystemOrRoot(String message) {
9535        final int uid = Binder.getCallingUid();
9536        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9537            throw new SecurityException(message);
9538        }
9539    }
9540
9541    @Override
9542    public void performFstrimIfNeeded() {
9543        enforceSystemOrRoot("Only the system can request fstrim");
9544
9545        // Before everything else, see whether we need to fstrim.
9546        try {
9547            IStorageManager sm = PackageHelper.getStorageManager();
9548            if (sm != null) {
9549                boolean doTrim = false;
9550                final long interval = android.provider.Settings.Global.getLong(
9551                        mContext.getContentResolver(),
9552                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9553                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9554                if (interval > 0) {
9555                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9556                    if (timeSinceLast > interval) {
9557                        doTrim = true;
9558                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9559                                + "; running immediately");
9560                    }
9561                }
9562                if (doTrim) {
9563                    final boolean dexOptDialogShown;
9564                    synchronized (mPackages) {
9565                        dexOptDialogShown = mDexOptDialogShown;
9566                    }
9567                    if (!isFirstBoot() && dexOptDialogShown) {
9568                        try {
9569                            ActivityManager.getService().showBootMessage(
9570                                    mContext.getResources().getString(
9571                                            R.string.android_upgrading_fstrim), true);
9572                        } catch (RemoteException e) {
9573                        }
9574                    }
9575                    sm.runMaintenance();
9576                }
9577            } else {
9578                Slog.e(TAG, "storageManager service unavailable!");
9579            }
9580        } catch (RemoteException e) {
9581            // Can't happen; StorageManagerService is local
9582        }
9583    }
9584
9585    @Override
9586    public void updatePackagesIfNeeded() {
9587        enforceSystemOrRoot("Only the system can request package update");
9588
9589        // We need to re-extract after an OTA.
9590        boolean causeUpgrade = isUpgrade();
9591
9592        // First boot or factory reset.
9593        // Note: we also handle devices that are upgrading to N right now as if it is their
9594        //       first boot, as they do not have profile data.
9595        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9596
9597        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9598        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9599
9600        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9601            return;
9602        }
9603
9604        List<PackageParser.Package> pkgs;
9605        synchronized (mPackages) {
9606            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9607        }
9608
9609        final long startTime = System.nanoTime();
9610        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9611                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
9612                    false /* bootComplete */);
9613
9614        final int elapsedTimeSeconds =
9615                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9616
9617        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9618        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9619        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9620        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9621        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9622    }
9623
9624    /*
9625     * Return the prebuilt profile path given a package base code path.
9626     */
9627    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
9628        return pkg.baseCodePath + ".prof";
9629    }
9630
9631    /**
9632     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9633     * containing statistics about the invocation. The array consists of three elements,
9634     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9635     * and {@code numberOfPackagesFailed}.
9636     */
9637    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9638            String compilerFilter, boolean bootComplete) {
9639
9640        int numberOfPackagesVisited = 0;
9641        int numberOfPackagesOptimized = 0;
9642        int numberOfPackagesSkipped = 0;
9643        int numberOfPackagesFailed = 0;
9644        final int numberOfPackagesToDexopt = pkgs.size();
9645
9646        for (PackageParser.Package pkg : pkgs) {
9647            numberOfPackagesVisited++;
9648
9649            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9650                // Copy over initial preopt profiles since we won't get any JIT samples for methods
9651                // that are already compiled.
9652                File profileFile = new File(getPrebuildProfilePath(pkg));
9653                // Copy profile if it exists.
9654                if (profileFile.exists()) {
9655                    try {
9656                        // We could also do this lazily before calling dexopt in
9657                        // PackageDexOptimizer to prevent this happening on first boot. The issue
9658                        // is that we don't have a good way to say "do this only once".
9659                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9660                                pkg.applicationInfo.uid, pkg.packageName)) {
9661                            Log.e(TAG, "Installer failed to copy system profile!");
9662                        }
9663                    } catch (Exception e) {
9664                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9665                                e);
9666                    }
9667                }
9668            }
9669
9670            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9671                if (DEBUG_DEXOPT) {
9672                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9673                }
9674                numberOfPackagesSkipped++;
9675                continue;
9676            }
9677
9678            if (DEBUG_DEXOPT) {
9679                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9680                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9681            }
9682
9683            if (showDialog) {
9684                try {
9685                    ActivityManager.getService().showBootMessage(
9686                            mContext.getResources().getString(R.string.android_upgrading_apk,
9687                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9688                } catch (RemoteException e) {
9689                }
9690                synchronized (mPackages) {
9691                    mDexOptDialogShown = true;
9692                }
9693            }
9694
9695            // If the OTA updates a system app which was previously preopted to a non-preopted state
9696            // the app might end up being verified at runtime. That's because by default the apps
9697            // are verify-profile but for preopted apps there's no profile.
9698            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
9699            // that before the OTA the app was preopted) the app gets compiled with a non-profile
9700            // filter (by default 'quicken').
9701            // Note that at this stage unused apps are already filtered.
9702            if (isSystemApp(pkg) &&
9703                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
9704                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
9705                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
9706            }
9707
9708            // checkProfiles is false to avoid merging profiles during boot which
9709            // might interfere with background compilation (b/28612421).
9710            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9711            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9712            // trade-off worth doing to save boot time work.
9713            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9714            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9715                    pkg.packageName,
9716                    compilerFilter,
9717                    dexoptFlags));
9718
9719            if (pkg.isSystemApp()) {
9720                // Only dexopt shared secondary dex files belonging to system apps to not slow down
9721                // too much boot after an OTA.
9722                int secondaryDexoptFlags = dexoptFlags |
9723                        DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9724                        DexoptOptions.DEXOPT_ONLY_SHARED_DEX;
9725                mDexManager.dexoptSecondaryDex(new DexoptOptions(
9726                        pkg.packageName,
9727                        compilerFilter,
9728                        secondaryDexoptFlags));
9729            }
9730
9731            // TODO(shubhamajmera): Record secondary dexopt stats.
9732            switch (primaryDexOptStaus) {
9733                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9734                    numberOfPackagesOptimized++;
9735                    break;
9736                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9737                    numberOfPackagesSkipped++;
9738                    break;
9739                case PackageDexOptimizer.DEX_OPT_FAILED:
9740                    numberOfPackagesFailed++;
9741                    break;
9742                default:
9743                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9744                    break;
9745            }
9746        }
9747
9748        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9749                numberOfPackagesFailed };
9750    }
9751
9752    @Override
9753    public void notifyPackageUse(String packageName, int reason) {
9754        synchronized (mPackages) {
9755            final int callingUid = Binder.getCallingUid();
9756            final int callingUserId = UserHandle.getUserId(callingUid);
9757            if (getInstantAppPackageName(callingUid) != null) {
9758                if (!isCallerSameApp(packageName, callingUid)) {
9759                    return;
9760                }
9761            } else {
9762                if (isInstantApp(packageName, callingUserId)) {
9763                    return;
9764                }
9765            }
9766            final PackageParser.Package p = mPackages.get(packageName);
9767            if (p == null) {
9768                return;
9769            }
9770            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9771        }
9772    }
9773
9774    @Override
9775    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9776            List<String> classPaths, String loaderIsa) {
9777        int userId = UserHandle.getCallingUserId();
9778        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9779        if (ai == null) {
9780            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9781                + loadingPackageName + ", user=" + userId);
9782            return;
9783        }
9784        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9785    }
9786
9787    @Override
9788    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9789            IDexModuleRegisterCallback callback) {
9790        int userId = UserHandle.getCallingUserId();
9791        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9792        DexManager.RegisterDexModuleResult result;
9793        if (ai == null) {
9794            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9795                     " calling user. package=" + packageName + ", user=" + userId);
9796            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9797        } else {
9798            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9799        }
9800
9801        if (callback != null) {
9802            mHandler.post(() -> {
9803                try {
9804                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9805                } catch (RemoteException e) {
9806                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9807                }
9808            });
9809        }
9810    }
9811
9812    /**
9813     * Ask the package manager to perform a dex-opt with the given compiler filter.
9814     *
9815     * Note: exposed only for the shell command to allow moving packages explicitly to a
9816     *       definite state.
9817     */
9818    @Override
9819    public boolean performDexOptMode(String packageName,
9820            boolean checkProfiles, String targetCompilerFilter, boolean force,
9821            boolean bootComplete, String splitName) {
9822        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9823                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9824                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9825        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
9826                splitName, flags));
9827    }
9828
9829    /**
9830     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9831     * secondary dex files belonging to the given package.
9832     *
9833     * Note: exposed only for the shell command to allow moving packages explicitly to a
9834     *       definite state.
9835     */
9836    @Override
9837    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9838            boolean force) {
9839        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9840                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9841                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9842                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9843        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9844    }
9845
9846    /*package*/ boolean performDexOpt(DexoptOptions options) {
9847        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9848            return false;
9849        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9850            return false;
9851        }
9852
9853        if (options.isDexoptOnlySecondaryDex()) {
9854            return mDexManager.dexoptSecondaryDex(options);
9855        } else {
9856            int dexoptStatus = performDexOptWithStatus(options);
9857            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9858        }
9859    }
9860
9861    /**
9862     * Perform dexopt on the given package and return one of following result:
9863     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9864     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9865     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9866     */
9867    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9868        return performDexOptTraced(options);
9869    }
9870
9871    private int performDexOptTraced(DexoptOptions options) {
9872        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9873        try {
9874            return performDexOptInternal(options);
9875        } finally {
9876            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9877        }
9878    }
9879
9880    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9881    // if the package can now be considered up to date for the given filter.
9882    private int performDexOptInternal(DexoptOptions options) {
9883        PackageParser.Package p;
9884        synchronized (mPackages) {
9885            p = mPackages.get(options.getPackageName());
9886            if (p == null) {
9887                // Package could not be found. Report failure.
9888                return PackageDexOptimizer.DEX_OPT_FAILED;
9889            }
9890            mPackageUsage.maybeWriteAsync(mPackages);
9891            mCompilerStats.maybeWriteAsync();
9892        }
9893        long callingId = Binder.clearCallingIdentity();
9894        try {
9895            synchronized (mInstallLock) {
9896                return performDexOptInternalWithDependenciesLI(p, options);
9897            }
9898        } finally {
9899            Binder.restoreCallingIdentity(callingId);
9900        }
9901    }
9902
9903    public ArraySet<String> getOptimizablePackages() {
9904        ArraySet<String> pkgs = new ArraySet<String>();
9905        synchronized (mPackages) {
9906            for (PackageParser.Package p : mPackages.values()) {
9907                if (PackageDexOptimizer.canOptimizePackage(p)) {
9908                    pkgs.add(p.packageName);
9909                }
9910            }
9911        }
9912        return pkgs;
9913    }
9914
9915    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9916            DexoptOptions options) {
9917        // Select the dex optimizer based on the force parameter.
9918        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9919        //       allocate an object here.
9920        PackageDexOptimizer pdo = options.isForce()
9921                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9922                : mPackageDexOptimizer;
9923
9924        // Dexopt all dependencies first. Note: we ignore the return value and march on
9925        // on errors.
9926        // Note that we are going to call performDexOpt on those libraries as many times as
9927        // they are referenced in packages. When we do a batch of performDexOpt (for example
9928        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9929        // and the first package that uses the library will dexopt it. The
9930        // others will see that the compiled code for the library is up to date.
9931        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9932        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9933        if (!deps.isEmpty()) {
9934            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9935                    options.getCompilerFilter(), options.getSplitName(),
9936                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9937            for (PackageParser.Package depPackage : deps) {
9938                // TODO: Analyze and investigate if we (should) profile libraries.
9939                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9940                        getOrCreateCompilerPackageStats(depPackage),
9941                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9942            }
9943        }
9944        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9945                getOrCreateCompilerPackageStats(p),
9946                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9947    }
9948
9949    /**
9950     * Reconcile the information we have about the secondary dex files belonging to
9951     * {@code packagName} and the actual dex files. For all dex files that were
9952     * deleted, update the internal records and delete the generated oat files.
9953     */
9954    @Override
9955    public void reconcileSecondaryDexFiles(String packageName) {
9956        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9957            return;
9958        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9959            return;
9960        }
9961        mDexManager.reconcileSecondaryDexFiles(packageName);
9962    }
9963
9964    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9965    // a reference there.
9966    /*package*/ DexManager getDexManager() {
9967        return mDexManager;
9968    }
9969
9970    /**
9971     * Execute the background dexopt job immediately.
9972     */
9973    @Override
9974    public boolean runBackgroundDexoptJob() {
9975        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9976            return false;
9977        }
9978        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
9979    }
9980
9981    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9982        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9983                || p.usesStaticLibraries != null) {
9984            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9985            Set<String> collectedNames = new HashSet<>();
9986            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9987
9988            retValue.remove(p);
9989
9990            return retValue;
9991        } else {
9992            return Collections.emptyList();
9993        }
9994    }
9995
9996    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9997            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9998        if (!collectedNames.contains(p.packageName)) {
9999            collectedNames.add(p.packageName);
10000            collected.add(p);
10001
10002            if (p.usesLibraries != null) {
10003                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
10004                        null, collected, collectedNames);
10005            }
10006            if (p.usesOptionalLibraries != null) {
10007                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
10008                        null, collected, collectedNames);
10009            }
10010            if (p.usesStaticLibraries != null) {
10011                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
10012                        p.usesStaticLibrariesVersions, collected, collectedNames);
10013            }
10014        }
10015    }
10016
10017    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
10018            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
10019        final int libNameCount = libs.size();
10020        for (int i = 0; i < libNameCount; i++) {
10021            String libName = libs.get(i);
10022            int version = (versions != null && versions.length == libNameCount)
10023                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
10024            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
10025            if (libPkg != null) {
10026                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
10027            }
10028        }
10029    }
10030
10031    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
10032        synchronized (mPackages) {
10033            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
10034            if (libEntry != null) {
10035                return mPackages.get(libEntry.apk);
10036            }
10037            return null;
10038        }
10039    }
10040
10041    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
10042        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10043        if (versionedLib == null) {
10044            return null;
10045        }
10046        return versionedLib.get(version);
10047    }
10048
10049    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
10050        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10051                pkg.staticSharedLibName);
10052        if (versionedLib == null) {
10053            return null;
10054        }
10055        int previousLibVersion = -1;
10056        final int versionCount = versionedLib.size();
10057        for (int i = 0; i < versionCount; i++) {
10058            final int libVersion = versionedLib.keyAt(i);
10059            if (libVersion < pkg.staticSharedLibVersion) {
10060                previousLibVersion = Math.max(previousLibVersion, libVersion);
10061            }
10062        }
10063        if (previousLibVersion >= 0) {
10064            return versionedLib.get(previousLibVersion);
10065        }
10066        return null;
10067    }
10068
10069    public void shutdown() {
10070        mPackageUsage.writeNow(mPackages);
10071        mCompilerStats.writeNow();
10072        mDexManager.writePackageDexUsageNow();
10073    }
10074
10075    @Override
10076    public void dumpProfiles(String packageName) {
10077        PackageParser.Package pkg;
10078        synchronized (mPackages) {
10079            pkg = mPackages.get(packageName);
10080            if (pkg == null) {
10081                throw new IllegalArgumentException("Unknown package: " + packageName);
10082            }
10083        }
10084        /* Only the shell, root, or the app user should be able to dump profiles. */
10085        int callingUid = Binder.getCallingUid();
10086        if (callingUid != Process.SHELL_UID &&
10087            callingUid != Process.ROOT_UID &&
10088            callingUid != pkg.applicationInfo.uid) {
10089            throw new SecurityException("dumpProfiles");
10090        }
10091
10092        synchronized (mInstallLock) {
10093            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
10094            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
10095            try {
10096                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
10097                String codePaths = TextUtils.join(";", allCodePaths);
10098                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
10099            } catch (InstallerException e) {
10100                Slog.w(TAG, "Failed to dump profiles", e);
10101            }
10102            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10103        }
10104    }
10105
10106    @Override
10107    public void forceDexOpt(String packageName) {
10108        enforceSystemOrRoot("forceDexOpt");
10109
10110        PackageParser.Package pkg;
10111        synchronized (mPackages) {
10112            pkg = mPackages.get(packageName);
10113            if (pkg == null) {
10114                throw new IllegalArgumentException("Unknown package: " + packageName);
10115            }
10116        }
10117
10118        synchronized (mInstallLock) {
10119            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
10120
10121            // Whoever is calling forceDexOpt wants a compiled package.
10122            // Don't use profiles since that may cause compilation to be skipped.
10123            final int res = performDexOptInternalWithDependenciesLI(
10124                    pkg,
10125                    new DexoptOptions(packageName,
10126                            getDefaultCompilerFilter(),
10127                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
10128
10129            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10130            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
10131                throw new IllegalStateException("Failed to dexopt: " + res);
10132            }
10133        }
10134    }
10135
10136    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
10137        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
10138            Slog.w(TAG, "Unable to update from " + oldPkg.name
10139                    + " to " + newPkg.packageName
10140                    + ": old package not in system partition");
10141            return false;
10142        } else if (mPackages.get(oldPkg.name) != null) {
10143            Slog.w(TAG, "Unable to update from " + oldPkg.name
10144                    + " to " + newPkg.packageName
10145                    + ": old package still exists");
10146            return false;
10147        }
10148        return true;
10149    }
10150
10151    void removeCodePathLI(File codePath) {
10152        if (codePath.isDirectory()) {
10153            try {
10154                mInstaller.rmPackageDir(codePath.getAbsolutePath());
10155            } catch (InstallerException e) {
10156                Slog.w(TAG, "Failed to remove code path", e);
10157            }
10158        } else {
10159            codePath.delete();
10160        }
10161    }
10162
10163    private int[] resolveUserIds(int userId) {
10164        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
10165    }
10166
10167    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10168        if (pkg == null) {
10169            Slog.wtf(TAG, "Package was null!", new Throwable());
10170            return;
10171        }
10172        clearAppDataLeafLIF(pkg, userId, flags);
10173        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10174        for (int i = 0; i < childCount; i++) {
10175            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10176        }
10177    }
10178
10179    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10180        final PackageSetting ps;
10181        synchronized (mPackages) {
10182            ps = mSettings.mPackages.get(pkg.packageName);
10183        }
10184        for (int realUserId : resolveUserIds(userId)) {
10185            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10186            try {
10187                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10188                        ceDataInode);
10189            } catch (InstallerException e) {
10190                Slog.w(TAG, String.valueOf(e));
10191            }
10192        }
10193    }
10194
10195    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10196        if (pkg == null) {
10197            Slog.wtf(TAG, "Package was null!", new Throwable());
10198            return;
10199        }
10200        destroyAppDataLeafLIF(pkg, userId, flags);
10201        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10202        for (int i = 0; i < childCount; i++) {
10203            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10204        }
10205    }
10206
10207    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10208        final PackageSetting ps;
10209        synchronized (mPackages) {
10210            ps = mSettings.mPackages.get(pkg.packageName);
10211        }
10212        for (int realUserId : resolveUserIds(userId)) {
10213            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10214            try {
10215                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10216                        ceDataInode);
10217            } catch (InstallerException e) {
10218                Slog.w(TAG, String.valueOf(e));
10219            }
10220            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
10221        }
10222    }
10223
10224    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
10225        if (pkg == null) {
10226            Slog.wtf(TAG, "Package was null!", new Throwable());
10227            return;
10228        }
10229        destroyAppProfilesLeafLIF(pkg);
10230        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10231        for (int i = 0; i < childCount; i++) {
10232            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
10233        }
10234    }
10235
10236    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
10237        try {
10238            mInstaller.destroyAppProfiles(pkg.packageName);
10239        } catch (InstallerException e) {
10240            Slog.w(TAG, String.valueOf(e));
10241        }
10242    }
10243
10244    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
10245        if (pkg == null) {
10246            Slog.wtf(TAG, "Package was null!", new Throwable());
10247            return;
10248        }
10249        clearAppProfilesLeafLIF(pkg);
10250        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10251        for (int i = 0; i < childCount; i++) {
10252            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
10253        }
10254    }
10255
10256    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
10257        try {
10258            mInstaller.clearAppProfiles(pkg.packageName);
10259        } catch (InstallerException e) {
10260            Slog.w(TAG, String.valueOf(e));
10261        }
10262    }
10263
10264    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
10265            long lastUpdateTime) {
10266        // Set parent install/update time
10267        PackageSetting ps = (PackageSetting) pkg.mExtras;
10268        if (ps != null) {
10269            ps.firstInstallTime = firstInstallTime;
10270            ps.lastUpdateTime = lastUpdateTime;
10271        }
10272        // Set children install/update time
10273        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10274        for (int i = 0; i < childCount; i++) {
10275            PackageParser.Package childPkg = pkg.childPackages.get(i);
10276            ps = (PackageSetting) childPkg.mExtras;
10277            if (ps != null) {
10278                ps.firstInstallTime = firstInstallTime;
10279                ps.lastUpdateTime = lastUpdateTime;
10280            }
10281        }
10282    }
10283
10284    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
10285            PackageParser.Package changingLib) {
10286        if (file.path != null) {
10287            usesLibraryFiles.add(file.path);
10288            return;
10289        }
10290        PackageParser.Package p = mPackages.get(file.apk);
10291        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
10292            // If we are doing this while in the middle of updating a library apk,
10293            // then we need to make sure to use that new apk for determining the
10294            // dependencies here.  (We haven't yet finished committing the new apk
10295            // to the package manager state.)
10296            if (p == null || p.packageName.equals(changingLib.packageName)) {
10297                p = changingLib;
10298            }
10299        }
10300        if (p != null) {
10301            usesLibraryFiles.addAll(p.getAllCodePaths());
10302            if (p.usesLibraryFiles != null) {
10303                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
10304            }
10305        }
10306    }
10307
10308    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
10309            PackageParser.Package changingLib) throws PackageManagerException {
10310        if (pkg == null) {
10311            return;
10312        }
10313        ArraySet<String> usesLibraryFiles = null;
10314        if (pkg.usesLibraries != null) {
10315            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
10316                    null, null, pkg.packageName, changingLib, true, null);
10317        }
10318        if (pkg.usesStaticLibraries != null) {
10319            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
10320                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
10321                    pkg.packageName, changingLib, true, usesLibraryFiles);
10322        }
10323        if (pkg.usesOptionalLibraries != null) {
10324            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
10325                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
10326        }
10327        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
10328            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
10329        } else {
10330            pkg.usesLibraryFiles = null;
10331        }
10332    }
10333
10334    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
10335            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
10336            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
10337            boolean required, @Nullable ArraySet<String> outUsedLibraries)
10338            throws PackageManagerException {
10339        final int libCount = requestedLibraries.size();
10340        for (int i = 0; i < libCount; i++) {
10341            final String libName = requestedLibraries.get(i);
10342            final int libVersion = requiredVersions != null ? requiredVersions[i]
10343                    : SharedLibraryInfo.VERSION_UNDEFINED;
10344            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
10345            if (libEntry == null) {
10346                if (required) {
10347                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10348                            "Package " + packageName + " requires unavailable shared library "
10349                                    + libName + "; failing!");
10350                } else if (DEBUG_SHARED_LIBRARIES) {
10351                    Slog.i(TAG, "Package " + packageName
10352                            + " desires unavailable shared library "
10353                            + libName + "; ignoring!");
10354                }
10355            } else {
10356                if (requiredVersions != null && requiredCertDigests != null) {
10357                    if (libEntry.info.getVersion() != requiredVersions[i]) {
10358                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10359                            "Package " + packageName + " requires unavailable static shared"
10360                                    + " library " + libName + " version "
10361                                    + libEntry.info.getVersion() + "; failing!");
10362                    }
10363
10364                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
10365                    if (libPkg == null) {
10366                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10367                                "Package " + packageName + " requires unavailable static shared"
10368                                        + " library; failing!");
10369                    }
10370
10371                    String expectedCertDigest = requiredCertDigests[i];
10372                    String libCertDigest = PackageUtils.computeCertSha256Digest(
10373                                libPkg.mSignatures[0]);
10374                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
10375                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10376                                "Package " + packageName + " requires differently signed" +
10377                                        " static shared library; failing!");
10378                    }
10379                }
10380
10381                if (outUsedLibraries == null) {
10382                    outUsedLibraries = new ArraySet<>();
10383                }
10384                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
10385            }
10386        }
10387        return outUsedLibraries;
10388    }
10389
10390    private static boolean hasString(List<String> list, List<String> which) {
10391        if (list == null) {
10392            return false;
10393        }
10394        for (int i=list.size()-1; i>=0; i--) {
10395            for (int j=which.size()-1; j>=0; j--) {
10396                if (which.get(j).equals(list.get(i))) {
10397                    return true;
10398                }
10399            }
10400        }
10401        return false;
10402    }
10403
10404    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
10405            PackageParser.Package changingPkg) {
10406        ArrayList<PackageParser.Package> res = null;
10407        for (PackageParser.Package pkg : mPackages.values()) {
10408            if (changingPkg != null
10409                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
10410                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
10411                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
10412                            changingPkg.staticSharedLibName)) {
10413                return null;
10414            }
10415            if (res == null) {
10416                res = new ArrayList<>();
10417            }
10418            res.add(pkg);
10419            try {
10420                updateSharedLibrariesLPr(pkg, changingPkg);
10421            } catch (PackageManagerException e) {
10422                // If a system app update or an app and a required lib missing we
10423                // delete the package and for updated system apps keep the data as
10424                // it is better for the user to reinstall than to be in an limbo
10425                // state. Also libs disappearing under an app should never happen
10426                // - just in case.
10427                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
10428                    final int flags = pkg.isUpdatedSystemApp()
10429                            ? PackageManager.DELETE_KEEP_DATA : 0;
10430                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
10431                            flags , null, true, null);
10432                }
10433                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
10434            }
10435        }
10436        return res;
10437    }
10438
10439    /**
10440     * Derive the value of the {@code cpuAbiOverride} based on the provided
10441     * value and an optional stored value from the package settings.
10442     */
10443    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
10444        String cpuAbiOverride = null;
10445
10446        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10447            cpuAbiOverride = null;
10448        } else if (abiOverride != null) {
10449            cpuAbiOverride = abiOverride;
10450        } else if (settings != null) {
10451            cpuAbiOverride = settings.cpuAbiOverrideString;
10452        }
10453
10454        return cpuAbiOverride;
10455    }
10456
10457    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10458            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10459                    throws PackageManagerException {
10460        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10461        // If the package has children and this is the first dive in the function
10462        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10463        // whether all packages (parent and children) would be successfully scanned
10464        // before the actual scan since scanning mutates internal state and we want
10465        // to atomically install the package and its children.
10466        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10467            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10468                scanFlags |= SCAN_CHECK_ONLY;
10469            }
10470        } else {
10471            scanFlags &= ~SCAN_CHECK_ONLY;
10472        }
10473
10474        final PackageParser.Package scannedPkg;
10475        try {
10476            // Scan the parent
10477            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10478            // Scan the children
10479            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10480            for (int i = 0; i < childCount; i++) {
10481                PackageParser.Package childPkg = pkg.childPackages.get(i);
10482                scanPackageLI(childPkg, policyFlags,
10483                        scanFlags, currentTime, user);
10484            }
10485        } finally {
10486            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10487        }
10488
10489        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10490            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10491        }
10492
10493        return scannedPkg;
10494    }
10495
10496    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10497            int scanFlags, long currentTime, @Nullable UserHandle user)
10498                    throws PackageManagerException {
10499        boolean success = false;
10500        try {
10501            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10502                    currentTime, user);
10503            success = true;
10504            return res;
10505        } finally {
10506            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10507                // DELETE_DATA_ON_FAILURES is only used by frozen paths
10508                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10509                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10510                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10511            }
10512        }
10513    }
10514
10515    /**
10516     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10517     */
10518    private static boolean apkHasCode(String fileName) {
10519        StrictJarFile jarFile = null;
10520        try {
10521            jarFile = new StrictJarFile(fileName,
10522                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10523            return jarFile.findEntry("classes.dex") != null;
10524        } catch (IOException ignore) {
10525        } finally {
10526            try {
10527                if (jarFile != null) {
10528                    jarFile.close();
10529                }
10530            } catch (IOException ignore) {}
10531        }
10532        return false;
10533    }
10534
10535    /**
10536     * Enforces code policy for the package. This ensures that if an APK has
10537     * declared hasCode="true" in its manifest that the APK actually contains
10538     * code.
10539     *
10540     * @throws PackageManagerException If bytecode could not be found when it should exist
10541     */
10542    private static void assertCodePolicy(PackageParser.Package pkg)
10543            throws PackageManagerException {
10544        final boolean shouldHaveCode =
10545                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10546        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10547            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10548                    "Package " + pkg.baseCodePath + " code is missing");
10549        }
10550
10551        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10552            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10553                final boolean splitShouldHaveCode =
10554                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10555                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10556                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10557                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10558                }
10559            }
10560        }
10561    }
10562
10563    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10564            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10565                    throws PackageManagerException {
10566        if (DEBUG_PACKAGE_SCANNING) {
10567            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10568                Log.d(TAG, "Scanning package " + pkg.packageName);
10569        }
10570
10571        applyPolicy(pkg, policyFlags);
10572
10573        assertPackageIsValid(pkg, policyFlags, scanFlags);
10574
10575        // Initialize package source and resource directories
10576        final File scanFile = new File(pkg.codePath);
10577        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10578        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10579
10580        SharedUserSetting suid = null;
10581        PackageSetting pkgSetting = null;
10582
10583        // Getting the package setting may have a side-effect, so if we
10584        // are only checking if scan would succeed, stash a copy of the
10585        // old setting to restore at the end.
10586        PackageSetting nonMutatedPs = null;
10587
10588        // We keep references to the derived CPU Abis from settings in oder to reuse
10589        // them in the case where we're not upgrading or booting for the first time.
10590        String primaryCpuAbiFromSettings = null;
10591        String secondaryCpuAbiFromSettings = null;
10592
10593        // writer
10594        synchronized (mPackages) {
10595            if (pkg.mSharedUserId != null) {
10596                // SIDE EFFECTS; may potentially allocate a new shared user
10597                suid = mSettings.getSharedUserLPw(
10598                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10599                if (DEBUG_PACKAGE_SCANNING) {
10600                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10601                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10602                                + "): packages=" + suid.packages);
10603                }
10604            }
10605
10606            // Check if we are renaming from an original package name.
10607            PackageSetting origPackage = null;
10608            String realName = null;
10609            if (pkg.mOriginalPackages != null) {
10610                // This package may need to be renamed to a previously
10611                // installed name.  Let's check on that...
10612                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10613                if (pkg.mOriginalPackages.contains(renamed)) {
10614                    // This package had originally been installed as the
10615                    // original name, and we have already taken care of
10616                    // transitioning to the new one.  Just update the new
10617                    // one to continue using the old name.
10618                    realName = pkg.mRealPackage;
10619                    if (!pkg.packageName.equals(renamed)) {
10620                        // Callers into this function may have already taken
10621                        // care of renaming the package; only do it here if
10622                        // it is not already done.
10623                        pkg.setPackageName(renamed);
10624                    }
10625                } else {
10626                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10627                        if ((origPackage = mSettings.getPackageLPr(
10628                                pkg.mOriginalPackages.get(i))) != null) {
10629                            // We do have the package already installed under its
10630                            // original name...  should we use it?
10631                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10632                                // New package is not compatible with original.
10633                                origPackage = null;
10634                                continue;
10635                            } else if (origPackage.sharedUser != null) {
10636                                // Make sure uid is compatible between packages.
10637                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10638                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10639                                            + " to " + pkg.packageName + ": old uid "
10640                                            + origPackage.sharedUser.name
10641                                            + " differs from " + pkg.mSharedUserId);
10642                                    origPackage = null;
10643                                    continue;
10644                                }
10645                                // TODO: Add case when shared user id is added [b/28144775]
10646                            } else {
10647                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10648                                        + pkg.packageName + " to old name " + origPackage.name);
10649                            }
10650                            break;
10651                        }
10652                    }
10653                }
10654            }
10655
10656            if (mTransferedPackages.contains(pkg.packageName)) {
10657                Slog.w(TAG, "Package " + pkg.packageName
10658                        + " was transferred to another, but its .apk remains");
10659            }
10660
10661            // See comments in nonMutatedPs declaration
10662            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10663                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10664                if (foundPs != null) {
10665                    nonMutatedPs = new PackageSetting(foundPs);
10666                }
10667            }
10668
10669            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10670                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10671                if (foundPs != null) {
10672                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10673                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10674                }
10675            }
10676
10677            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10678            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10679                PackageManagerService.reportSettingsProblem(Log.WARN,
10680                        "Package " + pkg.packageName + " shared user changed from "
10681                                + (pkgSetting.sharedUser != null
10682                                        ? pkgSetting.sharedUser.name : "<nothing>")
10683                                + " to "
10684                                + (suid != null ? suid.name : "<nothing>")
10685                                + "; replacing with new");
10686                pkgSetting = null;
10687            }
10688            final PackageSetting oldPkgSetting =
10689                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10690            final PackageSetting disabledPkgSetting =
10691                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10692
10693            String[] usesStaticLibraries = null;
10694            if (pkg.usesStaticLibraries != null) {
10695                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10696                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10697            }
10698
10699            if (pkgSetting == null) {
10700                final String parentPackageName = (pkg.parentPackage != null)
10701                        ? pkg.parentPackage.packageName : null;
10702                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10703                final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10704                // REMOVE SharedUserSetting from method; update in a separate call
10705                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10706                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10707                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10708                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10709                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10710                        true /*allowInstall*/, instantApp, virtualPreload,
10711                        parentPackageName, pkg.getChildPackageNames(),
10712                        UserManagerService.getInstance(), usesStaticLibraries,
10713                        pkg.usesStaticLibrariesVersions);
10714                // SIDE EFFECTS; updates system state; move elsewhere
10715                if (origPackage != null) {
10716                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10717                }
10718                mSettings.addUserToSettingLPw(pkgSetting);
10719            } else {
10720                // REMOVE SharedUserSetting from method; update in a separate call.
10721                //
10722                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10723                // secondaryCpuAbi are not known at this point so we always update them
10724                // to null here, only to reset them at a later point.
10725                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10726                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10727                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10728                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10729                        UserManagerService.getInstance(), usesStaticLibraries,
10730                        pkg.usesStaticLibrariesVersions);
10731            }
10732            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10733            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10734
10735            // SIDE EFFECTS; modifies system state; move elsewhere
10736            if (pkgSetting.origPackage != null) {
10737                // If we are first transitioning from an original package,
10738                // fix up the new package's name now.  We need to do this after
10739                // looking up the package under its new name, so getPackageLP
10740                // can take care of fiddling things correctly.
10741                pkg.setPackageName(origPackage.name);
10742
10743                // File a report about this.
10744                String msg = "New package " + pkgSetting.realName
10745                        + " renamed to replace old package " + pkgSetting.name;
10746                reportSettingsProblem(Log.WARN, msg);
10747
10748                // Make a note of it.
10749                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10750                    mTransferedPackages.add(origPackage.name);
10751                }
10752
10753                // No longer need to retain this.
10754                pkgSetting.origPackage = null;
10755            }
10756
10757            // SIDE EFFECTS; modifies system state; move elsewhere
10758            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10759                // Make a note of it.
10760                mTransferedPackages.add(pkg.packageName);
10761            }
10762
10763            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10764                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10765            }
10766
10767            if ((scanFlags & SCAN_BOOTING) == 0
10768                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10769                // Check all shared libraries and map to their actual file path.
10770                // We only do this here for apps not on a system dir, because those
10771                // are the only ones that can fail an install due to this.  We
10772                // will take care of the system apps by updating all of their
10773                // library paths after the scan is done. Also during the initial
10774                // scan don't update any libs as we do this wholesale after all
10775                // apps are scanned to avoid dependency based scanning.
10776                updateSharedLibrariesLPr(pkg, null);
10777            }
10778
10779            if (mFoundPolicyFile) {
10780                SELinuxMMAC.assignSeInfoValue(pkg);
10781            }
10782            pkg.applicationInfo.uid = pkgSetting.appId;
10783            pkg.mExtras = pkgSetting;
10784
10785
10786            // Static shared libs have same package with different versions where
10787            // we internally use a synthetic package name to allow multiple versions
10788            // of the same package, therefore we need to compare signatures against
10789            // the package setting for the latest library version.
10790            PackageSetting signatureCheckPs = pkgSetting;
10791            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10792                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10793                if (libraryEntry != null) {
10794                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10795                }
10796            }
10797
10798            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10799                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10800                    // We just determined the app is signed correctly, so bring
10801                    // over the latest parsed certs.
10802                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10803                } else {
10804                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10805                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10806                                "Package " + pkg.packageName + " upgrade keys do not match the "
10807                                + "previously installed version");
10808                    } else {
10809                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10810                        String msg = "System package " + pkg.packageName
10811                                + " signature changed; retaining data.";
10812                        reportSettingsProblem(Log.WARN, msg);
10813                    }
10814                }
10815            } else {
10816                try {
10817                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10818                    verifySignaturesLP(signatureCheckPs, pkg);
10819                    // We just determined the app is signed correctly, so bring
10820                    // over the latest parsed certs.
10821                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10822                } catch (PackageManagerException e) {
10823                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10824                        throw e;
10825                    }
10826                    // The signature has changed, but this package is in the system
10827                    // image...  let's recover!
10828                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10829                    // However...  if this package is part of a shared user, but it
10830                    // doesn't match the signature of the shared user, let's fail.
10831                    // What this means is that you can't change the signatures
10832                    // associated with an overall shared user, which doesn't seem all
10833                    // that unreasonable.
10834                    if (signatureCheckPs.sharedUser != null) {
10835                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10836                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10837                            throw new PackageManagerException(
10838                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10839                                    "Signature mismatch for shared user: "
10840                                            + pkgSetting.sharedUser);
10841                        }
10842                    }
10843                    // File a report about this.
10844                    String msg = "System package " + pkg.packageName
10845                            + " signature changed; retaining data.";
10846                    reportSettingsProblem(Log.WARN, msg);
10847                }
10848            }
10849
10850            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10851                // This package wants to adopt ownership of permissions from
10852                // another package.
10853                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10854                    final String origName = pkg.mAdoptPermissions.get(i);
10855                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10856                    if (orig != null) {
10857                        if (verifyPackageUpdateLPr(orig, pkg)) {
10858                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10859                                    + pkg.packageName);
10860                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10861                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
10862                        }
10863                    }
10864                }
10865            }
10866        }
10867
10868        pkg.applicationInfo.processName = fixProcessName(
10869                pkg.applicationInfo.packageName,
10870                pkg.applicationInfo.processName);
10871
10872        if (pkg != mPlatformPackage) {
10873            // Get all of our default paths setup
10874            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10875        }
10876
10877        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10878
10879        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10880            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10881                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10882                final boolean extractNativeLibs = !pkg.isLibrary();
10883                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
10884                        mAppLib32InstallDir);
10885                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10886
10887                // Some system apps still use directory structure for native libraries
10888                // in which case we might end up not detecting abi solely based on apk
10889                // structure. Try to detect abi based on directory structure.
10890                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10891                        pkg.applicationInfo.primaryCpuAbi == null) {
10892                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10893                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10894                }
10895            } else {
10896                // This is not a first boot or an upgrade, don't bother deriving the
10897                // ABI during the scan. Instead, trust the value that was stored in the
10898                // package setting.
10899                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10900                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10901
10902                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10903
10904                if (DEBUG_ABI_SELECTION) {
10905                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10906                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10907                        pkg.applicationInfo.secondaryCpuAbi);
10908                }
10909            }
10910        } else {
10911            if ((scanFlags & SCAN_MOVE) != 0) {
10912                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10913                // but we already have this packages package info in the PackageSetting. We just
10914                // use that and derive the native library path based on the new codepath.
10915                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10916                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10917            }
10918
10919            // Set native library paths again. For moves, the path will be updated based on the
10920            // ABIs we've determined above. For non-moves, the path will be updated based on the
10921            // ABIs we determined during compilation, but the path will depend on the final
10922            // package path (after the rename away from the stage path).
10923            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10924        }
10925
10926        // This is a special case for the "system" package, where the ABI is
10927        // dictated by the zygote configuration (and init.rc). We should keep track
10928        // of this ABI so that we can deal with "normal" applications that run under
10929        // the same UID correctly.
10930        if (mPlatformPackage == pkg) {
10931            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10932                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10933        }
10934
10935        // If there's a mismatch between the abi-override in the package setting
10936        // and the abiOverride specified for the install. Warn about this because we
10937        // would've already compiled the app without taking the package setting into
10938        // account.
10939        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10940            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10941                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10942                        " for package " + pkg.packageName);
10943            }
10944        }
10945
10946        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10947        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10948        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10949
10950        // Copy the derived override back to the parsed package, so that we can
10951        // update the package settings accordingly.
10952        pkg.cpuAbiOverride = cpuAbiOverride;
10953
10954        if (DEBUG_ABI_SELECTION) {
10955            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10956                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10957                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10958        }
10959
10960        // Push the derived path down into PackageSettings so we know what to
10961        // clean up at uninstall time.
10962        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10963
10964        if (DEBUG_ABI_SELECTION) {
10965            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10966                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10967                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10968        }
10969
10970        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
10971        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10972            // We don't do this here during boot because we can do it all
10973            // at once after scanning all existing packages.
10974            //
10975            // We also do this *before* we perform dexopt on this package, so that
10976            // we can avoid redundant dexopts, and also to make sure we've got the
10977            // code and package path correct.
10978            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10979        }
10980
10981        if (mFactoryTest && pkg.requestedPermissions.contains(
10982                android.Manifest.permission.FACTORY_TEST)) {
10983            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10984        }
10985
10986        if (isSystemApp(pkg)) {
10987            pkgSetting.isOrphaned = true;
10988        }
10989
10990        // Take care of first install / last update times.
10991        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
10992        if (currentTime != 0) {
10993            if (pkgSetting.firstInstallTime == 0) {
10994                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10995            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10996                pkgSetting.lastUpdateTime = currentTime;
10997            }
10998        } else if (pkgSetting.firstInstallTime == 0) {
10999            // We need *something*.  Take time time stamp of the file.
11000            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
11001        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
11002            if (scanFileTime != pkgSetting.timeStamp) {
11003                // A package on the system image has changed; consider this
11004                // to be an update.
11005                pkgSetting.lastUpdateTime = scanFileTime;
11006            }
11007        }
11008        pkgSetting.setTimeStamp(scanFileTime);
11009
11010        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
11011            if (nonMutatedPs != null) {
11012                synchronized (mPackages) {
11013                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
11014                }
11015            }
11016        } else {
11017            final int userId = user == null ? 0 : user.getIdentifier();
11018            // Modify state for the given package setting
11019            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
11020                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
11021            if (pkgSetting.getInstantApp(userId)) {
11022                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
11023            }
11024        }
11025        return pkg;
11026    }
11027
11028    /**
11029     * Applies policy to the parsed package based upon the given policy flags.
11030     * Ensures the package is in a good state.
11031     * <p>
11032     * Implementation detail: This method must NOT have any side effect. It would
11033     * ideally be static, but, it requires locks to read system state.
11034     */
11035    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
11036        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
11037            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
11038            if (pkg.applicationInfo.isDirectBootAware()) {
11039                // we're direct boot aware; set for all components
11040                for (PackageParser.Service s : pkg.services) {
11041                    s.info.encryptionAware = s.info.directBootAware = true;
11042                }
11043                for (PackageParser.Provider p : pkg.providers) {
11044                    p.info.encryptionAware = p.info.directBootAware = true;
11045                }
11046                for (PackageParser.Activity a : pkg.activities) {
11047                    a.info.encryptionAware = a.info.directBootAware = true;
11048                }
11049                for (PackageParser.Activity r : pkg.receivers) {
11050                    r.info.encryptionAware = r.info.directBootAware = true;
11051                }
11052            }
11053            if (compressedFileExists(pkg.baseCodePath)) {
11054                pkg.isStub = true;
11055            }
11056        } else {
11057            // Only allow system apps to be flagged as core apps.
11058            pkg.coreApp = false;
11059            // clear flags not applicable to regular apps
11060            pkg.applicationInfo.privateFlags &=
11061                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
11062            pkg.applicationInfo.privateFlags &=
11063                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
11064        }
11065        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
11066
11067        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
11068            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
11069        }
11070
11071        if (!isSystemApp(pkg)) {
11072            // Only system apps can use these features.
11073            pkg.mOriginalPackages = null;
11074            pkg.mRealPackage = null;
11075            pkg.mAdoptPermissions = null;
11076        }
11077    }
11078
11079    /**
11080     * Asserts the parsed package is valid according to the given policy. If the
11081     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
11082     * <p>
11083     * Implementation detail: This method must NOT have any side effects. It would
11084     * ideally be static, but, it requires locks to read system state.
11085     *
11086     * @throws PackageManagerException If the package fails any of the validation checks
11087     */
11088    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
11089            throws PackageManagerException {
11090        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
11091            assertCodePolicy(pkg);
11092        }
11093
11094        if (pkg.applicationInfo.getCodePath() == null ||
11095                pkg.applicationInfo.getResourcePath() == null) {
11096            // Bail out. The resource and code paths haven't been set.
11097            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
11098                    "Code and resource paths haven't been set correctly");
11099        }
11100
11101        // Make sure we're not adding any bogus keyset info
11102        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11103        ksms.assertScannedPackageValid(pkg);
11104
11105        synchronized (mPackages) {
11106            // The special "android" package can only be defined once
11107            if (pkg.packageName.equals("android")) {
11108                if (mAndroidApplication != null) {
11109                    Slog.w(TAG, "*************************************************");
11110                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
11111                    Slog.w(TAG, " codePath=" + pkg.codePath);
11112                    Slog.w(TAG, "*************************************************");
11113                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11114                            "Core android package being redefined.  Skipping.");
11115                }
11116            }
11117
11118            // A package name must be unique; don't allow duplicates
11119            if (mPackages.containsKey(pkg.packageName)) {
11120                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11121                        "Application package " + pkg.packageName
11122                        + " already installed.  Skipping duplicate.");
11123            }
11124
11125            if (pkg.applicationInfo.isStaticSharedLibrary()) {
11126                // Static libs have a synthetic package name containing the version
11127                // but we still want the base name to be unique.
11128                if (mPackages.containsKey(pkg.manifestPackageName)) {
11129                    throw new PackageManagerException(
11130                            "Duplicate static shared lib provider package");
11131                }
11132
11133                // Static shared libraries should have at least O target SDK
11134                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
11135                    throw new PackageManagerException(
11136                            "Packages declaring static-shared libs must target O SDK or higher");
11137                }
11138
11139                // Package declaring static a shared lib cannot be instant apps
11140                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11141                    throw new PackageManagerException(
11142                            "Packages declaring static-shared libs cannot be instant apps");
11143                }
11144
11145                // Package declaring static a shared lib cannot be renamed since the package
11146                // name is synthetic and apps can't code around package manager internals.
11147                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
11148                    throw new PackageManagerException(
11149                            "Packages declaring static-shared libs cannot be renamed");
11150                }
11151
11152                // Package declaring static a shared lib cannot declare child packages
11153                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
11154                    throw new PackageManagerException(
11155                            "Packages declaring static-shared libs cannot have child packages");
11156                }
11157
11158                // Package declaring static a shared lib cannot declare dynamic libs
11159                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
11160                    throw new PackageManagerException(
11161                            "Packages declaring static-shared libs cannot declare dynamic libs");
11162                }
11163
11164                // Package declaring static a shared lib cannot declare shared users
11165                if (pkg.mSharedUserId != null) {
11166                    throw new PackageManagerException(
11167                            "Packages declaring static-shared libs cannot declare shared users");
11168                }
11169
11170                // Static shared libs cannot declare activities
11171                if (!pkg.activities.isEmpty()) {
11172                    throw new PackageManagerException(
11173                            "Static shared libs cannot declare activities");
11174                }
11175
11176                // Static shared libs cannot declare services
11177                if (!pkg.services.isEmpty()) {
11178                    throw new PackageManagerException(
11179                            "Static shared libs cannot declare services");
11180                }
11181
11182                // Static shared libs cannot declare providers
11183                if (!pkg.providers.isEmpty()) {
11184                    throw new PackageManagerException(
11185                            "Static shared libs cannot declare content providers");
11186                }
11187
11188                // Static shared libs cannot declare receivers
11189                if (!pkg.receivers.isEmpty()) {
11190                    throw new PackageManagerException(
11191                            "Static shared libs cannot declare broadcast receivers");
11192                }
11193
11194                // Static shared libs cannot declare permission groups
11195                if (!pkg.permissionGroups.isEmpty()) {
11196                    throw new PackageManagerException(
11197                            "Static shared libs cannot declare permission groups");
11198                }
11199
11200                // Static shared libs cannot declare permissions
11201                if (!pkg.permissions.isEmpty()) {
11202                    throw new PackageManagerException(
11203                            "Static shared libs cannot declare permissions");
11204                }
11205
11206                // Static shared libs cannot declare protected broadcasts
11207                if (pkg.protectedBroadcasts != null) {
11208                    throw new PackageManagerException(
11209                            "Static shared libs cannot declare protected broadcasts");
11210                }
11211
11212                // Static shared libs cannot be overlay targets
11213                if (pkg.mOverlayTarget != null) {
11214                    throw new PackageManagerException(
11215                            "Static shared libs cannot be overlay targets");
11216                }
11217
11218                // The version codes must be ordered as lib versions
11219                int minVersionCode = Integer.MIN_VALUE;
11220                int maxVersionCode = Integer.MAX_VALUE;
11221
11222                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
11223                        pkg.staticSharedLibName);
11224                if (versionedLib != null) {
11225                    final int versionCount = versionedLib.size();
11226                    for (int i = 0; i < versionCount; i++) {
11227                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
11228                        final int libVersionCode = libInfo.getDeclaringPackage()
11229                                .getVersionCode();
11230                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
11231                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
11232                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
11233                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
11234                        } else {
11235                            minVersionCode = maxVersionCode = libVersionCode;
11236                            break;
11237                        }
11238                    }
11239                }
11240                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
11241                    throw new PackageManagerException("Static shared"
11242                            + " lib version codes must be ordered as lib versions");
11243                }
11244            }
11245
11246            // Only privileged apps and updated privileged apps can add child packages.
11247            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
11248                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
11249                    throw new PackageManagerException("Only privileged apps can add child "
11250                            + "packages. Ignoring package " + pkg.packageName);
11251                }
11252                final int childCount = pkg.childPackages.size();
11253                for (int i = 0; i < childCount; i++) {
11254                    PackageParser.Package childPkg = pkg.childPackages.get(i);
11255                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
11256                            childPkg.packageName)) {
11257                        throw new PackageManagerException("Can't override child of "
11258                                + "another disabled app. Ignoring package " + pkg.packageName);
11259                    }
11260                }
11261            }
11262
11263            // If we're only installing presumed-existing packages, require that the
11264            // scanned APK is both already known and at the path previously established
11265            // for it.  Previously unknown packages we pick up normally, but if we have an
11266            // a priori expectation about this package's install presence, enforce it.
11267            // With a singular exception for new system packages. When an OTA contains
11268            // a new system package, we allow the codepath to change from a system location
11269            // to the user-installed location. If we don't allow this change, any newer,
11270            // user-installed version of the application will be ignored.
11271            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
11272                if (mExpectingBetter.containsKey(pkg.packageName)) {
11273                    logCriticalInfo(Log.WARN,
11274                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
11275                } else {
11276                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
11277                    if (known != null) {
11278                        if (DEBUG_PACKAGE_SCANNING) {
11279                            Log.d(TAG, "Examining " + pkg.codePath
11280                                    + " and requiring known paths " + known.codePathString
11281                                    + " & " + known.resourcePathString);
11282                        }
11283                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
11284                                || !pkg.applicationInfo.getResourcePath().equals(
11285                                        known.resourcePathString)) {
11286                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
11287                                    "Application package " + pkg.packageName
11288                                    + " found at " + pkg.applicationInfo.getCodePath()
11289                                    + " but expected at " + known.codePathString
11290                                    + "; ignoring.");
11291                        }
11292                    }
11293                }
11294            }
11295
11296            // Verify that this new package doesn't have any content providers
11297            // that conflict with existing packages.  Only do this if the
11298            // package isn't already installed, since we don't want to break
11299            // things that are installed.
11300            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
11301                final int N = pkg.providers.size();
11302                int i;
11303                for (i=0; i<N; i++) {
11304                    PackageParser.Provider p = pkg.providers.get(i);
11305                    if (p.info.authority != null) {
11306                        String names[] = p.info.authority.split(";");
11307                        for (int j = 0; j < names.length; j++) {
11308                            if (mProvidersByAuthority.containsKey(names[j])) {
11309                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11310                                final String otherPackageName =
11311                                        ((other != null && other.getComponentName() != null) ?
11312                                                other.getComponentName().getPackageName() : "?");
11313                                throw new PackageManagerException(
11314                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11315                                        "Can't install because provider name " + names[j]
11316                                                + " (in package " + pkg.applicationInfo.packageName
11317                                                + ") is already used by " + otherPackageName);
11318                            }
11319                        }
11320                    }
11321                }
11322            }
11323        }
11324    }
11325
11326    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
11327            int type, String declaringPackageName, int declaringVersionCode) {
11328        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11329        if (versionedLib == null) {
11330            versionedLib = new SparseArray<>();
11331            mSharedLibraries.put(name, versionedLib);
11332            if (type == SharedLibraryInfo.TYPE_STATIC) {
11333                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11334            }
11335        } else if (versionedLib.indexOfKey(version) >= 0) {
11336            return false;
11337        }
11338        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11339                version, type, declaringPackageName, declaringVersionCode);
11340        versionedLib.put(version, libEntry);
11341        return true;
11342    }
11343
11344    private boolean removeSharedLibraryLPw(String name, int version) {
11345        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11346        if (versionedLib == null) {
11347            return false;
11348        }
11349        final int libIdx = versionedLib.indexOfKey(version);
11350        if (libIdx < 0) {
11351            return false;
11352        }
11353        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11354        versionedLib.remove(version);
11355        if (versionedLib.size() <= 0) {
11356            mSharedLibraries.remove(name);
11357            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11358                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11359                        .getPackageName());
11360            }
11361        }
11362        return true;
11363    }
11364
11365    /**
11366     * Adds a scanned package to the system. When this method is finished, the package will
11367     * be available for query, resolution, etc...
11368     */
11369    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11370            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
11371        final String pkgName = pkg.packageName;
11372        if (mCustomResolverComponentName != null &&
11373                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11374            setUpCustomResolverActivity(pkg);
11375        }
11376
11377        if (pkg.packageName.equals("android")) {
11378            synchronized (mPackages) {
11379                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11380                    // Set up information for our fall-back user intent resolution activity.
11381                    mPlatformPackage = pkg;
11382                    pkg.mVersionCode = mSdkVersion;
11383                    mAndroidApplication = pkg.applicationInfo;
11384                    if (!mResolverReplaced) {
11385                        mResolveActivity.applicationInfo = mAndroidApplication;
11386                        mResolveActivity.name = ResolverActivity.class.getName();
11387                        mResolveActivity.packageName = mAndroidApplication.packageName;
11388                        mResolveActivity.processName = "system:ui";
11389                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11390                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11391                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11392                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11393                        mResolveActivity.exported = true;
11394                        mResolveActivity.enabled = true;
11395                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11396                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11397                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11398                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11399                                | ActivityInfo.CONFIG_ORIENTATION
11400                                | ActivityInfo.CONFIG_KEYBOARD
11401                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11402                        mResolveInfo.activityInfo = mResolveActivity;
11403                        mResolveInfo.priority = 0;
11404                        mResolveInfo.preferredOrder = 0;
11405                        mResolveInfo.match = 0;
11406                        mResolveComponentName = new ComponentName(
11407                                mAndroidApplication.packageName, mResolveActivity.name);
11408                    }
11409                }
11410            }
11411        }
11412
11413        ArrayList<PackageParser.Package> clientLibPkgs = null;
11414        // writer
11415        synchronized (mPackages) {
11416            boolean hasStaticSharedLibs = false;
11417
11418            // Any app can add new static shared libraries
11419            if (pkg.staticSharedLibName != null) {
11420                // Static shared libs don't allow renaming as they have synthetic package
11421                // names to allow install of multiple versions, so use name from manifest.
11422                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11423                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11424                        pkg.manifestPackageName, pkg.mVersionCode)) {
11425                    hasStaticSharedLibs = true;
11426                } else {
11427                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11428                                + pkg.staticSharedLibName + " already exists; skipping");
11429                }
11430                // Static shared libs cannot be updated once installed since they
11431                // use synthetic package name which includes the version code, so
11432                // not need to update other packages's shared lib dependencies.
11433            }
11434
11435            if (!hasStaticSharedLibs
11436                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11437                // Only system apps can add new dynamic shared libraries.
11438                if (pkg.libraryNames != null) {
11439                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11440                        String name = pkg.libraryNames.get(i);
11441                        boolean allowed = false;
11442                        if (pkg.isUpdatedSystemApp()) {
11443                            // New library entries can only be added through the
11444                            // system image.  This is important to get rid of a lot
11445                            // of nasty edge cases: for example if we allowed a non-
11446                            // system update of the app to add a library, then uninstalling
11447                            // the update would make the library go away, and assumptions
11448                            // we made such as through app install filtering would now
11449                            // have allowed apps on the device which aren't compatible
11450                            // with it.  Better to just have the restriction here, be
11451                            // conservative, and create many fewer cases that can negatively
11452                            // impact the user experience.
11453                            final PackageSetting sysPs = mSettings
11454                                    .getDisabledSystemPkgLPr(pkg.packageName);
11455                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11456                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11457                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11458                                        allowed = true;
11459                                        break;
11460                                    }
11461                                }
11462                            }
11463                        } else {
11464                            allowed = true;
11465                        }
11466                        if (allowed) {
11467                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11468                                    SharedLibraryInfo.VERSION_UNDEFINED,
11469                                    SharedLibraryInfo.TYPE_DYNAMIC,
11470                                    pkg.packageName, pkg.mVersionCode)) {
11471                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11472                                        + name + " already exists; skipping");
11473                            }
11474                        } else {
11475                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11476                                    + name + " that is not declared on system image; skipping");
11477                        }
11478                    }
11479
11480                    if ((scanFlags & SCAN_BOOTING) == 0) {
11481                        // If we are not booting, we need to update any applications
11482                        // that are clients of our shared library.  If we are booting,
11483                        // this will all be done once the scan is complete.
11484                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11485                    }
11486                }
11487            }
11488        }
11489
11490        if ((scanFlags & SCAN_BOOTING) != 0) {
11491            // No apps can run during boot scan, so they don't need to be frozen
11492        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11493            // Caller asked to not kill app, so it's probably not frozen
11494        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11495            // Caller asked us to ignore frozen check for some reason; they
11496            // probably didn't know the package name
11497        } else {
11498            // We're doing major surgery on this package, so it better be frozen
11499            // right now to keep it from launching
11500            checkPackageFrozen(pkgName);
11501        }
11502
11503        // Also need to kill any apps that are dependent on the library.
11504        if (clientLibPkgs != null) {
11505            for (int i=0; i<clientLibPkgs.size(); i++) {
11506                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11507                killApplication(clientPkg.applicationInfo.packageName,
11508                        clientPkg.applicationInfo.uid, "update lib");
11509            }
11510        }
11511
11512        // writer
11513        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11514
11515        synchronized (mPackages) {
11516            // We don't expect installation to fail beyond this point
11517
11518            // Add the new setting to mSettings
11519            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11520            // Add the new setting to mPackages
11521            mPackages.put(pkg.applicationInfo.packageName, pkg);
11522            // Make sure we don't accidentally delete its data.
11523            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11524            while (iter.hasNext()) {
11525                PackageCleanItem item = iter.next();
11526                if (pkgName.equals(item.packageName)) {
11527                    iter.remove();
11528                }
11529            }
11530
11531            // Add the package's KeySets to the global KeySetManagerService
11532            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11533            ksms.addScannedPackageLPw(pkg);
11534
11535            int N = pkg.providers.size();
11536            StringBuilder r = null;
11537            int i;
11538            for (i=0; i<N; i++) {
11539                PackageParser.Provider p = pkg.providers.get(i);
11540                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11541                        p.info.processName);
11542                mProviders.addProvider(p);
11543                p.syncable = p.info.isSyncable;
11544                if (p.info.authority != null) {
11545                    String names[] = p.info.authority.split(";");
11546                    p.info.authority = null;
11547                    for (int j = 0; j < names.length; j++) {
11548                        if (j == 1 && p.syncable) {
11549                            // We only want the first authority for a provider to possibly be
11550                            // syncable, so if we already added this provider using a different
11551                            // authority clear the syncable flag. We copy the provider before
11552                            // changing it because the mProviders object contains a reference
11553                            // to a provider that we don't want to change.
11554                            // Only do this for the second authority since the resulting provider
11555                            // object can be the same for all future authorities for this provider.
11556                            p = new PackageParser.Provider(p);
11557                            p.syncable = false;
11558                        }
11559                        if (!mProvidersByAuthority.containsKey(names[j])) {
11560                            mProvidersByAuthority.put(names[j], p);
11561                            if (p.info.authority == null) {
11562                                p.info.authority = names[j];
11563                            } else {
11564                                p.info.authority = p.info.authority + ";" + names[j];
11565                            }
11566                            if (DEBUG_PACKAGE_SCANNING) {
11567                                if (chatty)
11568                                    Log.d(TAG, "Registered content provider: " + names[j]
11569                                            + ", className = " + p.info.name + ", isSyncable = "
11570                                            + p.info.isSyncable);
11571                            }
11572                        } else {
11573                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11574                            Slog.w(TAG, "Skipping provider name " + names[j] +
11575                                    " (in package " + pkg.applicationInfo.packageName +
11576                                    "): name already used by "
11577                                    + ((other != null && other.getComponentName() != null)
11578                                            ? other.getComponentName().getPackageName() : "?"));
11579                        }
11580                    }
11581                }
11582                if (chatty) {
11583                    if (r == null) {
11584                        r = new StringBuilder(256);
11585                    } else {
11586                        r.append(' ');
11587                    }
11588                    r.append(p.info.name);
11589                }
11590            }
11591            if (r != null) {
11592                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11593            }
11594
11595            N = pkg.services.size();
11596            r = null;
11597            for (i=0; i<N; i++) {
11598                PackageParser.Service s = pkg.services.get(i);
11599                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11600                        s.info.processName);
11601                mServices.addService(s);
11602                if (chatty) {
11603                    if (r == null) {
11604                        r = new StringBuilder(256);
11605                    } else {
11606                        r.append(' ');
11607                    }
11608                    r.append(s.info.name);
11609                }
11610            }
11611            if (r != null) {
11612                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11613            }
11614
11615            N = pkg.receivers.size();
11616            r = null;
11617            for (i=0; i<N; i++) {
11618                PackageParser.Activity a = pkg.receivers.get(i);
11619                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11620                        a.info.processName);
11621                mReceivers.addActivity(a, "receiver");
11622                if (chatty) {
11623                    if (r == null) {
11624                        r = new StringBuilder(256);
11625                    } else {
11626                        r.append(' ');
11627                    }
11628                    r.append(a.info.name);
11629                }
11630            }
11631            if (r != null) {
11632                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11633            }
11634
11635            N = pkg.activities.size();
11636            r = null;
11637            for (i=0; i<N; i++) {
11638                PackageParser.Activity a = pkg.activities.get(i);
11639                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11640                        a.info.processName);
11641                mActivities.addActivity(a, "activity");
11642                if (chatty) {
11643                    if (r == null) {
11644                        r = new StringBuilder(256);
11645                    } else {
11646                        r.append(' ');
11647                    }
11648                    r.append(a.info.name);
11649                }
11650            }
11651            if (r != null) {
11652                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11653            }
11654
11655            N = pkg.permissionGroups.size();
11656            r = null;
11657            for (i=0; i<N; i++) {
11658                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11659                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11660                final String curPackageName = cur == null ? null : cur.info.packageName;
11661                // Dont allow ephemeral apps to define new permission groups.
11662                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11663                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11664                            + pg.info.packageName
11665                            + " ignored: instant apps cannot define new permission groups.");
11666                    continue;
11667                }
11668                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11669                if (cur == null || isPackageUpdate) {
11670                    mPermissionGroups.put(pg.info.name, pg);
11671                    if (chatty) {
11672                        if (r == null) {
11673                            r = new StringBuilder(256);
11674                        } else {
11675                            r.append(' ');
11676                        }
11677                        if (isPackageUpdate) {
11678                            r.append("UPD:");
11679                        }
11680                        r.append(pg.info.name);
11681                    }
11682                } else {
11683                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11684                            + pg.info.packageName + " ignored: original from "
11685                            + cur.info.packageName);
11686                    if (chatty) {
11687                        if (r == null) {
11688                            r = new StringBuilder(256);
11689                        } else {
11690                            r.append(' ');
11691                        }
11692                        r.append("DUP:");
11693                        r.append(pg.info.name);
11694                    }
11695                }
11696            }
11697            if (r != null) {
11698                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11699            }
11700
11701            N = pkg.permissions.size();
11702            r = null;
11703            for (i=0; i<N; i++) {
11704                PackageParser.Permission p = pkg.permissions.get(i);
11705
11706                // Dont allow ephemeral apps to define new permissions.
11707                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11708                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11709                            + p.info.packageName
11710                            + " ignored: instant apps cannot define new permissions.");
11711                    continue;
11712                }
11713
11714                // Assume by default that we did not install this permission into the system.
11715                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11716
11717                // Now that permission groups have a special meaning, we ignore permission
11718                // groups for legacy apps to prevent unexpected behavior. In particular,
11719                // permissions for one app being granted to someone just because they happen
11720                // to be in a group defined by another app (before this had no implications).
11721                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11722                    p.group = mPermissionGroups.get(p.info.group);
11723                    // Warn for a permission in an unknown group.
11724                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11725                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11726                                + p.info.packageName + " in an unknown group " + p.info.group);
11727                    }
11728                }
11729
11730                ArrayMap<String, BasePermission> permissionMap =
11731                        p.tree ? mSettings.mPermissionTrees
11732                                : mSettings.mPermissions;
11733                BasePermission bp = permissionMap.get(p.info.name);
11734
11735                // Allow system apps to redefine non-system permissions
11736                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11737                    final boolean currentOwnerIsSystem = (bp.perm != null
11738                            && isSystemApp(bp.perm.owner));
11739                    if (isSystemApp(p.owner)) {
11740                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11741                            // It's a built-in permission and no owner, take ownership now
11742                            bp.packageSetting = pkgSetting;
11743                            bp.perm = p;
11744                            bp.uid = pkg.applicationInfo.uid;
11745                            bp.sourcePackage = p.info.packageName;
11746                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11747                        } else if (!currentOwnerIsSystem) {
11748                            String msg = "New decl " + p.owner + " of permission  "
11749                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
11750                            reportSettingsProblem(Log.WARN, msg);
11751                            bp = null;
11752                        }
11753                    }
11754                }
11755
11756                if (bp == null) {
11757                    bp = new BasePermission(p.info.name, p.info.packageName,
11758                            BasePermission.TYPE_NORMAL);
11759                    permissionMap.put(p.info.name, bp);
11760                }
11761
11762                if (bp.perm == null) {
11763                    if (bp.sourcePackage == null
11764                            || bp.sourcePackage.equals(p.info.packageName)) {
11765                        BasePermission tree = findPermissionTreeLP(p.info.name);
11766                        if (tree == null
11767                                || tree.sourcePackage.equals(p.info.packageName)) {
11768                            bp.packageSetting = pkgSetting;
11769                            bp.perm = p;
11770                            bp.uid = pkg.applicationInfo.uid;
11771                            bp.sourcePackage = p.info.packageName;
11772                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11773                            if (chatty) {
11774                                if (r == null) {
11775                                    r = new StringBuilder(256);
11776                                } else {
11777                                    r.append(' ');
11778                                }
11779                                r.append(p.info.name);
11780                            }
11781                        } else {
11782                            Slog.w(TAG, "Permission " + p.info.name + " from package "
11783                                    + p.info.packageName + " ignored: base tree "
11784                                    + tree.name + " is from package "
11785                                    + tree.sourcePackage);
11786                        }
11787                    } else {
11788                        Slog.w(TAG, "Permission " + p.info.name + " from package "
11789                                + p.info.packageName + " ignored: original from "
11790                                + bp.sourcePackage);
11791                    }
11792                } else if (chatty) {
11793                    if (r == null) {
11794                        r = new StringBuilder(256);
11795                    } else {
11796                        r.append(' ');
11797                    }
11798                    r.append("DUP:");
11799                    r.append(p.info.name);
11800                }
11801                if (bp.perm == p) {
11802                    bp.protectionLevel = p.info.protectionLevel;
11803                }
11804            }
11805
11806            if (r != null) {
11807                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
11808            }
11809
11810            N = pkg.instrumentation.size();
11811            r = null;
11812            for (i=0; i<N; i++) {
11813                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11814                a.info.packageName = pkg.applicationInfo.packageName;
11815                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11816                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11817                a.info.splitNames = pkg.splitNames;
11818                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11819                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11820                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11821                a.info.dataDir = pkg.applicationInfo.dataDir;
11822                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11823                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11824                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11825                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11826                mInstrumentation.put(a.getComponentName(), a);
11827                if (chatty) {
11828                    if (r == null) {
11829                        r = new StringBuilder(256);
11830                    } else {
11831                        r.append(' ');
11832                    }
11833                    r.append(a.info.name);
11834                }
11835            }
11836            if (r != null) {
11837                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11838            }
11839
11840            if (pkg.protectedBroadcasts != null) {
11841                N = pkg.protectedBroadcasts.size();
11842                synchronized (mProtectedBroadcasts) {
11843                    for (i = 0; i < N; i++) {
11844                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11845                    }
11846                }
11847            }
11848        }
11849
11850        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11851    }
11852
11853    /**
11854     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11855     * is derived purely on the basis of the contents of {@code scanFile} and
11856     * {@code cpuAbiOverride}.
11857     *
11858     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11859     */
11860    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11861                                 String cpuAbiOverride, boolean extractLibs,
11862                                 File appLib32InstallDir)
11863            throws PackageManagerException {
11864        // Give ourselves some initial paths; we'll come back for another
11865        // pass once we've determined ABI below.
11866        setNativeLibraryPaths(pkg, appLib32InstallDir);
11867
11868        // We would never need to extract libs for forward-locked and external packages,
11869        // since the container service will do it for us. We shouldn't attempt to
11870        // extract libs from system app when it was not updated.
11871        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11872                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11873            extractLibs = false;
11874        }
11875
11876        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11877        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11878
11879        NativeLibraryHelper.Handle handle = null;
11880        try {
11881            handle = NativeLibraryHelper.Handle.create(pkg);
11882            // TODO(multiArch): This can be null for apps that didn't go through the
11883            // usual installation process. We can calculate it again, like we
11884            // do during install time.
11885            //
11886            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11887            // unnecessary.
11888            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11889
11890            // Null out the abis so that they can be recalculated.
11891            pkg.applicationInfo.primaryCpuAbi = null;
11892            pkg.applicationInfo.secondaryCpuAbi = null;
11893            if (isMultiArch(pkg.applicationInfo)) {
11894                // Warn if we've set an abiOverride for multi-lib packages..
11895                // By definition, we need to copy both 32 and 64 bit libraries for
11896                // such packages.
11897                if (pkg.cpuAbiOverride != null
11898                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11899                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11900                }
11901
11902                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11903                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11904                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11905                    if (extractLibs) {
11906                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11907                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11908                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11909                                useIsaSpecificSubdirs);
11910                    } else {
11911                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11912                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11913                    }
11914                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11915                }
11916
11917                // Shared library native code should be in the APK zip aligned
11918                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11919                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11920                            "Shared library native lib extraction not supported");
11921                }
11922
11923                maybeThrowExceptionForMultiArchCopy(
11924                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11925
11926                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11927                    if (extractLibs) {
11928                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11929                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11930                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11931                                useIsaSpecificSubdirs);
11932                    } else {
11933                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11934                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11935                    }
11936                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11937                }
11938
11939                maybeThrowExceptionForMultiArchCopy(
11940                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11941
11942                if (abi64 >= 0) {
11943                    // Shared library native libs should be in the APK zip aligned
11944                    if (extractLibs && pkg.isLibrary()) {
11945                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11946                                "Shared library native lib extraction not supported");
11947                    }
11948                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11949                }
11950
11951                if (abi32 >= 0) {
11952                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11953                    if (abi64 >= 0) {
11954                        if (pkg.use32bitAbi) {
11955                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11956                            pkg.applicationInfo.primaryCpuAbi = abi;
11957                        } else {
11958                            pkg.applicationInfo.secondaryCpuAbi = abi;
11959                        }
11960                    } else {
11961                        pkg.applicationInfo.primaryCpuAbi = abi;
11962                    }
11963                }
11964            } else {
11965                String[] abiList = (cpuAbiOverride != null) ?
11966                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11967
11968                // Enable gross and lame hacks for apps that are built with old
11969                // SDK tools. We must scan their APKs for renderscript bitcode and
11970                // not launch them if it's present. Don't bother checking on devices
11971                // that don't have 64 bit support.
11972                boolean needsRenderScriptOverride = false;
11973                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11974                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11975                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11976                    needsRenderScriptOverride = true;
11977                }
11978
11979                final int copyRet;
11980                if (extractLibs) {
11981                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11982                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11983                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11984                } else {
11985                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11986                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11987                }
11988                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11989
11990                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11991                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11992                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11993                }
11994
11995                if (copyRet >= 0) {
11996                    // Shared libraries that have native libs must be multi-architecture
11997                    if (pkg.isLibrary()) {
11998                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11999                                "Shared library with native libs must be multiarch");
12000                    }
12001                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
12002                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
12003                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
12004                } else if (needsRenderScriptOverride) {
12005                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
12006                }
12007            }
12008        } catch (IOException ioe) {
12009            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
12010        } finally {
12011            IoUtils.closeQuietly(handle);
12012        }
12013
12014        // Now that we've calculated the ABIs and determined if it's an internal app,
12015        // we will go ahead and populate the nativeLibraryPath.
12016        setNativeLibraryPaths(pkg, appLib32InstallDir);
12017    }
12018
12019    /**
12020     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
12021     * i.e, so that all packages can be run inside a single process if required.
12022     *
12023     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
12024     * this function will either try and make the ABI for all packages in {@code packagesForUser}
12025     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
12026     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
12027     * updating a package that belongs to a shared user.
12028     *
12029     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
12030     * adds unnecessary complexity.
12031     */
12032    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
12033            PackageParser.Package scannedPackage) {
12034        String requiredInstructionSet = null;
12035        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
12036            requiredInstructionSet = VMRuntime.getInstructionSet(
12037                     scannedPackage.applicationInfo.primaryCpuAbi);
12038        }
12039
12040        PackageSetting requirer = null;
12041        for (PackageSetting ps : packagesForUser) {
12042            // If packagesForUser contains scannedPackage, we skip it. This will happen
12043            // when scannedPackage is an update of an existing package. Without this check,
12044            // we will never be able to change the ABI of any package belonging to a shared
12045            // user, even if it's compatible with other packages.
12046            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
12047                if (ps.primaryCpuAbiString == null) {
12048                    continue;
12049                }
12050
12051                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
12052                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
12053                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
12054                    // this but there's not much we can do.
12055                    String errorMessage = "Instruction set mismatch, "
12056                            + ((requirer == null) ? "[caller]" : requirer)
12057                            + " requires " + requiredInstructionSet + " whereas " + ps
12058                            + " requires " + instructionSet;
12059                    Slog.w(TAG, errorMessage);
12060                }
12061
12062                if (requiredInstructionSet == null) {
12063                    requiredInstructionSet = instructionSet;
12064                    requirer = ps;
12065                }
12066            }
12067        }
12068
12069        if (requiredInstructionSet != null) {
12070            String adjustedAbi;
12071            if (requirer != null) {
12072                // requirer != null implies that either scannedPackage was null or that scannedPackage
12073                // did not require an ABI, in which case we have to adjust scannedPackage to match
12074                // the ABI of the set (which is the same as requirer's ABI)
12075                adjustedAbi = requirer.primaryCpuAbiString;
12076                if (scannedPackage != null) {
12077                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
12078                }
12079            } else {
12080                // requirer == null implies that we're updating all ABIs in the set to
12081                // match scannedPackage.
12082                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
12083            }
12084
12085            for (PackageSetting ps : packagesForUser) {
12086                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
12087                    if (ps.primaryCpuAbiString != null) {
12088                        continue;
12089                    }
12090
12091                    ps.primaryCpuAbiString = adjustedAbi;
12092                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
12093                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
12094                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
12095                        if (DEBUG_ABI_SELECTION) {
12096                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
12097                                    + " (requirer="
12098                                    + (requirer != null ? requirer.pkg : "null")
12099                                    + ", scannedPackage="
12100                                    + (scannedPackage != null ? scannedPackage : "null")
12101                                    + ")");
12102                        }
12103                        try {
12104                            mInstaller.rmdex(ps.codePathString,
12105                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
12106                        } catch (InstallerException ignored) {
12107                        }
12108                    }
12109                }
12110            }
12111        }
12112    }
12113
12114    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
12115        synchronized (mPackages) {
12116            mResolverReplaced = true;
12117            // Set up information for custom user intent resolution activity.
12118            mResolveActivity.applicationInfo = pkg.applicationInfo;
12119            mResolveActivity.name = mCustomResolverComponentName.getClassName();
12120            mResolveActivity.packageName = pkg.applicationInfo.packageName;
12121            mResolveActivity.processName = pkg.applicationInfo.packageName;
12122            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
12123            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
12124                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12125            mResolveActivity.theme = 0;
12126            mResolveActivity.exported = true;
12127            mResolveActivity.enabled = true;
12128            mResolveInfo.activityInfo = mResolveActivity;
12129            mResolveInfo.priority = 0;
12130            mResolveInfo.preferredOrder = 0;
12131            mResolveInfo.match = 0;
12132            mResolveComponentName = mCustomResolverComponentName;
12133            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
12134                    mResolveComponentName);
12135        }
12136    }
12137
12138    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
12139        if (installerActivity == null) {
12140            if (DEBUG_EPHEMERAL) {
12141                Slog.d(TAG, "Clear ephemeral installer activity");
12142            }
12143            mInstantAppInstallerActivity = null;
12144            return;
12145        }
12146
12147        if (DEBUG_EPHEMERAL) {
12148            Slog.d(TAG, "Set ephemeral installer activity: "
12149                    + installerActivity.getComponentName());
12150        }
12151        // Set up information for ephemeral installer activity
12152        mInstantAppInstallerActivity = installerActivity;
12153        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
12154                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12155        mInstantAppInstallerActivity.exported = true;
12156        mInstantAppInstallerActivity.enabled = true;
12157        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
12158        mInstantAppInstallerInfo.priority = 0;
12159        mInstantAppInstallerInfo.preferredOrder = 1;
12160        mInstantAppInstallerInfo.isDefault = true;
12161        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
12162                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
12163    }
12164
12165    private static String calculateBundledApkRoot(final String codePathString) {
12166        final File codePath = new File(codePathString);
12167        final File codeRoot;
12168        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
12169            codeRoot = Environment.getRootDirectory();
12170        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
12171            codeRoot = Environment.getOemDirectory();
12172        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
12173            codeRoot = Environment.getVendorDirectory();
12174        } else {
12175            // Unrecognized code path; take its top real segment as the apk root:
12176            // e.g. /something/app/blah.apk => /something
12177            try {
12178                File f = codePath.getCanonicalFile();
12179                File parent = f.getParentFile();    // non-null because codePath is a file
12180                File tmp;
12181                while ((tmp = parent.getParentFile()) != null) {
12182                    f = parent;
12183                    parent = tmp;
12184                }
12185                codeRoot = f;
12186                Slog.w(TAG, "Unrecognized code path "
12187                        + codePath + " - using " + codeRoot);
12188            } catch (IOException e) {
12189                // Can't canonicalize the code path -- shenanigans?
12190                Slog.w(TAG, "Can't canonicalize code path " + codePath);
12191                return Environment.getRootDirectory().getPath();
12192            }
12193        }
12194        return codeRoot.getPath();
12195    }
12196
12197    /**
12198     * Derive and set the location of native libraries for the given package,
12199     * which varies depending on where and how the package was installed.
12200     */
12201    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
12202        final ApplicationInfo info = pkg.applicationInfo;
12203        final String codePath = pkg.codePath;
12204        final File codeFile = new File(codePath);
12205        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
12206        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
12207
12208        info.nativeLibraryRootDir = null;
12209        info.nativeLibraryRootRequiresIsa = false;
12210        info.nativeLibraryDir = null;
12211        info.secondaryNativeLibraryDir = null;
12212
12213        if (isApkFile(codeFile)) {
12214            // Monolithic install
12215            if (bundledApp) {
12216                // If "/system/lib64/apkname" exists, assume that is the per-package
12217                // native library directory to use; otherwise use "/system/lib/apkname".
12218                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
12219                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
12220                        getPrimaryInstructionSet(info));
12221
12222                // This is a bundled system app so choose the path based on the ABI.
12223                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
12224                // is just the default path.
12225                final String apkName = deriveCodePathName(codePath);
12226                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
12227                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
12228                        apkName).getAbsolutePath();
12229
12230                if (info.secondaryCpuAbi != null) {
12231                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
12232                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
12233                            secondaryLibDir, apkName).getAbsolutePath();
12234                }
12235            } else if (asecApp) {
12236                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
12237                        .getAbsolutePath();
12238            } else {
12239                final String apkName = deriveCodePathName(codePath);
12240                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
12241                        .getAbsolutePath();
12242            }
12243
12244            info.nativeLibraryRootRequiresIsa = false;
12245            info.nativeLibraryDir = info.nativeLibraryRootDir;
12246        } else {
12247            // Cluster install
12248            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
12249            info.nativeLibraryRootRequiresIsa = true;
12250
12251            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
12252                    getPrimaryInstructionSet(info)).getAbsolutePath();
12253
12254            if (info.secondaryCpuAbi != null) {
12255                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
12256                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
12257            }
12258        }
12259    }
12260
12261    /**
12262     * Calculate the abis and roots for a bundled app. These can uniquely
12263     * be determined from the contents of the system partition, i.e whether
12264     * it contains 64 or 32 bit shared libraries etc. We do not validate any
12265     * of this information, and instead assume that the system was built
12266     * sensibly.
12267     */
12268    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
12269                                           PackageSetting pkgSetting) {
12270        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
12271
12272        // If "/system/lib64/apkname" exists, assume that is the per-package
12273        // native library directory to use; otherwise use "/system/lib/apkname".
12274        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
12275        setBundledAppAbi(pkg, apkRoot, apkName);
12276        // pkgSetting might be null during rescan following uninstall of updates
12277        // to a bundled app, so accommodate that possibility.  The settings in
12278        // that case will be established later from the parsed package.
12279        //
12280        // If the settings aren't null, sync them up with what we've just derived.
12281        // note that apkRoot isn't stored in the package settings.
12282        if (pkgSetting != null) {
12283            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
12284            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
12285        }
12286    }
12287
12288    /**
12289     * Deduces the ABI of a bundled app and sets the relevant fields on the
12290     * parsed pkg object.
12291     *
12292     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
12293     *        under which system libraries are installed.
12294     * @param apkName the name of the installed package.
12295     */
12296    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
12297        final File codeFile = new File(pkg.codePath);
12298
12299        final boolean has64BitLibs;
12300        final boolean has32BitLibs;
12301        if (isApkFile(codeFile)) {
12302            // Monolithic install
12303            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
12304            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
12305        } else {
12306            // Cluster install
12307            final File rootDir = new File(codeFile, LIB_DIR_NAME);
12308            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
12309                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
12310                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
12311                has64BitLibs = (new File(rootDir, isa)).exists();
12312            } else {
12313                has64BitLibs = false;
12314            }
12315            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
12316                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
12317                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
12318                has32BitLibs = (new File(rootDir, isa)).exists();
12319            } else {
12320                has32BitLibs = false;
12321            }
12322        }
12323
12324        if (has64BitLibs && !has32BitLibs) {
12325            // The package has 64 bit libs, but not 32 bit libs. Its primary
12326            // ABI should be 64 bit. We can safely assume here that the bundled
12327            // native libraries correspond to the most preferred ABI in the list.
12328
12329            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12330            pkg.applicationInfo.secondaryCpuAbi = null;
12331        } else if (has32BitLibs && !has64BitLibs) {
12332            // The package has 32 bit libs but not 64 bit libs. Its primary
12333            // ABI should be 32 bit.
12334
12335            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12336            pkg.applicationInfo.secondaryCpuAbi = null;
12337        } else if (has32BitLibs && has64BitLibs) {
12338            // The application has both 64 and 32 bit bundled libraries. We check
12339            // here that the app declares multiArch support, and warn if it doesn't.
12340            //
12341            // We will be lenient here and record both ABIs. The primary will be the
12342            // ABI that's higher on the list, i.e, a device that's configured to prefer
12343            // 64 bit apps will see a 64 bit primary ABI,
12344
12345            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
12346                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12347            }
12348
12349            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12350                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12351                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12352            } else {
12353                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12354                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12355            }
12356        } else {
12357            pkg.applicationInfo.primaryCpuAbi = null;
12358            pkg.applicationInfo.secondaryCpuAbi = null;
12359        }
12360    }
12361
12362    private void killApplication(String pkgName, int appId, String reason) {
12363        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12364    }
12365
12366    private void killApplication(String pkgName, int appId, int userId, String reason) {
12367        // Request the ActivityManager to kill the process(only for existing packages)
12368        // so that we do not end up in a confused state while the user is still using the older
12369        // version of the application while the new one gets installed.
12370        final long token = Binder.clearCallingIdentity();
12371        try {
12372            IActivityManager am = ActivityManager.getService();
12373            if (am != null) {
12374                try {
12375                    am.killApplication(pkgName, appId, userId, reason);
12376                } catch (RemoteException e) {
12377                }
12378            }
12379        } finally {
12380            Binder.restoreCallingIdentity(token);
12381        }
12382    }
12383
12384    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12385        // Remove the parent package setting
12386        PackageSetting ps = (PackageSetting) pkg.mExtras;
12387        if (ps != null) {
12388            removePackageLI(ps, chatty);
12389        }
12390        // Remove the child package setting
12391        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12392        for (int i = 0; i < childCount; i++) {
12393            PackageParser.Package childPkg = pkg.childPackages.get(i);
12394            ps = (PackageSetting) childPkg.mExtras;
12395            if (ps != null) {
12396                removePackageLI(ps, chatty);
12397            }
12398        }
12399    }
12400
12401    void removePackageLI(PackageSetting ps, boolean chatty) {
12402        if (DEBUG_INSTALL) {
12403            if (chatty)
12404                Log.d(TAG, "Removing package " + ps.name);
12405        }
12406
12407        // writer
12408        synchronized (mPackages) {
12409            mPackages.remove(ps.name);
12410            final PackageParser.Package pkg = ps.pkg;
12411            if (pkg != null) {
12412                cleanPackageDataStructuresLILPw(pkg, chatty);
12413            }
12414        }
12415    }
12416
12417    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12418        if (DEBUG_INSTALL) {
12419            if (chatty)
12420                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12421        }
12422
12423        // writer
12424        synchronized (mPackages) {
12425            // Remove the parent package
12426            mPackages.remove(pkg.applicationInfo.packageName);
12427            cleanPackageDataStructuresLILPw(pkg, chatty);
12428
12429            // Remove the child packages
12430            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12431            for (int i = 0; i < childCount; i++) {
12432                PackageParser.Package childPkg = pkg.childPackages.get(i);
12433                mPackages.remove(childPkg.applicationInfo.packageName);
12434                cleanPackageDataStructuresLILPw(childPkg, chatty);
12435            }
12436        }
12437    }
12438
12439    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12440        int N = pkg.providers.size();
12441        StringBuilder r = null;
12442        int i;
12443        for (i=0; i<N; i++) {
12444            PackageParser.Provider p = pkg.providers.get(i);
12445            mProviders.removeProvider(p);
12446            if (p.info.authority == null) {
12447
12448                /* There was another ContentProvider with this authority when
12449                 * this app was installed so this authority is null,
12450                 * Ignore it as we don't have to unregister the provider.
12451                 */
12452                continue;
12453            }
12454            String names[] = p.info.authority.split(";");
12455            for (int j = 0; j < names.length; j++) {
12456                if (mProvidersByAuthority.get(names[j]) == p) {
12457                    mProvidersByAuthority.remove(names[j]);
12458                    if (DEBUG_REMOVE) {
12459                        if (chatty)
12460                            Log.d(TAG, "Unregistered content provider: " + names[j]
12461                                    + ", className = " + p.info.name + ", isSyncable = "
12462                                    + p.info.isSyncable);
12463                    }
12464                }
12465            }
12466            if (DEBUG_REMOVE && chatty) {
12467                if (r == null) {
12468                    r = new StringBuilder(256);
12469                } else {
12470                    r.append(' ');
12471                }
12472                r.append(p.info.name);
12473            }
12474        }
12475        if (r != null) {
12476            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12477        }
12478
12479        N = pkg.services.size();
12480        r = null;
12481        for (i=0; i<N; i++) {
12482            PackageParser.Service s = pkg.services.get(i);
12483            mServices.removeService(s);
12484            if (chatty) {
12485                if (r == null) {
12486                    r = new StringBuilder(256);
12487                } else {
12488                    r.append(' ');
12489                }
12490                r.append(s.info.name);
12491            }
12492        }
12493        if (r != null) {
12494            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12495        }
12496
12497        N = pkg.receivers.size();
12498        r = null;
12499        for (i=0; i<N; i++) {
12500            PackageParser.Activity a = pkg.receivers.get(i);
12501            mReceivers.removeActivity(a, "receiver");
12502            if (DEBUG_REMOVE && chatty) {
12503                if (r == null) {
12504                    r = new StringBuilder(256);
12505                } else {
12506                    r.append(' ');
12507                }
12508                r.append(a.info.name);
12509            }
12510        }
12511        if (r != null) {
12512            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12513        }
12514
12515        N = pkg.activities.size();
12516        r = null;
12517        for (i=0; i<N; i++) {
12518            PackageParser.Activity a = pkg.activities.get(i);
12519            mActivities.removeActivity(a, "activity");
12520            if (DEBUG_REMOVE && chatty) {
12521                if (r == null) {
12522                    r = new StringBuilder(256);
12523                } else {
12524                    r.append(' ');
12525                }
12526                r.append(a.info.name);
12527            }
12528        }
12529        if (r != null) {
12530            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12531        }
12532
12533        N = pkg.permissions.size();
12534        r = null;
12535        for (i=0; i<N; i++) {
12536            PackageParser.Permission p = pkg.permissions.get(i);
12537            BasePermission bp = mSettings.mPermissions.get(p.info.name);
12538            if (bp == null) {
12539                bp = mSettings.mPermissionTrees.get(p.info.name);
12540            }
12541            if (bp != null && bp.perm == p) {
12542                bp.perm = null;
12543                if (DEBUG_REMOVE && chatty) {
12544                    if (r == null) {
12545                        r = new StringBuilder(256);
12546                    } else {
12547                        r.append(' ');
12548                    }
12549                    r.append(p.info.name);
12550                }
12551            }
12552            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12553                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12554                if (appOpPkgs != null) {
12555                    appOpPkgs.remove(pkg.packageName);
12556                }
12557            }
12558        }
12559        if (r != null) {
12560            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12561        }
12562
12563        N = pkg.requestedPermissions.size();
12564        r = null;
12565        for (i=0; i<N; i++) {
12566            String perm = pkg.requestedPermissions.get(i);
12567            BasePermission bp = mSettings.mPermissions.get(perm);
12568            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12569                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12570                if (appOpPkgs != null) {
12571                    appOpPkgs.remove(pkg.packageName);
12572                    if (appOpPkgs.isEmpty()) {
12573                        mAppOpPermissionPackages.remove(perm);
12574                    }
12575                }
12576            }
12577        }
12578        if (r != null) {
12579            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12580        }
12581
12582        N = pkg.instrumentation.size();
12583        r = null;
12584        for (i=0; i<N; i++) {
12585            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12586            mInstrumentation.remove(a.getComponentName());
12587            if (DEBUG_REMOVE && chatty) {
12588                if (r == null) {
12589                    r = new StringBuilder(256);
12590                } else {
12591                    r.append(' ');
12592                }
12593                r.append(a.info.name);
12594            }
12595        }
12596        if (r != null) {
12597            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12598        }
12599
12600        r = null;
12601        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12602            // Only system apps can hold shared libraries.
12603            if (pkg.libraryNames != null) {
12604                for (i = 0; i < pkg.libraryNames.size(); i++) {
12605                    String name = pkg.libraryNames.get(i);
12606                    if (removeSharedLibraryLPw(name, 0)) {
12607                        if (DEBUG_REMOVE && chatty) {
12608                            if (r == null) {
12609                                r = new StringBuilder(256);
12610                            } else {
12611                                r.append(' ');
12612                            }
12613                            r.append(name);
12614                        }
12615                    }
12616                }
12617            }
12618        }
12619
12620        r = null;
12621
12622        // Any package can hold static shared libraries.
12623        if (pkg.staticSharedLibName != null) {
12624            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12625                if (DEBUG_REMOVE && chatty) {
12626                    if (r == null) {
12627                        r = new StringBuilder(256);
12628                    } else {
12629                        r.append(' ');
12630                    }
12631                    r.append(pkg.staticSharedLibName);
12632                }
12633            }
12634        }
12635
12636        if (r != null) {
12637            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12638        }
12639    }
12640
12641    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12642        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12643            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12644                return true;
12645            }
12646        }
12647        return false;
12648    }
12649
12650    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12651    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12652    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12653
12654    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12655        // Update the parent permissions
12656        updatePermissionsLPw(pkg.packageName, pkg, flags);
12657        // Update the child permissions
12658        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12659        for (int i = 0; i < childCount; i++) {
12660            PackageParser.Package childPkg = pkg.childPackages.get(i);
12661            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12662        }
12663    }
12664
12665    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12666            int flags) {
12667        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12668        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12669    }
12670
12671    private void updatePermissionsLPw(String changingPkg,
12672            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12673        // Make sure there are no dangling permission trees.
12674        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12675        while (it.hasNext()) {
12676            final BasePermission bp = it.next();
12677            if (bp.packageSetting == null) {
12678                // We may not yet have parsed the package, so just see if
12679                // we still know about its settings.
12680                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12681            }
12682            if (bp.packageSetting == null) {
12683                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12684                        + " from package " + bp.sourcePackage);
12685                it.remove();
12686            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12687                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12688                    Slog.i(TAG, "Removing old permission tree: " + bp.name
12689                            + " from package " + bp.sourcePackage);
12690                    flags |= UPDATE_PERMISSIONS_ALL;
12691                    it.remove();
12692                }
12693            }
12694        }
12695
12696        // Make sure all dynamic permissions have been assigned to a package,
12697        // and make sure there are no dangling permissions.
12698        it = mSettings.mPermissions.values().iterator();
12699        while (it.hasNext()) {
12700            final BasePermission bp = it.next();
12701            if (bp.type == BasePermission.TYPE_DYNAMIC) {
12702                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12703                        + bp.name + " pkg=" + bp.sourcePackage
12704                        + " info=" + bp.pendingInfo);
12705                if (bp.packageSetting == null && bp.pendingInfo != null) {
12706                    final BasePermission tree = findPermissionTreeLP(bp.name);
12707                    if (tree != null && tree.perm != null) {
12708                        bp.packageSetting = tree.packageSetting;
12709                        bp.perm = new PackageParser.Permission(tree.perm.owner,
12710                                new PermissionInfo(bp.pendingInfo));
12711                        bp.perm.info.packageName = tree.perm.info.packageName;
12712                        bp.perm.info.name = bp.name;
12713                        bp.uid = tree.uid;
12714                    }
12715                }
12716            }
12717            if (bp.packageSetting == null) {
12718                // We may not yet have parsed the package, so just see if
12719                // we still know about its settings.
12720                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12721            }
12722            if (bp.packageSetting == null) {
12723                Slog.w(TAG, "Removing dangling permission: " + bp.name
12724                        + " from package " + bp.sourcePackage);
12725                it.remove();
12726            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12727                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12728                    Slog.i(TAG, "Removing old permission: " + bp.name
12729                            + " from package " + bp.sourcePackage);
12730                    flags |= UPDATE_PERMISSIONS_ALL;
12731                    it.remove();
12732                }
12733            }
12734        }
12735
12736        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12737        // Now update the permissions for all packages, in particular
12738        // replace the granted permissions of the system packages.
12739        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12740            for (PackageParser.Package pkg : mPackages.values()) {
12741                if (pkg != pkgInfo) {
12742                    // Only replace for packages on requested volume
12743                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12744                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12745                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12746                    grantPermissionsLPw(pkg, replace, changingPkg);
12747                }
12748            }
12749        }
12750
12751        if (pkgInfo != null) {
12752            // Only replace for packages on requested volume
12753            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12754            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12755                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12756            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12757        }
12758        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12759    }
12760
12761    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12762            String packageOfInterest) {
12763        // IMPORTANT: There are two types of permissions: install and runtime.
12764        // Install time permissions are granted when the app is installed to
12765        // all device users and users added in the future. Runtime permissions
12766        // are granted at runtime explicitly to specific users. Normal and signature
12767        // protected permissions are install time permissions. Dangerous permissions
12768        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12769        // otherwise they are runtime permissions. This function does not manage
12770        // runtime permissions except for the case an app targeting Lollipop MR1
12771        // being upgraded to target a newer SDK, in which case dangerous permissions
12772        // are transformed from install time to runtime ones.
12773
12774        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12775        if (ps == null) {
12776            return;
12777        }
12778
12779        PermissionsState permissionsState = ps.getPermissionsState();
12780        PermissionsState origPermissions = permissionsState;
12781
12782        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12783
12784        boolean runtimePermissionsRevoked = false;
12785        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12786
12787        boolean changedInstallPermission = false;
12788
12789        if (replace) {
12790            ps.installPermissionsFixed = false;
12791            if (!ps.isSharedUser()) {
12792                origPermissions = new PermissionsState(permissionsState);
12793                permissionsState.reset();
12794            } else {
12795                // We need to know only about runtime permission changes since the
12796                // calling code always writes the install permissions state but
12797                // the runtime ones are written only if changed. The only cases of
12798                // changed runtime permissions here are promotion of an install to
12799                // runtime and revocation of a runtime from a shared user.
12800                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12801                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
12802                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12803                    runtimePermissionsRevoked = true;
12804                }
12805            }
12806        }
12807
12808        permissionsState.setGlobalGids(mGlobalGids);
12809
12810        final int N = pkg.requestedPermissions.size();
12811        for (int i=0; i<N; i++) {
12812            final String name = pkg.requestedPermissions.get(i);
12813            final BasePermission bp = mSettings.mPermissions.get(name);
12814            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12815                    >= Build.VERSION_CODES.M;
12816
12817            if (DEBUG_INSTALL) {
12818                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12819            }
12820
12821            if (bp == null || bp.packageSetting == null) {
12822                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12823                    if (DEBUG_PERMISSIONS) {
12824                        Slog.i(TAG, "Unknown permission " + name
12825                                + " in package " + pkg.packageName);
12826                    }
12827                }
12828                continue;
12829            }
12830
12831
12832            // Limit ephemeral apps to ephemeral allowed permissions.
12833            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12834                if (DEBUG_PERMISSIONS) {
12835                    Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
12836                            + pkg.packageName);
12837                }
12838                continue;
12839            }
12840
12841            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12842                if (DEBUG_PERMISSIONS) {
12843                    Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
12844                            + pkg.packageName);
12845                }
12846                continue;
12847            }
12848
12849            final String perm = bp.name;
12850            boolean allowedSig = false;
12851            int grant = GRANT_DENIED;
12852
12853            // Keep track of app op permissions.
12854            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12855                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
12856                if (pkgs == null) {
12857                    pkgs = new ArraySet<>();
12858                    mAppOpPermissionPackages.put(bp.name, pkgs);
12859                }
12860                pkgs.add(pkg.packageName);
12861            }
12862
12863            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
12864            switch (level) {
12865                case PermissionInfo.PROTECTION_NORMAL: {
12866                    // For all apps normal permissions are install time ones.
12867                    grant = GRANT_INSTALL;
12868                } break;
12869
12870                case PermissionInfo.PROTECTION_DANGEROUS: {
12871                    // If a permission review is required for legacy apps we represent
12872                    // their permissions as always granted runtime ones since we need
12873                    // to keep the review required permission flag per user while an
12874                    // install permission's state is shared across all users.
12875                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12876                        // For legacy apps dangerous permissions are install time ones.
12877                        grant = GRANT_INSTALL;
12878                    } else if (origPermissions.hasInstallPermission(bp.name)) {
12879                        // For legacy apps that became modern, install becomes runtime.
12880                        grant = GRANT_UPGRADE;
12881                    } else if (mPromoteSystemApps
12882                            && isSystemApp(ps)
12883                            && mExistingSystemPackages.contains(ps.name)) {
12884                        // For legacy system apps, install becomes runtime.
12885                        // We cannot check hasInstallPermission() for system apps since those
12886                        // permissions were granted implicitly and not persisted pre-M.
12887                        grant = GRANT_UPGRADE;
12888                    } else {
12889                        // For modern apps keep runtime permissions unchanged.
12890                        grant = GRANT_RUNTIME;
12891                    }
12892                } break;
12893
12894                case PermissionInfo.PROTECTION_SIGNATURE: {
12895                    // For all apps signature permissions are install time ones.
12896                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
12897                    if (allowedSig) {
12898                        grant = GRANT_INSTALL;
12899                    }
12900                } break;
12901            }
12902
12903            if (DEBUG_PERMISSIONS) {
12904                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
12905            }
12906
12907            if (grant != GRANT_DENIED) {
12908                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
12909                    // If this is an existing, non-system package, then
12910                    // we can't add any new permissions to it.
12911                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
12912                        // Except...  if this is a permission that was added
12913                        // to the platform (note: need to only do this when
12914                        // updating the platform).
12915                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
12916                            grant = GRANT_DENIED;
12917                        }
12918                    }
12919                }
12920
12921                switch (grant) {
12922                    case GRANT_INSTALL: {
12923                        // Revoke this as runtime permission to handle the case of
12924                        // a runtime permission being downgraded to an install one.
12925                        // Also in permission review mode we keep dangerous permissions
12926                        // for legacy apps
12927                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12928                            if (origPermissions.getRuntimePermissionState(
12929                                    bp.name, userId) != null) {
12930                                // Revoke the runtime permission and clear the flags.
12931                                origPermissions.revokeRuntimePermission(bp, userId);
12932                                origPermissions.updatePermissionFlags(bp, userId,
12933                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
12934                                // If we revoked a permission permission, we have to write.
12935                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12936                                        changedRuntimePermissionUserIds, userId);
12937                            }
12938                        }
12939                        // Grant an install permission.
12940                        if (permissionsState.grantInstallPermission(bp) !=
12941                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
12942                            changedInstallPermission = true;
12943                        }
12944                    } break;
12945
12946                    case GRANT_RUNTIME: {
12947                        // Grant previously granted runtime permissions.
12948                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12949                            PermissionState permissionState = origPermissions
12950                                    .getRuntimePermissionState(bp.name, userId);
12951                            int flags = permissionState != null
12952                                    ? permissionState.getFlags() : 0;
12953                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
12954                                // Don't propagate the permission in a permission review mode if
12955                                // the former was revoked, i.e. marked to not propagate on upgrade.
12956                                // Note that in a permission review mode install permissions are
12957                                // represented as constantly granted runtime ones since we need to
12958                                // keep a per user state associated with the permission. Also the
12959                                // revoke on upgrade flag is no longer applicable and is reset.
12960                                final boolean revokeOnUpgrade = (flags & PackageManager
12961                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
12962                                if (revokeOnUpgrade) {
12963                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12964                                    // Since we changed the flags, we have to write.
12965                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12966                                            changedRuntimePermissionUserIds, userId);
12967                                }
12968                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
12969                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
12970                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
12971                                        // If we cannot put the permission as it was,
12972                                        // we have to write.
12973                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12974                                                changedRuntimePermissionUserIds, userId);
12975                                    }
12976                                }
12977
12978                                // If the app supports runtime permissions no need for a review.
12979                                if (mPermissionReviewRequired
12980                                        && appSupportsRuntimePermissions
12981                                        && (flags & PackageManager
12982                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
12983                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
12984                                    // Since we changed the flags, we have to write.
12985                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12986                                            changedRuntimePermissionUserIds, userId);
12987                                }
12988                            } else if (mPermissionReviewRequired
12989                                    && !appSupportsRuntimePermissions) {
12990                                // For legacy apps that need a permission review, every new
12991                                // runtime permission is granted but it is pending a review.
12992                                // We also need to review only platform defined runtime
12993                                // permissions as these are the only ones the platform knows
12994                                // how to disable the API to simulate revocation as legacy
12995                                // apps don't expect to run with revoked permissions.
12996                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
12997                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
12998                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
12999                                        // We changed the flags, hence have to write.
13000                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13001                                                changedRuntimePermissionUserIds, userId);
13002                                    }
13003                                }
13004                                if (permissionsState.grantRuntimePermission(bp, userId)
13005                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
13006                                    // We changed the permission, hence have to write.
13007                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13008                                            changedRuntimePermissionUserIds, userId);
13009                                }
13010                            }
13011                            // Propagate the permission flags.
13012                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
13013                        }
13014                    } break;
13015
13016                    case GRANT_UPGRADE: {
13017                        // Grant runtime permissions for a previously held install permission.
13018                        PermissionState permissionState = origPermissions
13019                                .getInstallPermissionState(bp.name);
13020                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
13021
13022                        if (origPermissions.revokeInstallPermission(bp)
13023                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
13024                            // We will be transferring the permission flags, so clear them.
13025                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
13026                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
13027                            changedInstallPermission = true;
13028                        }
13029
13030                        // If the permission is not to be promoted to runtime we ignore it and
13031                        // also its other flags as they are not applicable to install permissions.
13032                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
13033                            for (int userId : currentUserIds) {
13034                                if (permissionsState.grantRuntimePermission(bp, userId) !=
13035                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
13036                                    // Transfer the permission flags.
13037                                    permissionsState.updatePermissionFlags(bp, userId,
13038                                            flags, flags);
13039                                    // If we granted the permission, we have to write.
13040                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13041                                            changedRuntimePermissionUserIds, userId);
13042                                }
13043                            }
13044                        }
13045                    } break;
13046
13047                    default: {
13048                        if (packageOfInterest == null
13049                                || packageOfInterest.equals(pkg.packageName)) {
13050                            if (DEBUG_PERMISSIONS) {
13051                                Slog.i(TAG, "Not granting permission " + perm
13052                                        + " to package " + pkg.packageName
13053                                        + " because it was previously installed without");
13054                            }
13055                        }
13056                    } break;
13057                }
13058            } else {
13059                if (permissionsState.revokeInstallPermission(bp) !=
13060                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
13061                    // Also drop the permission flags.
13062                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
13063                            PackageManager.MASK_PERMISSION_FLAGS, 0);
13064                    changedInstallPermission = true;
13065                    Slog.i(TAG, "Un-granting permission " + perm
13066                            + " from package " + pkg.packageName
13067                            + " (protectionLevel=" + bp.protectionLevel
13068                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
13069                            + ")");
13070                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
13071                    // Don't print warning for app op permissions, since it is fine for them
13072                    // not to be granted, there is a UI for the user to decide.
13073                    if (DEBUG_PERMISSIONS
13074                            && (packageOfInterest == null
13075                                    || packageOfInterest.equals(pkg.packageName))) {
13076                        Slog.i(TAG, "Not granting permission " + perm
13077                                + " to package " + pkg.packageName
13078                                + " (protectionLevel=" + bp.protectionLevel
13079                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
13080                                + ")");
13081                    }
13082                }
13083            }
13084        }
13085
13086        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
13087                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
13088            // This is the first that we have heard about this package, so the
13089            // permissions we have now selected are fixed until explicitly
13090            // changed.
13091            ps.installPermissionsFixed = true;
13092        }
13093
13094        // Persist the runtime permissions state for users with changes. If permissions
13095        // were revoked because no app in the shared user declares them we have to
13096        // write synchronously to avoid losing runtime permissions state.
13097        for (int userId : changedRuntimePermissionUserIds) {
13098            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
13099        }
13100    }
13101
13102    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
13103        boolean allowed = false;
13104        final int NP = PackageParser.NEW_PERMISSIONS.length;
13105        for (int ip=0; ip<NP; ip++) {
13106            final PackageParser.NewPermissionInfo npi
13107                    = PackageParser.NEW_PERMISSIONS[ip];
13108            if (npi.name.equals(perm)
13109                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
13110                allowed = true;
13111                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
13112                        + pkg.packageName);
13113                break;
13114            }
13115        }
13116        return allowed;
13117    }
13118
13119    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
13120            BasePermission bp, PermissionsState origPermissions) {
13121        boolean privilegedPermission = (bp.protectionLevel
13122                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
13123        boolean privappPermissionsDisable =
13124                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
13125        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
13126        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
13127        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
13128                && !platformPackage && platformPermission) {
13129            final ArraySet<String> allowedPermissions = SystemConfig.getInstance()
13130                    .getPrivAppPermissions(pkg.packageName);
13131            final boolean whitelisted =
13132                    allowedPermissions != null && allowedPermissions.contains(perm);
13133            if (!whitelisted) {
13134                Slog.w(TAG, "Privileged permission " + perm + " for package "
13135                        + pkg.packageName + " - not in privapp-permissions whitelist");
13136                // Only report violations for apps on system image
13137                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
13138                    // it's only a reportable violation if the permission isn't explicitly denied
13139                    final ArraySet<String> deniedPermissions = SystemConfig.getInstance()
13140                            .getPrivAppDenyPermissions(pkg.packageName);
13141                    final boolean permissionViolation =
13142                            deniedPermissions == null || !deniedPermissions.contains(perm);
13143                    if (permissionViolation) {
13144                        if (mPrivappPermissionsViolations == null) {
13145                            mPrivappPermissionsViolations = new ArraySet<>();
13146                        }
13147                        mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
13148                    } else {
13149                        return false;
13150                    }
13151                }
13152                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
13153                    return false;
13154                }
13155            }
13156        }
13157        boolean allowed = (compareSignatures(
13158                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
13159                        == PackageManager.SIGNATURE_MATCH)
13160                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
13161                        == PackageManager.SIGNATURE_MATCH);
13162        if (!allowed && privilegedPermission) {
13163            if (isSystemApp(pkg)) {
13164                // For updated system applications, a system permission
13165                // is granted only if it had been defined by the original application.
13166                if (pkg.isUpdatedSystemApp()) {
13167                    final PackageSetting sysPs = mSettings
13168                            .getDisabledSystemPkgLPr(pkg.packageName);
13169                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
13170                        // If the original was granted this permission, we take
13171                        // that grant decision as read and propagate it to the
13172                        // update.
13173                        if (sysPs.isPrivileged()) {
13174                            allowed = true;
13175                        }
13176                    } else {
13177                        // The system apk may have been updated with an older
13178                        // version of the one on the data partition, but which
13179                        // granted a new system permission that it didn't have
13180                        // before.  In this case we do want to allow the app to
13181                        // now get the new permission if the ancestral apk is
13182                        // privileged to get it.
13183                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
13184                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
13185                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
13186                                    allowed = true;
13187                                    break;
13188                                }
13189                            }
13190                        }
13191                        // Also if a privileged parent package on the system image or any of
13192                        // its children requested a privileged permission, the updated child
13193                        // packages can also get the permission.
13194                        if (pkg.parentPackage != null) {
13195                            final PackageSetting disabledSysParentPs = mSettings
13196                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
13197                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
13198                                    && disabledSysParentPs.isPrivileged()) {
13199                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
13200                                    allowed = true;
13201                                } else if (disabledSysParentPs.pkg.childPackages != null) {
13202                                    final int count = disabledSysParentPs.pkg.childPackages.size();
13203                                    for (int i = 0; i < count; i++) {
13204                                        PackageParser.Package disabledSysChildPkg =
13205                                                disabledSysParentPs.pkg.childPackages.get(i);
13206                                        if (isPackageRequestingPermission(disabledSysChildPkg,
13207                                                perm)) {
13208                                            allowed = true;
13209                                            break;
13210                                        }
13211                                    }
13212                                }
13213                            }
13214                        }
13215                    }
13216                } else {
13217                    allowed = isPrivilegedApp(pkg);
13218                }
13219            }
13220        }
13221        if (!allowed) {
13222            if (!allowed && (bp.protectionLevel
13223                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
13224                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
13225                // If this was a previously normal/dangerous permission that got moved
13226                // to a system permission as part of the runtime permission redesign, then
13227                // we still want to blindly grant it to old apps.
13228                allowed = true;
13229            }
13230            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
13231                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
13232                // If this permission is to be granted to the system installer and
13233                // this app is an installer, then it gets the permission.
13234                allowed = true;
13235            }
13236            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
13237                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
13238                // If this permission is to be granted to the system verifier and
13239                // this app is a verifier, then it gets the permission.
13240                allowed = true;
13241            }
13242            if (!allowed && (bp.protectionLevel
13243                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
13244                    && isSystemApp(pkg)) {
13245                // Any pre-installed system app is allowed to get this permission.
13246                allowed = true;
13247            }
13248            if (!allowed && (bp.protectionLevel
13249                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
13250                // For development permissions, a development permission
13251                // is granted only if it was already granted.
13252                allowed = origPermissions.hasInstallPermission(perm);
13253            }
13254            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
13255                    && pkg.packageName.equals(mSetupWizardPackage)) {
13256                // If this permission is to be granted to the system setup wizard and
13257                // this app is a setup wizard, then it gets the permission.
13258                allowed = true;
13259            }
13260        }
13261        return allowed;
13262    }
13263
13264    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
13265        final int permCount = pkg.requestedPermissions.size();
13266        for (int j = 0; j < permCount; j++) {
13267            String requestedPermission = pkg.requestedPermissions.get(j);
13268            if (permission.equals(requestedPermission)) {
13269                return true;
13270            }
13271        }
13272        return false;
13273    }
13274
13275    final class ActivityIntentResolver
13276            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
13277        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13278                boolean defaultOnly, int userId) {
13279            if (!sUserManager.exists(userId)) return null;
13280            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
13281            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13282        }
13283
13284        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13285                int userId) {
13286            if (!sUserManager.exists(userId)) return null;
13287            mFlags = flags;
13288            return super.queryIntent(intent, resolvedType,
13289                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13290                    userId);
13291        }
13292
13293        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13294                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
13295            if (!sUserManager.exists(userId)) return null;
13296            if (packageActivities == null) {
13297                return null;
13298            }
13299            mFlags = flags;
13300            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13301            final int N = packageActivities.size();
13302            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
13303                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
13304
13305            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
13306            for (int i = 0; i < N; ++i) {
13307                intentFilters = packageActivities.get(i).intents;
13308                if (intentFilters != null && intentFilters.size() > 0) {
13309                    PackageParser.ActivityIntentInfo[] array =
13310                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
13311                    intentFilters.toArray(array);
13312                    listCut.add(array);
13313                }
13314            }
13315            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13316        }
13317
13318        /**
13319         * Finds a privileged activity that matches the specified activity names.
13320         */
13321        private PackageParser.Activity findMatchingActivity(
13322                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
13323            for (PackageParser.Activity sysActivity : activityList) {
13324                if (sysActivity.info.name.equals(activityInfo.name)) {
13325                    return sysActivity;
13326                }
13327                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
13328                    return sysActivity;
13329                }
13330                if (sysActivity.info.targetActivity != null) {
13331                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
13332                        return sysActivity;
13333                    }
13334                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
13335                        return sysActivity;
13336                    }
13337                }
13338            }
13339            return null;
13340        }
13341
13342        public class IterGenerator<E> {
13343            public Iterator<E> generate(ActivityIntentInfo info) {
13344                return null;
13345            }
13346        }
13347
13348        public class ActionIterGenerator extends IterGenerator<String> {
13349            @Override
13350            public Iterator<String> generate(ActivityIntentInfo info) {
13351                return info.actionsIterator();
13352            }
13353        }
13354
13355        public class CategoriesIterGenerator extends IterGenerator<String> {
13356            @Override
13357            public Iterator<String> generate(ActivityIntentInfo info) {
13358                return info.categoriesIterator();
13359            }
13360        }
13361
13362        public class SchemesIterGenerator extends IterGenerator<String> {
13363            @Override
13364            public Iterator<String> generate(ActivityIntentInfo info) {
13365                return info.schemesIterator();
13366            }
13367        }
13368
13369        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
13370            @Override
13371            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
13372                return info.authoritiesIterator();
13373            }
13374        }
13375
13376        /**
13377         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
13378         * MODIFIED. Do not pass in a list that should not be changed.
13379         */
13380        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
13381                IterGenerator<T> generator, Iterator<T> searchIterator) {
13382            // loop through the set of actions; every one must be found in the intent filter
13383            while (searchIterator.hasNext()) {
13384                // we must have at least one filter in the list to consider a match
13385                if (intentList.size() == 0) {
13386                    break;
13387                }
13388
13389                final T searchAction = searchIterator.next();
13390
13391                // loop through the set of intent filters
13392                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
13393                while (intentIter.hasNext()) {
13394                    final ActivityIntentInfo intentInfo = intentIter.next();
13395                    boolean selectionFound = false;
13396
13397                    // loop through the intent filter's selection criteria; at least one
13398                    // of them must match the searched criteria
13399                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
13400                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
13401                        final T intentSelection = intentSelectionIter.next();
13402                        if (intentSelection != null && intentSelection.equals(searchAction)) {
13403                            selectionFound = true;
13404                            break;
13405                        }
13406                    }
13407
13408                    // the selection criteria wasn't found in this filter's set; this filter
13409                    // is not a potential match
13410                    if (!selectionFound) {
13411                        intentIter.remove();
13412                    }
13413                }
13414            }
13415        }
13416
13417        private boolean isProtectedAction(ActivityIntentInfo filter) {
13418            final Iterator<String> actionsIter = filter.actionsIterator();
13419            while (actionsIter != null && actionsIter.hasNext()) {
13420                final String filterAction = actionsIter.next();
13421                if (PROTECTED_ACTIONS.contains(filterAction)) {
13422                    return true;
13423                }
13424            }
13425            return false;
13426        }
13427
13428        /**
13429         * Adjusts the priority of the given intent filter according to policy.
13430         * <p>
13431         * <ul>
13432         * <li>The priority for non privileged applications is capped to '0'</li>
13433         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
13434         * <li>The priority for unbundled updates to privileged applications is capped to the
13435         *      priority defined on the system partition</li>
13436         * </ul>
13437         * <p>
13438         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
13439         * allowed to obtain any priority on any action.
13440         */
13441        private void adjustPriority(
13442                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
13443            // nothing to do; priority is fine as-is
13444            if (intent.getPriority() <= 0) {
13445                return;
13446            }
13447
13448            final ActivityInfo activityInfo = intent.activity.info;
13449            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
13450
13451            final boolean privilegedApp =
13452                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
13453            if (!privilegedApp) {
13454                // non-privileged applications can never define a priority >0
13455                if (DEBUG_FILTERS) {
13456                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
13457                            + " package: " + applicationInfo.packageName
13458                            + " activity: " + intent.activity.className
13459                            + " origPrio: " + intent.getPriority());
13460                }
13461                intent.setPriority(0);
13462                return;
13463            }
13464
13465            if (systemActivities == null) {
13466                // the system package is not disabled; we're parsing the system partition
13467                if (isProtectedAction(intent)) {
13468                    if (mDeferProtectedFilters) {
13469                        // We can't deal with these just yet. No component should ever obtain a
13470                        // >0 priority for a protected actions, with ONE exception -- the setup
13471                        // wizard. The setup wizard, however, cannot be known until we're able to
13472                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
13473                        // until all intent filters have been processed. Chicken, meet egg.
13474                        // Let the filter temporarily have a high priority and rectify the
13475                        // priorities after all system packages have been scanned.
13476                        mProtectedFilters.add(intent);
13477                        if (DEBUG_FILTERS) {
13478                            Slog.i(TAG, "Protected action; save for later;"
13479                                    + " package: " + applicationInfo.packageName
13480                                    + " activity: " + intent.activity.className
13481                                    + " origPrio: " + intent.getPriority());
13482                        }
13483                        return;
13484                    } else {
13485                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13486                            Slog.i(TAG, "No setup wizard;"
13487                                + " All protected intents capped to priority 0");
13488                        }
13489                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13490                            if (DEBUG_FILTERS) {
13491                                Slog.i(TAG, "Found setup wizard;"
13492                                    + " allow priority " + intent.getPriority() + ";"
13493                                    + " package: " + intent.activity.info.packageName
13494                                    + " activity: " + intent.activity.className
13495                                    + " priority: " + intent.getPriority());
13496                            }
13497                            // setup wizard gets whatever it wants
13498                            return;
13499                        }
13500                        if (DEBUG_FILTERS) {
13501                            Slog.i(TAG, "Protected action; cap priority to 0;"
13502                                    + " package: " + intent.activity.info.packageName
13503                                    + " activity: " + intent.activity.className
13504                                    + " origPrio: " + intent.getPriority());
13505                        }
13506                        intent.setPriority(0);
13507                        return;
13508                    }
13509                }
13510                // privileged apps on the system image get whatever priority they request
13511                return;
13512            }
13513
13514            // privileged app unbundled update ... try to find the same activity
13515            final PackageParser.Activity foundActivity =
13516                    findMatchingActivity(systemActivities, activityInfo);
13517            if (foundActivity == null) {
13518                // this is a new activity; it cannot obtain >0 priority
13519                if (DEBUG_FILTERS) {
13520                    Slog.i(TAG, "New activity; cap priority to 0;"
13521                            + " package: " + applicationInfo.packageName
13522                            + " activity: " + intent.activity.className
13523                            + " origPrio: " + intent.getPriority());
13524                }
13525                intent.setPriority(0);
13526                return;
13527            }
13528
13529            // found activity, now check for filter equivalence
13530
13531            // a shallow copy is enough; we modify the list, not its contents
13532            final List<ActivityIntentInfo> intentListCopy =
13533                    new ArrayList<>(foundActivity.intents);
13534            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13535
13536            // find matching action subsets
13537            final Iterator<String> actionsIterator = intent.actionsIterator();
13538            if (actionsIterator != null) {
13539                getIntentListSubset(
13540                        intentListCopy, new ActionIterGenerator(), actionsIterator);
13541                if (intentListCopy.size() == 0) {
13542                    // no more intents to match; we're not equivalent
13543                    if (DEBUG_FILTERS) {
13544                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
13545                                + " package: " + applicationInfo.packageName
13546                                + " activity: " + intent.activity.className
13547                                + " origPrio: " + intent.getPriority());
13548                    }
13549                    intent.setPriority(0);
13550                    return;
13551                }
13552            }
13553
13554            // find matching category subsets
13555            final Iterator<String> categoriesIterator = intent.categoriesIterator();
13556            if (categoriesIterator != null) {
13557                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13558                        categoriesIterator);
13559                if (intentListCopy.size() == 0) {
13560                    // no more intents to match; we're not equivalent
13561                    if (DEBUG_FILTERS) {
13562                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
13563                                + " package: " + applicationInfo.packageName
13564                                + " activity: " + intent.activity.className
13565                                + " origPrio: " + intent.getPriority());
13566                    }
13567                    intent.setPriority(0);
13568                    return;
13569                }
13570            }
13571
13572            // find matching schemes subsets
13573            final Iterator<String> schemesIterator = intent.schemesIterator();
13574            if (schemesIterator != null) {
13575                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13576                        schemesIterator);
13577                if (intentListCopy.size() == 0) {
13578                    // no more intents to match; we're not equivalent
13579                    if (DEBUG_FILTERS) {
13580                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
13581                                + " package: " + applicationInfo.packageName
13582                                + " activity: " + intent.activity.className
13583                                + " origPrio: " + intent.getPriority());
13584                    }
13585                    intent.setPriority(0);
13586                    return;
13587                }
13588            }
13589
13590            // find matching authorities subsets
13591            final Iterator<IntentFilter.AuthorityEntry>
13592                    authoritiesIterator = intent.authoritiesIterator();
13593            if (authoritiesIterator != null) {
13594                getIntentListSubset(intentListCopy,
13595                        new AuthoritiesIterGenerator(),
13596                        authoritiesIterator);
13597                if (intentListCopy.size() == 0) {
13598                    // no more intents to match; we're not equivalent
13599                    if (DEBUG_FILTERS) {
13600                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13601                                + " package: " + applicationInfo.packageName
13602                                + " activity: " + intent.activity.className
13603                                + " origPrio: " + intent.getPriority());
13604                    }
13605                    intent.setPriority(0);
13606                    return;
13607                }
13608            }
13609
13610            // we found matching filter(s); app gets the max priority of all intents
13611            int cappedPriority = 0;
13612            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13613                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13614            }
13615            if (intent.getPriority() > cappedPriority) {
13616                if (DEBUG_FILTERS) {
13617                    Slog.i(TAG, "Found matching filter(s);"
13618                            + " cap priority to " + cappedPriority + ";"
13619                            + " package: " + applicationInfo.packageName
13620                            + " activity: " + intent.activity.className
13621                            + " origPrio: " + intent.getPriority());
13622                }
13623                intent.setPriority(cappedPriority);
13624                return;
13625            }
13626            // all this for nothing; the requested priority was <= what was on the system
13627        }
13628
13629        public final void addActivity(PackageParser.Activity a, String type) {
13630            mActivities.put(a.getComponentName(), a);
13631            if (DEBUG_SHOW_INFO)
13632                Log.v(
13633                TAG, "  " + type + " " +
13634                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13635            if (DEBUG_SHOW_INFO)
13636                Log.v(TAG, "    Class=" + a.info.name);
13637            final int NI = a.intents.size();
13638            for (int j=0; j<NI; j++) {
13639                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13640                if ("activity".equals(type)) {
13641                    final PackageSetting ps =
13642                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13643                    final List<PackageParser.Activity> systemActivities =
13644                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
13645                    adjustPriority(systemActivities, intent);
13646                }
13647                if (DEBUG_SHOW_INFO) {
13648                    Log.v(TAG, "    IntentFilter:");
13649                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13650                }
13651                if (!intent.debugCheck()) {
13652                    Log.w(TAG, "==> For Activity " + a.info.name);
13653                }
13654                addFilter(intent);
13655            }
13656        }
13657
13658        public final void removeActivity(PackageParser.Activity a, String type) {
13659            mActivities.remove(a.getComponentName());
13660            if (DEBUG_SHOW_INFO) {
13661                Log.v(TAG, "  " + type + " "
13662                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13663                                : a.info.name) + ":");
13664                Log.v(TAG, "    Class=" + a.info.name);
13665            }
13666            final int NI = a.intents.size();
13667            for (int j=0; j<NI; j++) {
13668                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13669                if (DEBUG_SHOW_INFO) {
13670                    Log.v(TAG, "    IntentFilter:");
13671                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13672                }
13673                removeFilter(intent);
13674            }
13675        }
13676
13677        @Override
13678        protected boolean allowFilterResult(
13679                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13680            ActivityInfo filterAi = filter.activity.info;
13681            for (int i=dest.size()-1; i>=0; i--) {
13682                ActivityInfo destAi = dest.get(i).activityInfo;
13683                if (destAi.name == filterAi.name
13684                        && destAi.packageName == filterAi.packageName) {
13685                    return false;
13686                }
13687            }
13688            return true;
13689        }
13690
13691        @Override
13692        protected ActivityIntentInfo[] newArray(int size) {
13693            return new ActivityIntentInfo[size];
13694        }
13695
13696        @Override
13697        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13698            if (!sUserManager.exists(userId)) return true;
13699            PackageParser.Package p = filter.activity.owner;
13700            if (p != null) {
13701                PackageSetting ps = (PackageSetting)p.mExtras;
13702                if (ps != null) {
13703                    // System apps are never considered stopped for purposes of
13704                    // filtering, because there may be no way for the user to
13705                    // actually re-launch them.
13706                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13707                            && ps.getStopped(userId);
13708                }
13709            }
13710            return false;
13711        }
13712
13713        @Override
13714        protected boolean isPackageForFilter(String packageName,
13715                PackageParser.ActivityIntentInfo info) {
13716            return packageName.equals(info.activity.owner.packageName);
13717        }
13718
13719        @Override
13720        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13721                int match, int userId) {
13722            if (!sUserManager.exists(userId)) return null;
13723            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13724                return null;
13725            }
13726            final PackageParser.Activity activity = info.activity;
13727            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13728            if (ps == null) {
13729                return null;
13730            }
13731            final PackageUserState userState = ps.readUserState(userId);
13732            ActivityInfo ai =
13733                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13734            if (ai == null) {
13735                return null;
13736            }
13737            final boolean matchExplicitlyVisibleOnly =
13738                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13739            final boolean matchVisibleToInstantApp =
13740                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13741            final boolean componentVisible =
13742                    matchVisibleToInstantApp
13743                    && info.isVisibleToInstantApp()
13744                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13745            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13746            // throw out filters that aren't visible to ephemeral apps
13747            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13748                return null;
13749            }
13750            // throw out instant app filters if we're not explicitly requesting them
13751            if (!matchInstantApp && userState.instantApp) {
13752                return null;
13753            }
13754            // throw out instant app filters if updates are available; will trigger
13755            // instant app resolution
13756            if (userState.instantApp && ps.isUpdateAvailable()) {
13757                return null;
13758            }
13759            final ResolveInfo res = new ResolveInfo();
13760            res.activityInfo = ai;
13761            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13762                res.filter = info;
13763            }
13764            if (info != null) {
13765                res.handleAllWebDataURI = info.handleAllWebDataURI();
13766            }
13767            res.priority = info.getPriority();
13768            res.preferredOrder = activity.owner.mPreferredOrder;
13769            //System.out.println("Result: " + res.activityInfo.className +
13770            //                   " = " + res.priority);
13771            res.match = match;
13772            res.isDefault = info.hasDefault;
13773            res.labelRes = info.labelRes;
13774            res.nonLocalizedLabel = info.nonLocalizedLabel;
13775            if (userNeedsBadging(userId)) {
13776                res.noResourceId = true;
13777            } else {
13778                res.icon = info.icon;
13779            }
13780            res.iconResourceId = info.icon;
13781            res.system = res.activityInfo.applicationInfo.isSystemApp();
13782            res.isInstantAppAvailable = userState.instantApp;
13783            return res;
13784        }
13785
13786        @Override
13787        protected void sortResults(List<ResolveInfo> results) {
13788            Collections.sort(results, mResolvePrioritySorter);
13789        }
13790
13791        @Override
13792        protected void dumpFilter(PrintWriter out, String prefix,
13793                PackageParser.ActivityIntentInfo filter) {
13794            out.print(prefix); out.print(
13795                    Integer.toHexString(System.identityHashCode(filter.activity)));
13796                    out.print(' ');
13797                    filter.activity.printComponentShortName(out);
13798                    out.print(" filter ");
13799                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13800        }
13801
13802        @Override
13803        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13804            return filter.activity;
13805        }
13806
13807        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13808            PackageParser.Activity activity = (PackageParser.Activity)label;
13809            out.print(prefix); out.print(
13810                    Integer.toHexString(System.identityHashCode(activity)));
13811                    out.print(' ');
13812                    activity.printComponentShortName(out);
13813            if (count > 1) {
13814                out.print(" ("); out.print(count); out.print(" filters)");
13815            }
13816            out.println();
13817        }
13818
13819        // Keys are String (activity class name), values are Activity.
13820        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13821                = new ArrayMap<ComponentName, PackageParser.Activity>();
13822        private int mFlags;
13823    }
13824
13825    private final class ServiceIntentResolver
13826            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13827        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13828                boolean defaultOnly, int userId) {
13829            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13830            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13831        }
13832
13833        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13834                int userId) {
13835            if (!sUserManager.exists(userId)) return null;
13836            mFlags = flags;
13837            return super.queryIntent(intent, resolvedType,
13838                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13839                    userId);
13840        }
13841
13842        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13843                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13844            if (!sUserManager.exists(userId)) return null;
13845            if (packageServices == null) {
13846                return null;
13847            }
13848            mFlags = flags;
13849            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13850            final int N = packageServices.size();
13851            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13852                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13853
13854            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13855            for (int i = 0; i < N; ++i) {
13856                intentFilters = packageServices.get(i).intents;
13857                if (intentFilters != null && intentFilters.size() > 0) {
13858                    PackageParser.ServiceIntentInfo[] array =
13859                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
13860                    intentFilters.toArray(array);
13861                    listCut.add(array);
13862                }
13863            }
13864            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13865        }
13866
13867        public final void addService(PackageParser.Service s) {
13868            mServices.put(s.getComponentName(), s);
13869            if (DEBUG_SHOW_INFO) {
13870                Log.v(TAG, "  "
13871                        + (s.info.nonLocalizedLabel != null
13872                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13873                Log.v(TAG, "    Class=" + s.info.name);
13874            }
13875            final int NI = s.intents.size();
13876            int j;
13877            for (j=0; j<NI; j++) {
13878                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13879                if (DEBUG_SHOW_INFO) {
13880                    Log.v(TAG, "    IntentFilter:");
13881                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13882                }
13883                if (!intent.debugCheck()) {
13884                    Log.w(TAG, "==> For Service " + s.info.name);
13885                }
13886                addFilter(intent);
13887            }
13888        }
13889
13890        public final void removeService(PackageParser.Service s) {
13891            mServices.remove(s.getComponentName());
13892            if (DEBUG_SHOW_INFO) {
13893                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
13894                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13895                Log.v(TAG, "    Class=" + s.info.name);
13896            }
13897            final int NI = s.intents.size();
13898            int j;
13899            for (j=0; j<NI; j++) {
13900                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13901                if (DEBUG_SHOW_INFO) {
13902                    Log.v(TAG, "    IntentFilter:");
13903                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13904                }
13905                removeFilter(intent);
13906            }
13907        }
13908
13909        @Override
13910        protected boolean allowFilterResult(
13911                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
13912            ServiceInfo filterSi = filter.service.info;
13913            for (int i=dest.size()-1; i>=0; i--) {
13914                ServiceInfo destAi = dest.get(i).serviceInfo;
13915                if (destAi.name == filterSi.name
13916                        && destAi.packageName == filterSi.packageName) {
13917                    return false;
13918                }
13919            }
13920            return true;
13921        }
13922
13923        @Override
13924        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
13925            return new PackageParser.ServiceIntentInfo[size];
13926        }
13927
13928        @Override
13929        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
13930            if (!sUserManager.exists(userId)) return true;
13931            PackageParser.Package p = filter.service.owner;
13932            if (p != null) {
13933                PackageSetting ps = (PackageSetting)p.mExtras;
13934                if (ps != null) {
13935                    // System apps are never considered stopped for purposes of
13936                    // filtering, because there may be no way for the user to
13937                    // actually re-launch them.
13938                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13939                            && ps.getStopped(userId);
13940                }
13941            }
13942            return false;
13943        }
13944
13945        @Override
13946        protected boolean isPackageForFilter(String packageName,
13947                PackageParser.ServiceIntentInfo info) {
13948            return packageName.equals(info.service.owner.packageName);
13949        }
13950
13951        @Override
13952        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
13953                int match, int userId) {
13954            if (!sUserManager.exists(userId)) return null;
13955            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
13956            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
13957                return null;
13958            }
13959            final PackageParser.Service service = info.service;
13960            PackageSetting ps = (PackageSetting) service.owner.mExtras;
13961            if (ps == null) {
13962                return null;
13963            }
13964            final PackageUserState userState = ps.readUserState(userId);
13965            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
13966                    userState, userId);
13967            if (si == null) {
13968                return null;
13969            }
13970            final boolean matchVisibleToInstantApp =
13971                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13972            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13973            // throw out filters that aren't visible to ephemeral apps
13974            if (matchVisibleToInstantApp
13975                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13976                return null;
13977            }
13978            // throw out ephemeral filters if we're not explicitly requesting them
13979            if (!isInstantApp && userState.instantApp) {
13980                return null;
13981            }
13982            // throw out instant app filters if updates are available; will trigger
13983            // instant app resolution
13984            if (userState.instantApp && ps.isUpdateAvailable()) {
13985                return null;
13986            }
13987            final ResolveInfo res = new ResolveInfo();
13988            res.serviceInfo = si;
13989            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13990                res.filter = filter;
13991            }
13992            res.priority = info.getPriority();
13993            res.preferredOrder = service.owner.mPreferredOrder;
13994            res.match = match;
13995            res.isDefault = info.hasDefault;
13996            res.labelRes = info.labelRes;
13997            res.nonLocalizedLabel = info.nonLocalizedLabel;
13998            res.icon = info.icon;
13999            res.system = res.serviceInfo.applicationInfo.isSystemApp();
14000            return res;
14001        }
14002
14003        @Override
14004        protected void sortResults(List<ResolveInfo> results) {
14005            Collections.sort(results, mResolvePrioritySorter);
14006        }
14007
14008        @Override
14009        protected void dumpFilter(PrintWriter out, String prefix,
14010                PackageParser.ServiceIntentInfo filter) {
14011            out.print(prefix); out.print(
14012                    Integer.toHexString(System.identityHashCode(filter.service)));
14013                    out.print(' ');
14014                    filter.service.printComponentShortName(out);
14015                    out.print(" filter ");
14016                    out.println(Integer.toHexString(System.identityHashCode(filter)));
14017        }
14018
14019        @Override
14020        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
14021            return filter.service;
14022        }
14023
14024        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
14025            PackageParser.Service service = (PackageParser.Service)label;
14026            out.print(prefix); out.print(
14027                    Integer.toHexString(System.identityHashCode(service)));
14028                    out.print(' ');
14029                    service.printComponentShortName(out);
14030            if (count > 1) {
14031                out.print(" ("); out.print(count); out.print(" filters)");
14032            }
14033            out.println();
14034        }
14035
14036//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
14037//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
14038//            final List<ResolveInfo> retList = Lists.newArrayList();
14039//            while (i.hasNext()) {
14040//                final ResolveInfo resolveInfo = (ResolveInfo) i;
14041//                if (isEnabledLP(resolveInfo.serviceInfo)) {
14042//                    retList.add(resolveInfo);
14043//                }
14044//            }
14045//            return retList;
14046//        }
14047
14048        // Keys are String (activity class name), values are Activity.
14049        private final ArrayMap<ComponentName, PackageParser.Service> mServices
14050                = new ArrayMap<ComponentName, PackageParser.Service>();
14051        private int mFlags;
14052    }
14053
14054    private final class ProviderIntentResolver
14055            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
14056        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
14057                boolean defaultOnly, int userId) {
14058            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
14059            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
14060        }
14061
14062        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
14063                int userId) {
14064            if (!sUserManager.exists(userId))
14065                return null;
14066            mFlags = flags;
14067            return super.queryIntent(intent, resolvedType,
14068                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
14069                    userId);
14070        }
14071
14072        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
14073                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
14074            if (!sUserManager.exists(userId))
14075                return null;
14076            if (packageProviders == null) {
14077                return null;
14078            }
14079            mFlags = flags;
14080            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
14081            final int N = packageProviders.size();
14082            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
14083                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
14084
14085            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
14086            for (int i = 0; i < N; ++i) {
14087                intentFilters = packageProviders.get(i).intents;
14088                if (intentFilters != null && intentFilters.size() > 0) {
14089                    PackageParser.ProviderIntentInfo[] array =
14090                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
14091                    intentFilters.toArray(array);
14092                    listCut.add(array);
14093                }
14094            }
14095            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
14096        }
14097
14098        public final void addProvider(PackageParser.Provider p) {
14099            if (mProviders.containsKey(p.getComponentName())) {
14100                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
14101                return;
14102            }
14103
14104            mProviders.put(p.getComponentName(), p);
14105            if (DEBUG_SHOW_INFO) {
14106                Log.v(TAG, "  "
14107                        + (p.info.nonLocalizedLabel != null
14108                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
14109                Log.v(TAG, "    Class=" + p.info.name);
14110            }
14111            final int NI = p.intents.size();
14112            int j;
14113            for (j = 0; j < NI; j++) {
14114                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
14115                if (DEBUG_SHOW_INFO) {
14116                    Log.v(TAG, "    IntentFilter:");
14117                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14118                }
14119                if (!intent.debugCheck()) {
14120                    Log.w(TAG, "==> For Provider " + p.info.name);
14121                }
14122                addFilter(intent);
14123            }
14124        }
14125
14126        public final void removeProvider(PackageParser.Provider p) {
14127            mProviders.remove(p.getComponentName());
14128            if (DEBUG_SHOW_INFO) {
14129                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
14130                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
14131                Log.v(TAG, "    Class=" + p.info.name);
14132            }
14133            final int NI = p.intents.size();
14134            int j;
14135            for (j = 0; j < NI; j++) {
14136                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
14137                if (DEBUG_SHOW_INFO) {
14138                    Log.v(TAG, "    IntentFilter:");
14139                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14140                }
14141                removeFilter(intent);
14142            }
14143        }
14144
14145        @Override
14146        protected boolean allowFilterResult(
14147                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
14148            ProviderInfo filterPi = filter.provider.info;
14149            for (int i = dest.size() - 1; i >= 0; i--) {
14150                ProviderInfo destPi = dest.get(i).providerInfo;
14151                if (destPi.name == filterPi.name
14152                        && destPi.packageName == filterPi.packageName) {
14153                    return false;
14154                }
14155            }
14156            return true;
14157        }
14158
14159        @Override
14160        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
14161            return new PackageParser.ProviderIntentInfo[size];
14162        }
14163
14164        @Override
14165        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
14166            if (!sUserManager.exists(userId))
14167                return true;
14168            PackageParser.Package p = filter.provider.owner;
14169            if (p != null) {
14170                PackageSetting ps = (PackageSetting) p.mExtras;
14171                if (ps != null) {
14172                    // System apps are never considered stopped for purposes of
14173                    // filtering, because there may be no way for the user to
14174                    // actually re-launch them.
14175                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
14176                            && ps.getStopped(userId);
14177                }
14178            }
14179            return false;
14180        }
14181
14182        @Override
14183        protected boolean isPackageForFilter(String packageName,
14184                PackageParser.ProviderIntentInfo info) {
14185            return packageName.equals(info.provider.owner.packageName);
14186        }
14187
14188        @Override
14189        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
14190                int match, int userId) {
14191            if (!sUserManager.exists(userId))
14192                return null;
14193            final PackageParser.ProviderIntentInfo info = filter;
14194            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
14195                return null;
14196            }
14197            final PackageParser.Provider provider = info.provider;
14198            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
14199            if (ps == null) {
14200                return null;
14201            }
14202            final PackageUserState userState = ps.readUserState(userId);
14203            final boolean matchVisibleToInstantApp =
14204                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
14205            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
14206            // throw out filters that aren't visible to instant applications
14207            if (matchVisibleToInstantApp
14208                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
14209                return null;
14210            }
14211            // throw out instant application filters if we're not explicitly requesting them
14212            if (!isInstantApp && userState.instantApp) {
14213                return null;
14214            }
14215            // throw out instant application filters if updates are available; will trigger
14216            // instant application resolution
14217            if (userState.instantApp && ps.isUpdateAvailable()) {
14218                return null;
14219            }
14220            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
14221                    userState, userId);
14222            if (pi == null) {
14223                return null;
14224            }
14225            final ResolveInfo res = new ResolveInfo();
14226            res.providerInfo = pi;
14227            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
14228                res.filter = filter;
14229            }
14230            res.priority = info.getPriority();
14231            res.preferredOrder = provider.owner.mPreferredOrder;
14232            res.match = match;
14233            res.isDefault = info.hasDefault;
14234            res.labelRes = info.labelRes;
14235            res.nonLocalizedLabel = info.nonLocalizedLabel;
14236            res.icon = info.icon;
14237            res.system = res.providerInfo.applicationInfo.isSystemApp();
14238            return res;
14239        }
14240
14241        @Override
14242        protected void sortResults(List<ResolveInfo> results) {
14243            Collections.sort(results, mResolvePrioritySorter);
14244        }
14245
14246        @Override
14247        protected void dumpFilter(PrintWriter out, String prefix,
14248                PackageParser.ProviderIntentInfo filter) {
14249            out.print(prefix);
14250            out.print(
14251                    Integer.toHexString(System.identityHashCode(filter.provider)));
14252            out.print(' ');
14253            filter.provider.printComponentShortName(out);
14254            out.print(" filter ");
14255            out.println(Integer.toHexString(System.identityHashCode(filter)));
14256        }
14257
14258        @Override
14259        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
14260            return filter.provider;
14261        }
14262
14263        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
14264            PackageParser.Provider provider = (PackageParser.Provider)label;
14265            out.print(prefix); out.print(
14266                    Integer.toHexString(System.identityHashCode(provider)));
14267                    out.print(' ');
14268                    provider.printComponentShortName(out);
14269            if (count > 1) {
14270                out.print(" ("); out.print(count); out.print(" filters)");
14271            }
14272            out.println();
14273        }
14274
14275        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
14276                = new ArrayMap<ComponentName, PackageParser.Provider>();
14277        private int mFlags;
14278    }
14279
14280    static final class EphemeralIntentResolver
14281            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
14282        /**
14283         * The result that has the highest defined order. Ordering applies on a
14284         * per-package basis. Mapping is from package name to Pair of order and
14285         * EphemeralResolveInfo.
14286         * <p>
14287         * NOTE: This is implemented as a field variable for convenience and efficiency.
14288         * By having a field variable, we're able to track filter ordering as soon as
14289         * a non-zero order is defined. Otherwise, multiple loops across the result set
14290         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
14291         * this needs to be contained entirely within {@link #filterResults}.
14292         */
14293        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
14294
14295        @Override
14296        protected AuxiliaryResolveInfo[] newArray(int size) {
14297            return new AuxiliaryResolveInfo[size];
14298        }
14299
14300        @Override
14301        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
14302            return true;
14303        }
14304
14305        @Override
14306        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
14307                int userId) {
14308            if (!sUserManager.exists(userId)) {
14309                return null;
14310            }
14311            final String packageName = responseObj.resolveInfo.getPackageName();
14312            final Integer order = responseObj.getOrder();
14313            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
14314                    mOrderResult.get(packageName);
14315            // ordering is enabled and this item's order isn't high enough
14316            if (lastOrderResult != null && lastOrderResult.first >= order) {
14317                return null;
14318            }
14319            final InstantAppResolveInfo res = responseObj.resolveInfo;
14320            if (order > 0) {
14321                // non-zero order, enable ordering
14322                mOrderResult.put(packageName, new Pair<>(order, res));
14323            }
14324            return responseObj;
14325        }
14326
14327        @Override
14328        protected void filterResults(List<AuxiliaryResolveInfo> results) {
14329            // only do work if ordering is enabled [most of the time it won't be]
14330            if (mOrderResult.size() == 0) {
14331                return;
14332            }
14333            int resultSize = results.size();
14334            for (int i = 0; i < resultSize; i++) {
14335                final InstantAppResolveInfo info = results.get(i).resolveInfo;
14336                final String packageName = info.getPackageName();
14337                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
14338                if (savedInfo == null) {
14339                    // package doesn't having ordering
14340                    continue;
14341                }
14342                if (savedInfo.second == info) {
14343                    // circled back to the highest ordered item; remove from order list
14344                    mOrderResult.remove(savedInfo);
14345                    if (mOrderResult.size() == 0) {
14346                        // no more ordered items
14347                        break;
14348                    }
14349                    continue;
14350                }
14351                // item has a worse order, remove it from the result list
14352                results.remove(i);
14353                resultSize--;
14354                i--;
14355            }
14356        }
14357    }
14358
14359    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
14360            new Comparator<ResolveInfo>() {
14361        public int compare(ResolveInfo r1, ResolveInfo r2) {
14362            int v1 = r1.priority;
14363            int v2 = r2.priority;
14364            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
14365            if (v1 != v2) {
14366                return (v1 > v2) ? -1 : 1;
14367            }
14368            v1 = r1.preferredOrder;
14369            v2 = r2.preferredOrder;
14370            if (v1 != v2) {
14371                return (v1 > v2) ? -1 : 1;
14372            }
14373            if (r1.isDefault != r2.isDefault) {
14374                return r1.isDefault ? -1 : 1;
14375            }
14376            v1 = r1.match;
14377            v2 = r2.match;
14378            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
14379            if (v1 != v2) {
14380                return (v1 > v2) ? -1 : 1;
14381            }
14382            if (r1.system != r2.system) {
14383                return r1.system ? -1 : 1;
14384            }
14385            if (r1.activityInfo != null) {
14386                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
14387            }
14388            if (r1.serviceInfo != null) {
14389                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
14390            }
14391            if (r1.providerInfo != null) {
14392                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
14393            }
14394            return 0;
14395        }
14396    };
14397
14398    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
14399            new Comparator<ProviderInfo>() {
14400        public int compare(ProviderInfo p1, ProviderInfo p2) {
14401            final int v1 = p1.initOrder;
14402            final int v2 = p2.initOrder;
14403            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
14404        }
14405    };
14406
14407    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
14408            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
14409            final int[] userIds) {
14410        mHandler.post(new Runnable() {
14411            @Override
14412            public void run() {
14413                try {
14414                    final IActivityManager am = ActivityManager.getService();
14415                    if (am == null) return;
14416                    final int[] resolvedUserIds;
14417                    if (userIds == null) {
14418                        resolvedUserIds = am.getRunningUserIds();
14419                    } else {
14420                        resolvedUserIds = userIds;
14421                    }
14422                    for (int id : resolvedUserIds) {
14423                        final Intent intent = new Intent(action,
14424                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
14425                        if (extras != null) {
14426                            intent.putExtras(extras);
14427                        }
14428                        if (targetPkg != null) {
14429                            intent.setPackage(targetPkg);
14430                        }
14431                        // Modify the UID when posting to other users
14432                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
14433                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
14434                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
14435                            intent.putExtra(Intent.EXTRA_UID, uid);
14436                        }
14437                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
14438                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
14439                        if (DEBUG_BROADCASTS) {
14440                            RuntimeException here = new RuntimeException("here");
14441                            here.fillInStackTrace();
14442                            Slog.d(TAG, "Sending to user " + id + ": "
14443                                    + intent.toShortString(false, true, false, false)
14444                                    + " " + intent.getExtras(), here);
14445                        }
14446                        am.broadcastIntent(null, intent, null, finishedReceiver,
14447                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
14448                                null, finishedReceiver != null, false, id);
14449                    }
14450                } catch (RemoteException ex) {
14451                }
14452            }
14453        });
14454    }
14455
14456    /**
14457     * Check if the external storage media is available. This is true if there
14458     * is a mounted external storage medium or if the external storage is
14459     * emulated.
14460     */
14461    private boolean isExternalMediaAvailable() {
14462        return mMediaMounted || Environment.isExternalStorageEmulated();
14463    }
14464
14465    @Override
14466    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
14467        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14468            return null;
14469        }
14470        // writer
14471        synchronized (mPackages) {
14472            if (!isExternalMediaAvailable()) {
14473                // If the external storage is no longer mounted at this point,
14474                // the caller may not have been able to delete all of this
14475                // packages files and can not delete any more.  Bail.
14476                return null;
14477            }
14478            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14479            if (lastPackage != null) {
14480                pkgs.remove(lastPackage);
14481            }
14482            if (pkgs.size() > 0) {
14483                return pkgs.get(0);
14484            }
14485        }
14486        return null;
14487    }
14488
14489    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14490        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14491                userId, andCode ? 1 : 0, packageName);
14492        if (mSystemReady) {
14493            msg.sendToTarget();
14494        } else {
14495            if (mPostSystemReadyMessages == null) {
14496                mPostSystemReadyMessages = new ArrayList<>();
14497            }
14498            mPostSystemReadyMessages.add(msg);
14499        }
14500    }
14501
14502    void startCleaningPackages() {
14503        // reader
14504        if (!isExternalMediaAvailable()) {
14505            return;
14506        }
14507        synchronized (mPackages) {
14508            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14509                return;
14510            }
14511        }
14512        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14513        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14514        IActivityManager am = ActivityManager.getService();
14515        if (am != null) {
14516            int dcsUid = -1;
14517            synchronized (mPackages) {
14518                if (!mDefaultContainerWhitelisted) {
14519                    mDefaultContainerWhitelisted = true;
14520                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14521                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14522                }
14523            }
14524            try {
14525                if (dcsUid > 0) {
14526                    am.backgroundWhitelistUid(dcsUid);
14527                }
14528                am.startService(null, intent, null, false, mContext.getOpPackageName(),
14529                        UserHandle.USER_SYSTEM);
14530            } catch (RemoteException e) {
14531            }
14532        }
14533    }
14534
14535    @Override
14536    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14537            int installFlags, String installerPackageName, int userId) {
14538        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14539
14540        final int callingUid = Binder.getCallingUid();
14541        enforceCrossUserPermission(callingUid, userId,
14542                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14543
14544        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14545            try {
14546                if (observer != null) {
14547                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14548                }
14549            } catch (RemoteException re) {
14550            }
14551            return;
14552        }
14553
14554        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14555            installFlags |= PackageManager.INSTALL_FROM_ADB;
14556
14557        } else {
14558            // Caller holds INSTALL_PACKAGES permission, so we're less strict
14559            // about installerPackageName.
14560
14561            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14562            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14563        }
14564
14565        UserHandle user;
14566        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14567            user = UserHandle.ALL;
14568        } else {
14569            user = new UserHandle(userId);
14570        }
14571
14572        // Only system components can circumvent runtime permissions when installing.
14573        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14574                && mContext.checkCallingOrSelfPermission(Manifest.permission
14575                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14576            throw new SecurityException("You need the "
14577                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14578                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14579        }
14580
14581        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14582                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14583            throw new IllegalArgumentException(
14584                    "New installs into ASEC containers no longer supported");
14585        }
14586
14587        final File originFile = new File(originPath);
14588        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14589
14590        final Message msg = mHandler.obtainMessage(INIT_COPY);
14591        final VerificationInfo verificationInfo = new VerificationInfo(
14592                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14593        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14594                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14595                null /*packageAbiOverride*/, null /*grantedPermissions*/,
14596                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14597        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14598        msg.obj = params;
14599
14600        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14601                System.identityHashCode(msg.obj));
14602        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14603                System.identityHashCode(msg.obj));
14604
14605        mHandler.sendMessage(msg);
14606    }
14607
14608
14609    /**
14610     * Ensure that the install reason matches what we know about the package installer (e.g. whether
14611     * it is acting on behalf on an enterprise or the user).
14612     *
14613     * Note that the ordering of the conditionals in this method is important. The checks we perform
14614     * are as follows, in this order:
14615     *
14616     * 1) If the install is being performed by a system app, we can trust the app to have set the
14617     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14618     *    what it is.
14619     * 2) If the install is being performed by a device or profile owner app, the install reason
14620     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14621     *    set the install reason correctly. If the app targets an older SDK version where install
14622     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14623     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14624     * 3) In all other cases, the install is being performed by a regular app that is neither part
14625     *    of the system nor a device or profile owner. We have no reason to believe that this app is
14626     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14627     *    set to enterprise policy and if so, change it to unknown instead.
14628     */
14629    private int fixUpInstallReason(String installerPackageName, int installerUid,
14630            int installReason) {
14631        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14632                == PERMISSION_GRANTED) {
14633            // If the install is being performed by a system app, we trust that app to have set the
14634            // install reason correctly.
14635            return installReason;
14636        }
14637
14638        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14639            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14640        if (dpm != null) {
14641            ComponentName owner = null;
14642            try {
14643                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14644                if (owner == null) {
14645                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14646                }
14647            } catch (RemoteException e) {
14648            }
14649            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14650                // If the install is being performed by a device or profile owner, the install
14651                // reason should be enterprise policy.
14652                return PackageManager.INSTALL_REASON_POLICY;
14653            }
14654        }
14655
14656        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14657            // If the install is being performed by a regular app (i.e. neither system app nor
14658            // device or profile owner), we have no reason to believe that the app is acting on
14659            // behalf of an enterprise. If the app set the install reason to enterprise policy,
14660            // change it to unknown instead.
14661            return PackageManager.INSTALL_REASON_UNKNOWN;
14662        }
14663
14664        // If the install is being performed by a regular app and the install reason was set to any
14665        // value but enterprise policy, leave the install reason unchanged.
14666        return installReason;
14667    }
14668
14669    void installStage(String packageName, File stagedDir, String stagedCid,
14670            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14671            String installerPackageName, int installerUid, UserHandle user,
14672            Certificate[][] certificates) {
14673        if (DEBUG_EPHEMERAL) {
14674            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14675                Slog.d(TAG, "Ephemeral install of " + packageName);
14676            }
14677        }
14678        final VerificationInfo verificationInfo = new VerificationInfo(
14679                sessionParams.originatingUri, sessionParams.referrerUri,
14680                sessionParams.originatingUid, installerUid);
14681
14682        final OriginInfo origin;
14683        if (stagedDir != null) {
14684            origin = OriginInfo.fromStagedFile(stagedDir);
14685        } else {
14686            origin = OriginInfo.fromStagedContainer(stagedCid);
14687        }
14688
14689        final Message msg = mHandler.obtainMessage(INIT_COPY);
14690        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14691                sessionParams.installReason);
14692        final InstallParams params = new InstallParams(origin, null, observer,
14693                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14694                verificationInfo, user, sessionParams.abiOverride,
14695                sessionParams.grantedRuntimePermissions, certificates, installReason);
14696        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14697        msg.obj = params;
14698
14699        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14700                System.identityHashCode(msg.obj));
14701        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14702                System.identityHashCode(msg.obj));
14703
14704        mHandler.sendMessage(msg);
14705    }
14706
14707    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14708            int userId) {
14709        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14710        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
14711                false /*startReceiver*/, pkgSetting.appId, userId);
14712
14713        // Send a session commit broadcast
14714        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14715        info.installReason = pkgSetting.getInstallReason(userId);
14716        info.appPackageName = packageName;
14717        sendSessionCommitBroadcast(info, userId);
14718    }
14719
14720    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
14721            boolean includeStopped, int appId, int... userIds) {
14722        if (ArrayUtils.isEmpty(userIds)) {
14723            return;
14724        }
14725        Bundle extras = new Bundle(1);
14726        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14727        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14728
14729        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14730                packageName, extras, 0, null, null, userIds);
14731        if (sendBootCompleted) {
14732            mHandler.post(() -> {
14733                        for (int userId : userIds) {
14734                            sendBootCompletedBroadcastToSystemApp(
14735                                    packageName, includeStopped, userId);
14736                        }
14737                    }
14738            );
14739        }
14740    }
14741
14742    /**
14743     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14744     * automatically without needing an explicit launch.
14745     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14746     */
14747    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
14748            int userId) {
14749        // If user is not running, the app didn't miss any broadcast
14750        if (!mUserManagerInternal.isUserRunning(userId)) {
14751            return;
14752        }
14753        final IActivityManager am = ActivityManager.getService();
14754        try {
14755            // Deliver LOCKED_BOOT_COMPLETED first
14756            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14757                    .setPackage(packageName);
14758            if (includeStopped) {
14759                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14760            }
14761            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14762            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14763                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14764
14765            // Deliver BOOT_COMPLETED only if user is unlocked
14766            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14767                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14768                if (includeStopped) {
14769                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14770                }
14771                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14772                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14773            }
14774        } catch (RemoteException e) {
14775            throw e.rethrowFromSystemServer();
14776        }
14777    }
14778
14779    @Override
14780    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14781            int userId) {
14782        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14783        PackageSetting pkgSetting;
14784        final int callingUid = Binder.getCallingUid();
14785        enforceCrossUserPermission(callingUid, userId,
14786                true /* requireFullPermission */, true /* checkShell */,
14787                "setApplicationHiddenSetting for user " + userId);
14788
14789        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14790            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14791            return false;
14792        }
14793
14794        long callingId = Binder.clearCallingIdentity();
14795        try {
14796            boolean sendAdded = false;
14797            boolean sendRemoved = false;
14798            // writer
14799            synchronized (mPackages) {
14800                pkgSetting = mSettings.mPackages.get(packageName);
14801                if (pkgSetting == null) {
14802                    return false;
14803                }
14804                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14805                    return false;
14806                }
14807                // Do not allow "android" is being disabled
14808                if ("android".equals(packageName)) {
14809                    Slog.w(TAG, "Cannot hide package: android");
14810                    return false;
14811                }
14812                // Cannot hide static shared libs as they are considered
14813                // a part of the using app (emulating static linking). Also
14814                // static libs are installed always on internal storage.
14815                PackageParser.Package pkg = mPackages.get(packageName);
14816                if (pkg != null && pkg.staticSharedLibName != null) {
14817                    Slog.w(TAG, "Cannot hide package: " + packageName
14818                            + " providing static shared library: "
14819                            + pkg.staticSharedLibName);
14820                    return false;
14821                }
14822                // Only allow protected packages to hide themselves.
14823                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14824                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14825                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14826                    return false;
14827                }
14828
14829                if (pkgSetting.getHidden(userId) != hidden) {
14830                    pkgSetting.setHidden(hidden, userId);
14831                    mSettings.writePackageRestrictionsLPr(userId);
14832                    if (hidden) {
14833                        sendRemoved = true;
14834                    } else {
14835                        sendAdded = true;
14836                    }
14837                }
14838            }
14839            if (sendAdded) {
14840                sendPackageAddedForUser(packageName, pkgSetting, userId);
14841                return true;
14842            }
14843            if (sendRemoved) {
14844                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14845                        "hiding pkg");
14846                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14847                return true;
14848            }
14849        } finally {
14850            Binder.restoreCallingIdentity(callingId);
14851        }
14852        return false;
14853    }
14854
14855    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14856            int userId) {
14857        final PackageRemovedInfo info = new PackageRemovedInfo(this);
14858        info.removedPackage = packageName;
14859        info.installerPackageName = pkgSetting.installerPackageName;
14860        info.removedUsers = new int[] {userId};
14861        info.broadcastUsers = new int[] {userId};
14862        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14863        info.sendPackageRemovedBroadcasts(true /*killApp*/);
14864    }
14865
14866    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14867        if (pkgList.length > 0) {
14868            Bundle extras = new Bundle(1);
14869            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14870
14871            sendPackageBroadcast(
14872                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14873                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
14874                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14875                    new int[] {userId});
14876        }
14877    }
14878
14879    /**
14880     * Returns true if application is not found or there was an error. Otherwise it returns
14881     * the hidden state of the package for the given user.
14882     */
14883    @Override
14884    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14885        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14886        final int callingUid = Binder.getCallingUid();
14887        enforceCrossUserPermission(callingUid, userId,
14888                true /* requireFullPermission */, false /* checkShell */,
14889                "getApplicationHidden for user " + userId);
14890        PackageSetting ps;
14891        long callingId = Binder.clearCallingIdentity();
14892        try {
14893            // writer
14894            synchronized (mPackages) {
14895                ps = mSettings.mPackages.get(packageName);
14896                if (ps == null) {
14897                    return true;
14898                }
14899                if (filterAppAccessLPr(ps, callingUid, userId)) {
14900                    return true;
14901                }
14902                return ps.getHidden(userId);
14903            }
14904        } finally {
14905            Binder.restoreCallingIdentity(callingId);
14906        }
14907    }
14908
14909    /**
14910     * @hide
14911     */
14912    @Override
14913    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
14914            int installReason) {
14915        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
14916                null);
14917        PackageSetting pkgSetting;
14918        final int callingUid = Binder.getCallingUid();
14919        enforceCrossUserPermission(callingUid, userId,
14920                true /* requireFullPermission */, true /* checkShell */,
14921                "installExistingPackage for user " + userId);
14922        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14923            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
14924        }
14925
14926        long callingId = Binder.clearCallingIdentity();
14927        try {
14928            boolean installed = false;
14929            final boolean instantApp =
14930                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14931            final boolean fullApp =
14932                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
14933
14934            // writer
14935            synchronized (mPackages) {
14936                pkgSetting = mSettings.mPackages.get(packageName);
14937                if (pkgSetting == null) {
14938                    return PackageManager.INSTALL_FAILED_INVALID_URI;
14939                }
14940                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
14941                    // only allow the existing package to be used if it's installed as a full
14942                    // application for at least one user
14943                    boolean installAllowed = false;
14944                    for (int checkUserId : sUserManager.getUserIds()) {
14945                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
14946                        if (installAllowed) {
14947                            break;
14948                        }
14949                    }
14950                    if (!installAllowed) {
14951                        return PackageManager.INSTALL_FAILED_INVALID_URI;
14952                    }
14953                }
14954                if (!pkgSetting.getInstalled(userId)) {
14955                    pkgSetting.setInstalled(true, userId);
14956                    pkgSetting.setHidden(false, userId);
14957                    pkgSetting.setInstallReason(installReason, userId);
14958                    mSettings.writePackageRestrictionsLPr(userId);
14959                    mSettings.writeKernelMappingLPr(pkgSetting);
14960                    installed = true;
14961                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14962                    // upgrade app from instant to full; we don't allow app downgrade
14963                    installed = true;
14964                }
14965                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
14966            }
14967
14968            if (installed) {
14969                if (pkgSetting.pkg != null) {
14970                    synchronized (mInstallLock) {
14971                        // We don't need to freeze for a brand new install
14972                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
14973                    }
14974                }
14975                sendPackageAddedForUser(packageName, pkgSetting, userId);
14976                synchronized (mPackages) {
14977                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
14978                }
14979            }
14980        } finally {
14981            Binder.restoreCallingIdentity(callingId);
14982        }
14983
14984        return PackageManager.INSTALL_SUCCEEDED;
14985    }
14986
14987    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
14988            boolean instantApp, boolean fullApp) {
14989        // no state specified; do nothing
14990        if (!instantApp && !fullApp) {
14991            return;
14992        }
14993        if (userId != UserHandle.USER_ALL) {
14994            if (instantApp && !pkgSetting.getInstantApp(userId)) {
14995                pkgSetting.setInstantApp(true /*instantApp*/, userId);
14996            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14997                pkgSetting.setInstantApp(false /*instantApp*/, userId);
14998            }
14999        } else {
15000            for (int currentUserId : sUserManager.getUserIds()) {
15001                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
15002                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
15003                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
15004                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
15005                }
15006            }
15007        }
15008    }
15009
15010    boolean isUserRestricted(int userId, String restrictionKey) {
15011        Bundle restrictions = sUserManager.getUserRestrictions(userId);
15012        if (restrictions.getBoolean(restrictionKey, false)) {
15013            Log.w(TAG, "User is restricted: " + restrictionKey);
15014            return true;
15015        }
15016        return false;
15017    }
15018
15019    @Override
15020    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
15021            int userId) {
15022        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
15023        final int callingUid = Binder.getCallingUid();
15024        enforceCrossUserPermission(callingUid, userId,
15025                true /* requireFullPermission */, true /* checkShell */,
15026                "setPackagesSuspended for user " + userId);
15027
15028        if (ArrayUtils.isEmpty(packageNames)) {
15029            return packageNames;
15030        }
15031
15032        // List of package names for whom the suspended state has changed.
15033        List<String> changedPackages = new ArrayList<>(packageNames.length);
15034        // List of package names for whom the suspended state is not set as requested in this
15035        // method.
15036        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
15037        long callingId = Binder.clearCallingIdentity();
15038        try {
15039            for (int i = 0; i < packageNames.length; i++) {
15040                String packageName = packageNames[i];
15041                boolean changed = false;
15042                final int appId;
15043                synchronized (mPackages) {
15044                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
15045                    if (pkgSetting == null
15046                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
15047                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
15048                                + "\". Skipping suspending/un-suspending.");
15049                        unactionedPackages.add(packageName);
15050                        continue;
15051                    }
15052                    appId = pkgSetting.appId;
15053                    if (pkgSetting.getSuspended(userId) != suspended) {
15054                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
15055                            unactionedPackages.add(packageName);
15056                            continue;
15057                        }
15058                        pkgSetting.setSuspended(suspended, userId);
15059                        mSettings.writePackageRestrictionsLPr(userId);
15060                        changed = true;
15061                        changedPackages.add(packageName);
15062                    }
15063                }
15064
15065                if (changed && suspended) {
15066                    killApplication(packageName, UserHandle.getUid(userId, appId),
15067                            "suspending package");
15068                }
15069            }
15070        } finally {
15071            Binder.restoreCallingIdentity(callingId);
15072        }
15073
15074        if (!changedPackages.isEmpty()) {
15075            sendPackagesSuspendedForUser(changedPackages.toArray(
15076                    new String[changedPackages.size()]), userId, suspended);
15077        }
15078
15079        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
15080    }
15081
15082    @Override
15083    public boolean isPackageSuspendedForUser(String packageName, int userId) {
15084        final int callingUid = Binder.getCallingUid();
15085        enforceCrossUserPermission(callingUid, userId,
15086                true /* requireFullPermission */, false /* checkShell */,
15087                "isPackageSuspendedForUser for user " + userId);
15088        synchronized (mPackages) {
15089            final PackageSetting ps = mSettings.mPackages.get(packageName);
15090            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
15091                throw new IllegalArgumentException("Unknown target package: " + packageName);
15092            }
15093            return ps.getSuspended(userId);
15094        }
15095    }
15096
15097    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
15098        if (isPackageDeviceAdmin(packageName, userId)) {
15099            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15100                    + "\": has an active device admin");
15101            return false;
15102        }
15103
15104        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
15105        if (packageName.equals(activeLauncherPackageName)) {
15106            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15107                    + "\": contains the active launcher");
15108            return false;
15109        }
15110
15111        if (packageName.equals(mRequiredInstallerPackage)) {
15112            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15113                    + "\": required for package installation");
15114            return false;
15115        }
15116
15117        if (packageName.equals(mRequiredUninstallerPackage)) {
15118            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15119                    + "\": required for package uninstallation");
15120            return false;
15121        }
15122
15123        if (packageName.equals(mRequiredVerifierPackage)) {
15124            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15125                    + "\": required for package verification");
15126            return false;
15127        }
15128
15129        if (packageName.equals(getDefaultDialerPackageName(userId))) {
15130            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15131                    + "\": is the default dialer");
15132            return false;
15133        }
15134
15135        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
15136            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15137                    + "\": protected package");
15138            return false;
15139        }
15140
15141        // Cannot suspend static shared libs as they are considered
15142        // a part of the using app (emulating static linking). Also
15143        // static libs are installed always on internal storage.
15144        PackageParser.Package pkg = mPackages.get(packageName);
15145        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
15146            Slog.w(TAG, "Cannot suspend package: " + packageName
15147                    + " providing static shared library: "
15148                    + pkg.staticSharedLibName);
15149            return false;
15150        }
15151
15152        return true;
15153    }
15154
15155    private String getActiveLauncherPackageName(int userId) {
15156        Intent intent = new Intent(Intent.ACTION_MAIN);
15157        intent.addCategory(Intent.CATEGORY_HOME);
15158        ResolveInfo resolveInfo = resolveIntent(
15159                intent,
15160                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
15161                PackageManager.MATCH_DEFAULT_ONLY,
15162                userId);
15163
15164        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
15165    }
15166
15167    private String getDefaultDialerPackageName(int userId) {
15168        synchronized (mPackages) {
15169            return mSettings.getDefaultDialerPackageNameLPw(userId);
15170        }
15171    }
15172
15173    @Override
15174    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
15175        mContext.enforceCallingOrSelfPermission(
15176                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15177                "Only package verification agents can verify applications");
15178
15179        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
15180        final PackageVerificationResponse response = new PackageVerificationResponse(
15181                verificationCode, Binder.getCallingUid());
15182        msg.arg1 = id;
15183        msg.obj = response;
15184        mHandler.sendMessage(msg);
15185    }
15186
15187    @Override
15188    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
15189            long millisecondsToDelay) {
15190        mContext.enforceCallingOrSelfPermission(
15191                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15192                "Only package verification agents can extend verification timeouts");
15193
15194        final PackageVerificationState state = mPendingVerification.get(id);
15195        final PackageVerificationResponse response = new PackageVerificationResponse(
15196                verificationCodeAtTimeout, Binder.getCallingUid());
15197
15198        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
15199            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
15200        }
15201        if (millisecondsToDelay < 0) {
15202            millisecondsToDelay = 0;
15203        }
15204        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
15205                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
15206            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
15207        }
15208
15209        if ((state != null) && !state.timeoutExtended()) {
15210            state.extendTimeout();
15211
15212            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
15213            msg.arg1 = id;
15214            msg.obj = response;
15215            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
15216        }
15217    }
15218
15219    private void broadcastPackageVerified(int verificationId, Uri packageUri,
15220            int verificationCode, UserHandle user) {
15221        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
15222        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
15223        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15224        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15225        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
15226
15227        mContext.sendBroadcastAsUser(intent, user,
15228                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
15229    }
15230
15231    private ComponentName matchComponentForVerifier(String packageName,
15232            List<ResolveInfo> receivers) {
15233        ActivityInfo targetReceiver = null;
15234
15235        final int NR = receivers.size();
15236        for (int i = 0; i < NR; i++) {
15237            final ResolveInfo info = receivers.get(i);
15238            if (info.activityInfo == null) {
15239                continue;
15240            }
15241
15242            if (packageName.equals(info.activityInfo.packageName)) {
15243                targetReceiver = info.activityInfo;
15244                break;
15245            }
15246        }
15247
15248        if (targetReceiver == null) {
15249            return null;
15250        }
15251
15252        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
15253    }
15254
15255    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
15256            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
15257        if (pkgInfo.verifiers.length == 0) {
15258            return null;
15259        }
15260
15261        final int N = pkgInfo.verifiers.length;
15262        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
15263        for (int i = 0; i < N; i++) {
15264            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
15265
15266            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
15267                    receivers);
15268            if (comp == null) {
15269                continue;
15270            }
15271
15272            final int verifierUid = getUidForVerifier(verifierInfo);
15273            if (verifierUid == -1) {
15274                continue;
15275            }
15276
15277            if (DEBUG_VERIFY) {
15278                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
15279                        + " with the correct signature");
15280            }
15281            sufficientVerifiers.add(comp);
15282            verificationState.addSufficientVerifier(verifierUid);
15283        }
15284
15285        return sufficientVerifiers;
15286    }
15287
15288    private int getUidForVerifier(VerifierInfo verifierInfo) {
15289        synchronized (mPackages) {
15290            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
15291            if (pkg == null) {
15292                return -1;
15293            } else if (pkg.mSignatures.length != 1) {
15294                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15295                        + " has more than one signature; ignoring");
15296                return -1;
15297            }
15298
15299            /*
15300             * If the public key of the package's signature does not match
15301             * our expected public key, then this is a different package and
15302             * we should skip.
15303             */
15304
15305            final byte[] expectedPublicKey;
15306            try {
15307                final Signature verifierSig = pkg.mSignatures[0];
15308                final PublicKey publicKey = verifierSig.getPublicKey();
15309                expectedPublicKey = publicKey.getEncoded();
15310            } catch (CertificateException e) {
15311                return -1;
15312            }
15313
15314            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
15315
15316            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
15317                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15318                        + " does not have the expected public key; ignoring");
15319                return -1;
15320            }
15321
15322            return pkg.applicationInfo.uid;
15323        }
15324    }
15325
15326    @Override
15327    public void finishPackageInstall(int token, boolean didLaunch) {
15328        enforceSystemOrRoot("Only the system is allowed to finish installs");
15329
15330        if (DEBUG_INSTALL) {
15331            Slog.v(TAG, "BM finishing package install for " + token);
15332        }
15333        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15334
15335        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
15336        mHandler.sendMessage(msg);
15337    }
15338
15339    /**
15340     * Get the verification agent timeout.  Used for both the APK verifier and the
15341     * intent filter verifier.
15342     *
15343     * @return verification timeout in milliseconds
15344     */
15345    private long getVerificationTimeout() {
15346        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
15347                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
15348                DEFAULT_VERIFICATION_TIMEOUT);
15349    }
15350
15351    /**
15352     * Get the default verification agent response code.
15353     *
15354     * @return default verification response code
15355     */
15356    private int getDefaultVerificationResponse(UserHandle user) {
15357        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
15358            return PackageManager.VERIFICATION_REJECT;
15359        }
15360        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15361                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
15362                DEFAULT_VERIFICATION_RESPONSE);
15363    }
15364
15365    /**
15366     * Check whether or not package verification has been enabled.
15367     *
15368     * @return true if verification should be performed
15369     */
15370    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
15371        if (!DEFAULT_VERIFY_ENABLE) {
15372            return false;
15373        }
15374
15375        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
15376
15377        // Check if installing from ADB
15378        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
15379            // Do not run verification in a test harness environment
15380            if (ActivityManager.isRunningInTestHarness()) {
15381                return false;
15382            }
15383            if (ensureVerifyAppsEnabled) {
15384                return true;
15385            }
15386            // Check if the developer does not want package verification for ADB installs
15387            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15388                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
15389                return false;
15390            }
15391        } else {
15392            // only when not installed from ADB, skip verification for instant apps when
15393            // the installer and verifier are the same.
15394            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
15395                if (mInstantAppInstallerActivity != null
15396                        && mInstantAppInstallerActivity.packageName.equals(
15397                                mRequiredVerifierPackage)) {
15398                    try {
15399                        mContext.getSystemService(AppOpsManager.class)
15400                                .checkPackage(installerUid, mRequiredVerifierPackage);
15401                        if (DEBUG_VERIFY) {
15402                            Slog.i(TAG, "disable verification for instant app");
15403                        }
15404                        return false;
15405                    } catch (SecurityException ignore) { }
15406                }
15407            }
15408        }
15409
15410        if (ensureVerifyAppsEnabled) {
15411            return true;
15412        }
15413
15414        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15415                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
15416    }
15417
15418    @Override
15419    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
15420            throws RemoteException {
15421        mContext.enforceCallingOrSelfPermission(
15422                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
15423                "Only intentfilter verification agents can verify applications");
15424
15425        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
15426        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
15427                Binder.getCallingUid(), verificationCode, failedDomains);
15428        msg.arg1 = id;
15429        msg.obj = response;
15430        mHandler.sendMessage(msg);
15431    }
15432
15433    @Override
15434    public int getIntentVerificationStatus(String packageName, int userId) {
15435        final int callingUid = Binder.getCallingUid();
15436        if (UserHandle.getUserId(callingUid) != userId) {
15437            mContext.enforceCallingOrSelfPermission(
15438                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15439                    "getIntentVerificationStatus" + userId);
15440        }
15441        if (getInstantAppPackageName(callingUid) != null) {
15442            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15443        }
15444        synchronized (mPackages) {
15445            final PackageSetting ps = mSettings.mPackages.get(packageName);
15446            if (ps == null
15447                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15448                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15449            }
15450            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
15451        }
15452    }
15453
15454    @Override
15455    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
15456        mContext.enforceCallingOrSelfPermission(
15457                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15458
15459        boolean result = false;
15460        synchronized (mPackages) {
15461            final PackageSetting ps = mSettings.mPackages.get(packageName);
15462            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15463                return false;
15464            }
15465            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
15466        }
15467        if (result) {
15468            scheduleWritePackageRestrictionsLocked(userId);
15469        }
15470        return result;
15471    }
15472
15473    @Override
15474    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
15475            String packageName) {
15476        final int callingUid = Binder.getCallingUid();
15477        if (getInstantAppPackageName(callingUid) != null) {
15478            return ParceledListSlice.emptyList();
15479        }
15480        synchronized (mPackages) {
15481            final PackageSetting ps = mSettings.mPackages.get(packageName);
15482            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15483                return ParceledListSlice.emptyList();
15484            }
15485            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
15486        }
15487    }
15488
15489    @Override
15490    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
15491        if (TextUtils.isEmpty(packageName)) {
15492            return ParceledListSlice.emptyList();
15493        }
15494        final int callingUid = Binder.getCallingUid();
15495        final int callingUserId = UserHandle.getUserId(callingUid);
15496        synchronized (mPackages) {
15497            PackageParser.Package pkg = mPackages.get(packageName);
15498            if (pkg == null || pkg.activities == null) {
15499                return ParceledListSlice.emptyList();
15500            }
15501            if (pkg.mExtras == null) {
15502                return ParceledListSlice.emptyList();
15503            }
15504            final PackageSetting ps = (PackageSetting) pkg.mExtras;
15505            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15506                return ParceledListSlice.emptyList();
15507            }
15508            final int count = pkg.activities.size();
15509            ArrayList<IntentFilter> result = new ArrayList<>();
15510            for (int n=0; n<count; n++) {
15511                PackageParser.Activity activity = pkg.activities.get(n);
15512                if (activity.intents != null && activity.intents.size() > 0) {
15513                    result.addAll(activity.intents);
15514                }
15515            }
15516            return new ParceledListSlice<>(result);
15517        }
15518    }
15519
15520    @Override
15521    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15522        mContext.enforceCallingOrSelfPermission(
15523                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15524        if (UserHandle.getCallingUserId() != userId) {
15525            mContext.enforceCallingOrSelfPermission(
15526                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15527        }
15528
15529        synchronized (mPackages) {
15530            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15531            if (packageName != null) {
15532                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
15533                        packageName, userId);
15534            }
15535            return result;
15536        }
15537    }
15538
15539    @Override
15540    public String getDefaultBrowserPackageName(int userId) {
15541        if (UserHandle.getCallingUserId() != userId) {
15542            mContext.enforceCallingOrSelfPermission(
15543                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15544        }
15545        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15546            return null;
15547        }
15548        synchronized (mPackages) {
15549            return mSettings.getDefaultBrowserPackageNameLPw(userId);
15550        }
15551    }
15552
15553    /**
15554     * Get the "allow unknown sources" setting.
15555     *
15556     * @return the current "allow unknown sources" setting
15557     */
15558    private int getUnknownSourcesSettings() {
15559        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15560                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15561                -1);
15562    }
15563
15564    @Override
15565    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15566        final int callingUid = Binder.getCallingUid();
15567        if (getInstantAppPackageName(callingUid) != null) {
15568            return;
15569        }
15570        // writer
15571        synchronized (mPackages) {
15572            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15573            if (targetPackageSetting == null
15574                    || filterAppAccessLPr(
15575                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15576                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15577            }
15578
15579            PackageSetting installerPackageSetting;
15580            if (installerPackageName != null) {
15581                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15582                if (installerPackageSetting == null) {
15583                    throw new IllegalArgumentException("Unknown installer package: "
15584                            + installerPackageName);
15585                }
15586            } else {
15587                installerPackageSetting = null;
15588            }
15589
15590            Signature[] callerSignature;
15591            Object obj = mSettings.getUserIdLPr(callingUid);
15592            if (obj != null) {
15593                if (obj instanceof SharedUserSetting) {
15594                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15595                } else if (obj instanceof PackageSetting) {
15596                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15597                } else {
15598                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15599                }
15600            } else {
15601                throw new SecurityException("Unknown calling UID: " + callingUid);
15602            }
15603
15604            // Verify: can't set installerPackageName to a package that is
15605            // not signed with the same cert as the caller.
15606            if (installerPackageSetting != null) {
15607                if (compareSignatures(callerSignature,
15608                        installerPackageSetting.signatures.mSignatures)
15609                        != PackageManager.SIGNATURE_MATCH) {
15610                    throw new SecurityException(
15611                            "Caller does not have same cert as new installer package "
15612                            + installerPackageName);
15613                }
15614            }
15615
15616            // Verify: if target already has an installer package, it must
15617            // be signed with the same cert as the caller.
15618            if (targetPackageSetting.installerPackageName != null) {
15619                PackageSetting setting = mSettings.mPackages.get(
15620                        targetPackageSetting.installerPackageName);
15621                // If the currently set package isn't valid, then it's always
15622                // okay to change it.
15623                if (setting != null) {
15624                    if (compareSignatures(callerSignature,
15625                            setting.signatures.mSignatures)
15626                            != PackageManager.SIGNATURE_MATCH) {
15627                        throw new SecurityException(
15628                                "Caller does not have same cert as old installer package "
15629                                + targetPackageSetting.installerPackageName);
15630                    }
15631                }
15632            }
15633
15634            // Okay!
15635            targetPackageSetting.installerPackageName = installerPackageName;
15636            if (installerPackageName != null) {
15637                mSettings.mInstallerPackages.add(installerPackageName);
15638            }
15639            scheduleWriteSettingsLocked();
15640        }
15641    }
15642
15643    @Override
15644    public void setApplicationCategoryHint(String packageName, int categoryHint,
15645            String callerPackageName) {
15646        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15647            throw new SecurityException("Instant applications don't have access to this method");
15648        }
15649        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15650                callerPackageName);
15651        synchronized (mPackages) {
15652            PackageSetting ps = mSettings.mPackages.get(packageName);
15653            if (ps == null) {
15654                throw new IllegalArgumentException("Unknown target package " + packageName);
15655            }
15656            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15657                throw new IllegalArgumentException("Unknown target package " + packageName);
15658            }
15659            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15660                throw new IllegalArgumentException("Calling package " + callerPackageName
15661                        + " is not installer for " + packageName);
15662            }
15663
15664            if (ps.categoryHint != categoryHint) {
15665                ps.categoryHint = categoryHint;
15666                scheduleWriteSettingsLocked();
15667            }
15668        }
15669    }
15670
15671    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15672        // Queue up an async operation since the package installation may take a little while.
15673        mHandler.post(new Runnable() {
15674            public void run() {
15675                mHandler.removeCallbacks(this);
15676                 // Result object to be returned
15677                PackageInstalledInfo res = new PackageInstalledInfo();
15678                res.setReturnCode(currentStatus);
15679                res.uid = -1;
15680                res.pkg = null;
15681                res.removedInfo = null;
15682                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15683                    args.doPreInstall(res.returnCode);
15684                    synchronized (mInstallLock) {
15685                        installPackageTracedLI(args, res);
15686                    }
15687                    args.doPostInstall(res.returnCode, res.uid);
15688                }
15689
15690                // A restore should be performed at this point if (a) the install
15691                // succeeded, (b) the operation is not an update, and (c) the new
15692                // package has not opted out of backup participation.
15693                final boolean update = res.removedInfo != null
15694                        && res.removedInfo.removedPackage != null;
15695                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15696                boolean doRestore = !update
15697                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15698
15699                // Set up the post-install work request bookkeeping.  This will be used
15700                // and cleaned up by the post-install event handling regardless of whether
15701                // there's a restore pass performed.  Token values are >= 1.
15702                int token;
15703                if (mNextInstallToken < 0) mNextInstallToken = 1;
15704                token = mNextInstallToken++;
15705
15706                PostInstallData data = new PostInstallData(args, res);
15707                mRunningInstalls.put(token, data);
15708                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15709
15710                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15711                    // Pass responsibility to the Backup Manager.  It will perform a
15712                    // restore if appropriate, then pass responsibility back to the
15713                    // Package Manager to run the post-install observer callbacks
15714                    // and broadcasts.
15715                    IBackupManager bm = IBackupManager.Stub.asInterface(
15716                            ServiceManager.getService(Context.BACKUP_SERVICE));
15717                    if (bm != null) {
15718                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15719                                + " to BM for possible restore");
15720                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15721                        try {
15722                            // TODO: http://b/22388012
15723                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15724                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15725                            } else {
15726                                doRestore = false;
15727                            }
15728                        } catch (RemoteException e) {
15729                            // can't happen; the backup manager is local
15730                        } catch (Exception e) {
15731                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15732                            doRestore = false;
15733                        }
15734                    } else {
15735                        Slog.e(TAG, "Backup Manager not found!");
15736                        doRestore = false;
15737                    }
15738                }
15739
15740                if (!doRestore) {
15741                    // No restore possible, or the Backup Manager was mysteriously not
15742                    // available -- just fire the post-install work request directly.
15743                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15744
15745                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15746
15747                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15748                    mHandler.sendMessage(msg);
15749                }
15750            }
15751        });
15752    }
15753
15754    /**
15755     * Callback from PackageSettings whenever an app is first transitioned out of the
15756     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15757     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15758     * here whether the app is the target of an ongoing install, and only send the
15759     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15760     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15761     * handling.
15762     */
15763    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15764        // Serialize this with the rest of the install-process message chain.  In the
15765        // restore-at-install case, this Runnable will necessarily run before the
15766        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15767        // are coherent.  In the non-restore case, the app has already completed install
15768        // and been launched through some other means, so it is not in a problematic
15769        // state for observers to see the FIRST_LAUNCH signal.
15770        mHandler.post(new Runnable() {
15771            @Override
15772            public void run() {
15773                for (int i = 0; i < mRunningInstalls.size(); i++) {
15774                    final PostInstallData data = mRunningInstalls.valueAt(i);
15775                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15776                        continue;
15777                    }
15778                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15779                        // right package; but is it for the right user?
15780                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15781                            if (userId == data.res.newUsers[uIndex]) {
15782                                if (DEBUG_BACKUP) {
15783                                    Slog.i(TAG, "Package " + pkgName
15784                                            + " being restored so deferring FIRST_LAUNCH");
15785                                }
15786                                return;
15787                            }
15788                        }
15789                    }
15790                }
15791                // didn't find it, so not being restored
15792                if (DEBUG_BACKUP) {
15793                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15794                }
15795                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15796            }
15797        });
15798    }
15799
15800    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15801        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15802                installerPkg, null, userIds);
15803    }
15804
15805    private abstract class HandlerParams {
15806        private static final int MAX_RETRIES = 4;
15807
15808        /**
15809         * Number of times startCopy() has been attempted and had a non-fatal
15810         * error.
15811         */
15812        private int mRetries = 0;
15813
15814        /** User handle for the user requesting the information or installation. */
15815        private final UserHandle mUser;
15816        String traceMethod;
15817        int traceCookie;
15818
15819        HandlerParams(UserHandle user) {
15820            mUser = user;
15821        }
15822
15823        UserHandle getUser() {
15824            return mUser;
15825        }
15826
15827        HandlerParams setTraceMethod(String traceMethod) {
15828            this.traceMethod = traceMethod;
15829            return this;
15830        }
15831
15832        HandlerParams setTraceCookie(int traceCookie) {
15833            this.traceCookie = traceCookie;
15834            return this;
15835        }
15836
15837        final boolean startCopy() {
15838            boolean res;
15839            try {
15840                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15841
15842                if (++mRetries > MAX_RETRIES) {
15843                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15844                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15845                    handleServiceError();
15846                    return false;
15847                } else {
15848                    handleStartCopy();
15849                    res = true;
15850                }
15851            } catch (RemoteException e) {
15852                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15853                mHandler.sendEmptyMessage(MCS_RECONNECT);
15854                res = false;
15855            }
15856            handleReturnCode();
15857            return res;
15858        }
15859
15860        final void serviceError() {
15861            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15862            handleServiceError();
15863            handleReturnCode();
15864        }
15865
15866        abstract void handleStartCopy() throws RemoteException;
15867        abstract void handleServiceError();
15868        abstract void handleReturnCode();
15869    }
15870
15871    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15872        for (File path : paths) {
15873            try {
15874                mcs.clearDirectory(path.getAbsolutePath());
15875            } catch (RemoteException e) {
15876            }
15877        }
15878    }
15879
15880    static class OriginInfo {
15881        /**
15882         * Location where install is coming from, before it has been
15883         * copied/renamed into place. This could be a single monolithic APK
15884         * file, or a cluster directory. This location may be untrusted.
15885         */
15886        final File file;
15887        final String cid;
15888
15889        /**
15890         * Flag indicating that {@link #file} or {@link #cid} has already been
15891         * staged, meaning downstream users don't need to defensively copy the
15892         * contents.
15893         */
15894        final boolean staged;
15895
15896        /**
15897         * Flag indicating that {@link #file} or {@link #cid} is an already
15898         * installed app that is being moved.
15899         */
15900        final boolean existing;
15901
15902        final String resolvedPath;
15903        final File resolvedFile;
15904
15905        static OriginInfo fromNothing() {
15906            return new OriginInfo(null, null, false, false);
15907        }
15908
15909        static OriginInfo fromUntrustedFile(File file) {
15910            return new OriginInfo(file, null, false, false);
15911        }
15912
15913        static OriginInfo fromExistingFile(File file) {
15914            return new OriginInfo(file, null, false, true);
15915        }
15916
15917        static OriginInfo fromStagedFile(File file) {
15918            return new OriginInfo(file, null, true, false);
15919        }
15920
15921        static OriginInfo fromStagedContainer(String cid) {
15922            return new OriginInfo(null, cid, true, false);
15923        }
15924
15925        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
15926            this.file = file;
15927            this.cid = cid;
15928            this.staged = staged;
15929            this.existing = existing;
15930
15931            if (cid != null) {
15932                resolvedPath = PackageHelper.getSdDir(cid);
15933                resolvedFile = new File(resolvedPath);
15934            } else if (file != null) {
15935                resolvedPath = file.getAbsolutePath();
15936                resolvedFile = file;
15937            } else {
15938                resolvedPath = null;
15939                resolvedFile = null;
15940            }
15941        }
15942    }
15943
15944    static class MoveInfo {
15945        final int moveId;
15946        final String fromUuid;
15947        final String toUuid;
15948        final String packageName;
15949        final String dataAppName;
15950        final int appId;
15951        final String seinfo;
15952        final int targetSdkVersion;
15953
15954        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15955                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15956            this.moveId = moveId;
15957            this.fromUuid = fromUuid;
15958            this.toUuid = toUuid;
15959            this.packageName = packageName;
15960            this.dataAppName = dataAppName;
15961            this.appId = appId;
15962            this.seinfo = seinfo;
15963            this.targetSdkVersion = targetSdkVersion;
15964        }
15965    }
15966
15967    static class VerificationInfo {
15968        /** A constant used to indicate that a uid value is not present. */
15969        public static final int NO_UID = -1;
15970
15971        /** URI referencing where the package was downloaded from. */
15972        final Uri originatingUri;
15973
15974        /** HTTP referrer URI associated with the originatingURI. */
15975        final Uri referrer;
15976
15977        /** UID of the application that the install request originated from. */
15978        final int originatingUid;
15979
15980        /** UID of application requesting the install */
15981        final int installerUid;
15982
15983        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15984            this.originatingUri = originatingUri;
15985            this.referrer = referrer;
15986            this.originatingUid = originatingUid;
15987            this.installerUid = installerUid;
15988        }
15989    }
15990
15991    class InstallParams extends HandlerParams {
15992        final OriginInfo origin;
15993        final MoveInfo move;
15994        final IPackageInstallObserver2 observer;
15995        int installFlags;
15996        final String installerPackageName;
15997        final String volumeUuid;
15998        private InstallArgs mArgs;
15999        private int mRet;
16000        final String packageAbiOverride;
16001        final String[] grantedRuntimePermissions;
16002        final VerificationInfo verificationInfo;
16003        final Certificate[][] certificates;
16004        final int installReason;
16005
16006        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16007                int installFlags, String installerPackageName, String volumeUuid,
16008                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
16009                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
16010            super(user);
16011            this.origin = origin;
16012            this.move = move;
16013            this.observer = observer;
16014            this.installFlags = installFlags;
16015            this.installerPackageName = installerPackageName;
16016            this.volumeUuid = volumeUuid;
16017            this.verificationInfo = verificationInfo;
16018            this.packageAbiOverride = packageAbiOverride;
16019            this.grantedRuntimePermissions = grantedPermissions;
16020            this.certificates = certificates;
16021            this.installReason = installReason;
16022        }
16023
16024        @Override
16025        public String toString() {
16026            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
16027                    + " file=" + origin.file + " cid=" + origin.cid + "}";
16028        }
16029
16030        private int installLocationPolicy(PackageInfoLite pkgLite) {
16031            String packageName = pkgLite.packageName;
16032            int installLocation = pkgLite.installLocation;
16033            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16034            // reader
16035            synchronized (mPackages) {
16036                // Currently installed package which the new package is attempting to replace or
16037                // null if no such package is installed.
16038                PackageParser.Package installedPkg = mPackages.get(packageName);
16039                // Package which currently owns the data which the new package will own if installed.
16040                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
16041                // will be null whereas dataOwnerPkg will contain information about the package
16042                // which was uninstalled while keeping its data.
16043                PackageParser.Package dataOwnerPkg = installedPkg;
16044                if (dataOwnerPkg  == null) {
16045                    PackageSetting ps = mSettings.mPackages.get(packageName);
16046                    if (ps != null) {
16047                        dataOwnerPkg = ps.pkg;
16048                    }
16049                }
16050
16051                if (dataOwnerPkg != null) {
16052                    // If installed, the package will get access to data left on the device by its
16053                    // predecessor. As a security measure, this is permited only if this is not a
16054                    // version downgrade or if the predecessor package is marked as debuggable and
16055                    // a downgrade is explicitly requested.
16056                    //
16057                    // On debuggable platform builds, downgrades are permitted even for
16058                    // non-debuggable packages to make testing easier. Debuggable platform builds do
16059                    // not offer security guarantees and thus it's OK to disable some security
16060                    // mechanisms to make debugging/testing easier on those builds. However, even on
16061                    // debuggable builds downgrades of packages are permitted only if requested via
16062                    // installFlags. This is because we aim to keep the behavior of debuggable
16063                    // platform builds as close as possible to the behavior of non-debuggable
16064                    // platform builds.
16065                    final boolean downgradeRequested =
16066                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
16067                    final boolean packageDebuggable =
16068                                (dataOwnerPkg.applicationInfo.flags
16069                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
16070                    final boolean downgradePermitted =
16071                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
16072                    if (!downgradePermitted) {
16073                        try {
16074                            checkDowngrade(dataOwnerPkg, pkgLite);
16075                        } catch (PackageManagerException e) {
16076                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
16077                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
16078                        }
16079                    }
16080                }
16081
16082                if (installedPkg != null) {
16083                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16084                        // Check for updated system application.
16085                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16086                            if (onSd) {
16087                                Slog.w(TAG, "Cannot install update to system app on sdcard");
16088                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
16089                            }
16090                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16091                        } else {
16092                            if (onSd) {
16093                                // Install flag overrides everything.
16094                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16095                            }
16096                            // If current upgrade specifies particular preference
16097                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
16098                                // Application explicitly specified internal.
16099                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16100                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
16101                                // App explictly prefers external. Let policy decide
16102                            } else {
16103                                // Prefer previous location
16104                                if (isExternal(installedPkg)) {
16105                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16106                                }
16107                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16108                            }
16109                        }
16110                    } else {
16111                        // Invalid install. Return error code
16112                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
16113                    }
16114                }
16115            }
16116            // All the special cases have been taken care of.
16117            // Return result based on recommended install location.
16118            if (onSd) {
16119                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16120            }
16121            return pkgLite.recommendedInstallLocation;
16122        }
16123
16124        /*
16125         * Invoke remote method to get package information and install
16126         * location values. Override install location based on default
16127         * policy if needed and then create install arguments based
16128         * on the install location.
16129         */
16130        public void handleStartCopy() throws RemoteException {
16131            int ret = PackageManager.INSTALL_SUCCEEDED;
16132
16133            // If we're already staged, we've firmly committed to an install location
16134            if (origin.staged) {
16135                if (origin.file != null) {
16136                    installFlags |= PackageManager.INSTALL_INTERNAL;
16137                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
16138                } else if (origin.cid != null) {
16139                    installFlags |= PackageManager.INSTALL_EXTERNAL;
16140                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
16141                } else {
16142                    throw new IllegalStateException("Invalid stage location");
16143                }
16144            }
16145
16146            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16147            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
16148            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16149            PackageInfoLite pkgLite = null;
16150
16151            if (onInt && onSd) {
16152                // Check if both bits are set.
16153                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
16154                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16155            } else if (onSd && ephemeral) {
16156                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
16157                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16158            } else {
16159                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
16160                        packageAbiOverride);
16161
16162                if (DEBUG_EPHEMERAL && ephemeral) {
16163                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
16164                }
16165
16166                /*
16167                 * If we have too little free space, try to free cache
16168                 * before giving up.
16169                 */
16170                if (!origin.staged && pkgLite.recommendedInstallLocation
16171                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
16172                    // TODO: focus freeing disk space on the target device
16173                    final StorageManager storage = StorageManager.from(mContext);
16174                    final long lowThreshold = storage.getStorageLowBytes(
16175                            Environment.getDataDirectory());
16176
16177                    final long sizeBytes = mContainerService.calculateInstalledSize(
16178                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
16179
16180                    try {
16181                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
16182                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
16183                                installFlags, packageAbiOverride);
16184                    } catch (InstallerException e) {
16185                        Slog.w(TAG, "Failed to free cache", e);
16186                    }
16187
16188                    /*
16189                     * The cache free must have deleted the file we
16190                     * downloaded to install.
16191                     *
16192                     * TODO: fix the "freeCache" call to not delete
16193                     *       the file we care about.
16194                     */
16195                    if (pkgLite.recommendedInstallLocation
16196                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
16197                        pkgLite.recommendedInstallLocation
16198                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
16199                    }
16200                }
16201            }
16202
16203            if (ret == PackageManager.INSTALL_SUCCEEDED) {
16204                int loc = pkgLite.recommendedInstallLocation;
16205                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
16206                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16207                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
16208                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
16209                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
16210                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16211                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
16212                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
16213                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
16214                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
16215                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
16216                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
16217                } else {
16218                    // Override with defaults if needed.
16219                    loc = installLocationPolicy(pkgLite);
16220                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
16221                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
16222                    } else if (!onSd && !onInt) {
16223                        // Override install location with flags
16224                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
16225                            // Set the flag to install on external media.
16226                            installFlags |= PackageManager.INSTALL_EXTERNAL;
16227                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
16228                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
16229                            if (DEBUG_EPHEMERAL) {
16230                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
16231                            }
16232                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
16233                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
16234                                    |PackageManager.INSTALL_INTERNAL);
16235                        } else {
16236                            // Make sure the flag for installing on external
16237                            // media is unset
16238                            installFlags |= PackageManager.INSTALL_INTERNAL;
16239                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
16240                        }
16241                    }
16242                }
16243            }
16244
16245            final InstallArgs args = createInstallArgs(this);
16246            mArgs = args;
16247
16248            if (ret == PackageManager.INSTALL_SUCCEEDED) {
16249                // TODO: http://b/22976637
16250                // Apps installed for "all" users use the device owner to verify the app
16251                UserHandle verifierUser = getUser();
16252                if (verifierUser == UserHandle.ALL) {
16253                    verifierUser = UserHandle.SYSTEM;
16254                }
16255
16256                /*
16257                 * Determine if we have any installed package verifiers. If we
16258                 * do, then we'll defer to them to verify the packages.
16259                 */
16260                final int requiredUid = mRequiredVerifierPackage == null ? -1
16261                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
16262                                verifierUser.getIdentifier());
16263                final int installerUid =
16264                        verificationInfo == null ? -1 : verificationInfo.installerUid;
16265                if (!origin.existing && requiredUid != -1
16266                        && isVerificationEnabled(
16267                                verifierUser.getIdentifier(), installFlags, installerUid)) {
16268                    final Intent verification = new Intent(
16269                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
16270                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
16271                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
16272                            PACKAGE_MIME_TYPE);
16273                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
16274
16275                    // Query all live verifiers based on current user state
16276                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
16277                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
16278                            false /*allowDynamicSplits*/);
16279
16280                    if (DEBUG_VERIFY) {
16281                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
16282                                + verification.toString() + " with " + pkgLite.verifiers.length
16283                                + " optional verifiers");
16284                    }
16285
16286                    final int verificationId = mPendingVerificationToken++;
16287
16288                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
16289
16290                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
16291                            installerPackageName);
16292
16293                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
16294                            installFlags);
16295
16296                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
16297                            pkgLite.packageName);
16298
16299                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
16300                            pkgLite.versionCode);
16301
16302                    if (verificationInfo != null) {
16303                        if (verificationInfo.originatingUri != null) {
16304                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
16305                                    verificationInfo.originatingUri);
16306                        }
16307                        if (verificationInfo.referrer != null) {
16308                            verification.putExtra(Intent.EXTRA_REFERRER,
16309                                    verificationInfo.referrer);
16310                        }
16311                        if (verificationInfo.originatingUid >= 0) {
16312                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
16313                                    verificationInfo.originatingUid);
16314                        }
16315                        if (verificationInfo.installerUid >= 0) {
16316                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
16317                                    verificationInfo.installerUid);
16318                        }
16319                    }
16320
16321                    final PackageVerificationState verificationState = new PackageVerificationState(
16322                            requiredUid, args);
16323
16324                    mPendingVerification.append(verificationId, verificationState);
16325
16326                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
16327                            receivers, verificationState);
16328
16329                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
16330                    final long idleDuration = getVerificationTimeout();
16331
16332                    /*
16333                     * If any sufficient verifiers were listed in the package
16334                     * manifest, attempt to ask them.
16335                     */
16336                    if (sufficientVerifiers != null) {
16337                        final int N = sufficientVerifiers.size();
16338                        if (N == 0) {
16339                            Slog.i(TAG, "Additional verifiers required, but none installed.");
16340                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
16341                        } else {
16342                            for (int i = 0; i < N; i++) {
16343                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
16344                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16345                                        verifierComponent.getPackageName(), idleDuration,
16346                                        verifierUser.getIdentifier(), false, "package verifier");
16347
16348                                final Intent sufficientIntent = new Intent(verification);
16349                                sufficientIntent.setComponent(verifierComponent);
16350                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
16351                            }
16352                        }
16353                    }
16354
16355                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
16356                            mRequiredVerifierPackage, receivers);
16357                    if (ret == PackageManager.INSTALL_SUCCEEDED
16358                            && mRequiredVerifierPackage != null) {
16359                        Trace.asyncTraceBegin(
16360                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
16361                        /*
16362                         * Send the intent to the required verification agent,
16363                         * but only start the verification timeout after the
16364                         * target BroadcastReceivers have run.
16365                         */
16366                        verification.setComponent(requiredVerifierComponent);
16367                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16368                                mRequiredVerifierPackage, idleDuration,
16369                                verifierUser.getIdentifier(), false, "package verifier");
16370                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
16371                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16372                                new BroadcastReceiver() {
16373                                    @Override
16374                                    public void onReceive(Context context, Intent intent) {
16375                                        final Message msg = mHandler
16376                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
16377                                        msg.arg1 = verificationId;
16378                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
16379                                    }
16380                                }, null, 0, null, null);
16381
16382                        /*
16383                         * We don't want the copy to proceed until verification
16384                         * succeeds, so null out this field.
16385                         */
16386                        mArgs = null;
16387                    }
16388                } else {
16389                    /*
16390                     * No package verification is enabled, so immediately start
16391                     * the remote call to initiate copy using temporary file.
16392                     */
16393                    ret = args.copyApk(mContainerService, true);
16394                }
16395            }
16396
16397            mRet = ret;
16398        }
16399
16400        @Override
16401        void handleReturnCode() {
16402            // If mArgs is null, then MCS couldn't be reached. When it
16403            // reconnects, it will try again to install. At that point, this
16404            // will succeed.
16405            if (mArgs != null) {
16406                processPendingInstall(mArgs, mRet);
16407            }
16408        }
16409
16410        @Override
16411        void handleServiceError() {
16412            mArgs = createInstallArgs(this);
16413            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16414        }
16415
16416        public boolean isForwardLocked() {
16417            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16418        }
16419    }
16420
16421    /**
16422     * Used during creation of InstallArgs
16423     *
16424     * @param installFlags package installation flags
16425     * @return true if should be installed on external storage
16426     */
16427    private static boolean installOnExternalAsec(int installFlags) {
16428        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
16429            return false;
16430        }
16431        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
16432            return true;
16433        }
16434        return false;
16435    }
16436
16437    /**
16438     * Used during creation of InstallArgs
16439     *
16440     * @param installFlags package installation flags
16441     * @return true if should be installed as forward locked
16442     */
16443    private static boolean installForwardLocked(int installFlags) {
16444        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16445    }
16446
16447    private InstallArgs createInstallArgs(InstallParams params) {
16448        if (params.move != null) {
16449            return new MoveInstallArgs(params);
16450        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
16451            return new AsecInstallArgs(params);
16452        } else {
16453            return new FileInstallArgs(params);
16454        }
16455    }
16456
16457    /**
16458     * Create args that describe an existing installed package. Typically used
16459     * when cleaning up old installs, or used as a move source.
16460     */
16461    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
16462            String resourcePath, String[] instructionSets) {
16463        final boolean isInAsec;
16464        if (installOnExternalAsec(installFlags)) {
16465            /* Apps on SD card are always in ASEC containers. */
16466            isInAsec = true;
16467        } else if (installForwardLocked(installFlags)
16468                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
16469            /*
16470             * Forward-locked apps are only in ASEC containers if they're the
16471             * new style
16472             */
16473            isInAsec = true;
16474        } else {
16475            isInAsec = false;
16476        }
16477
16478        if (isInAsec) {
16479            return new AsecInstallArgs(codePath, instructionSets,
16480                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
16481        } else {
16482            return new FileInstallArgs(codePath, resourcePath, instructionSets);
16483        }
16484    }
16485
16486    static abstract class InstallArgs {
16487        /** @see InstallParams#origin */
16488        final OriginInfo origin;
16489        /** @see InstallParams#move */
16490        final MoveInfo move;
16491
16492        final IPackageInstallObserver2 observer;
16493        // Always refers to PackageManager flags only
16494        final int installFlags;
16495        final String installerPackageName;
16496        final String volumeUuid;
16497        final UserHandle user;
16498        final String abiOverride;
16499        final String[] installGrantPermissions;
16500        /** If non-null, drop an async trace when the install completes */
16501        final String traceMethod;
16502        final int traceCookie;
16503        final Certificate[][] certificates;
16504        final int installReason;
16505
16506        // The list of instruction sets supported by this app. This is currently
16507        // only used during the rmdex() phase to clean up resources. We can get rid of this
16508        // if we move dex files under the common app path.
16509        /* nullable */ String[] instructionSets;
16510
16511        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16512                int installFlags, String installerPackageName, String volumeUuid,
16513                UserHandle user, String[] instructionSets,
16514                String abiOverride, String[] installGrantPermissions,
16515                String traceMethod, int traceCookie, Certificate[][] certificates,
16516                int installReason) {
16517            this.origin = origin;
16518            this.move = move;
16519            this.installFlags = installFlags;
16520            this.observer = observer;
16521            this.installerPackageName = installerPackageName;
16522            this.volumeUuid = volumeUuid;
16523            this.user = user;
16524            this.instructionSets = instructionSets;
16525            this.abiOverride = abiOverride;
16526            this.installGrantPermissions = installGrantPermissions;
16527            this.traceMethod = traceMethod;
16528            this.traceCookie = traceCookie;
16529            this.certificates = certificates;
16530            this.installReason = installReason;
16531        }
16532
16533        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16534        abstract int doPreInstall(int status);
16535
16536        /**
16537         * Rename package into final resting place. All paths on the given
16538         * scanned package should be updated to reflect the rename.
16539         */
16540        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16541        abstract int doPostInstall(int status, int uid);
16542
16543        /** @see PackageSettingBase#codePathString */
16544        abstract String getCodePath();
16545        /** @see PackageSettingBase#resourcePathString */
16546        abstract String getResourcePath();
16547
16548        // Need installer lock especially for dex file removal.
16549        abstract void cleanUpResourcesLI();
16550        abstract boolean doPostDeleteLI(boolean delete);
16551
16552        /**
16553         * Called before the source arguments are copied. This is used mostly
16554         * for MoveParams when it needs to read the source file to put it in the
16555         * destination.
16556         */
16557        int doPreCopy() {
16558            return PackageManager.INSTALL_SUCCEEDED;
16559        }
16560
16561        /**
16562         * Called after the source arguments are copied. This is used mostly for
16563         * MoveParams when it needs to read the source file to put it in the
16564         * destination.
16565         */
16566        int doPostCopy(int uid) {
16567            return PackageManager.INSTALL_SUCCEEDED;
16568        }
16569
16570        protected boolean isFwdLocked() {
16571            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16572        }
16573
16574        protected boolean isExternalAsec() {
16575            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16576        }
16577
16578        protected boolean isEphemeral() {
16579            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16580        }
16581
16582        UserHandle getUser() {
16583            return user;
16584        }
16585    }
16586
16587    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16588        if (!allCodePaths.isEmpty()) {
16589            if (instructionSets == null) {
16590                throw new IllegalStateException("instructionSet == null");
16591            }
16592            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16593            for (String codePath : allCodePaths) {
16594                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16595                    try {
16596                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
16597                    } catch (InstallerException ignored) {
16598                    }
16599                }
16600            }
16601        }
16602    }
16603
16604    /**
16605     * Logic to handle installation of non-ASEC applications, including copying
16606     * and renaming logic.
16607     */
16608    class FileInstallArgs extends InstallArgs {
16609        private File codeFile;
16610        private File resourceFile;
16611
16612        // Example topology:
16613        // /data/app/com.example/base.apk
16614        // /data/app/com.example/split_foo.apk
16615        // /data/app/com.example/lib/arm/libfoo.so
16616        // /data/app/com.example/lib/arm64/libfoo.so
16617        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16618
16619        /** New install */
16620        FileInstallArgs(InstallParams params) {
16621            super(params.origin, params.move, params.observer, params.installFlags,
16622                    params.installerPackageName, params.volumeUuid,
16623                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16624                    params.grantedRuntimePermissions,
16625                    params.traceMethod, params.traceCookie, params.certificates,
16626                    params.installReason);
16627            if (isFwdLocked()) {
16628                throw new IllegalArgumentException("Forward locking only supported in ASEC");
16629            }
16630        }
16631
16632        /** Existing install */
16633        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16634            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16635                    null, null, null, 0, null /*certificates*/,
16636                    PackageManager.INSTALL_REASON_UNKNOWN);
16637            this.codeFile = (codePath != null) ? new File(codePath) : null;
16638            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16639        }
16640
16641        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16642            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16643            try {
16644                return doCopyApk(imcs, temp);
16645            } finally {
16646                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16647            }
16648        }
16649
16650        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16651            if (origin.staged) {
16652                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16653                codeFile = origin.file;
16654                resourceFile = origin.file;
16655                return PackageManager.INSTALL_SUCCEEDED;
16656            }
16657
16658            try {
16659                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16660                final File tempDir =
16661                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16662                codeFile = tempDir;
16663                resourceFile = tempDir;
16664            } catch (IOException e) {
16665                Slog.w(TAG, "Failed to create copy file: " + e);
16666                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16667            }
16668
16669            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16670                @Override
16671                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16672                    if (!FileUtils.isValidExtFilename(name)) {
16673                        throw new IllegalArgumentException("Invalid filename: " + name);
16674                    }
16675                    try {
16676                        final File file = new File(codeFile, name);
16677                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16678                                O_RDWR | O_CREAT, 0644);
16679                        Os.chmod(file.getAbsolutePath(), 0644);
16680                        return new ParcelFileDescriptor(fd);
16681                    } catch (ErrnoException e) {
16682                        throw new RemoteException("Failed to open: " + e.getMessage());
16683                    }
16684                }
16685            };
16686
16687            int ret = PackageManager.INSTALL_SUCCEEDED;
16688            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16689            if (ret != PackageManager.INSTALL_SUCCEEDED) {
16690                Slog.e(TAG, "Failed to copy package");
16691                return ret;
16692            }
16693
16694            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16695            NativeLibraryHelper.Handle handle = null;
16696            try {
16697                handle = NativeLibraryHelper.Handle.create(codeFile);
16698                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16699                        abiOverride);
16700            } catch (IOException e) {
16701                Slog.e(TAG, "Copying native libraries failed", e);
16702                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16703            } finally {
16704                IoUtils.closeQuietly(handle);
16705            }
16706
16707            return ret;
16708        }
16709
16710        int doPreInstall(int status) {
16711            if (status != PackageManager.INSTALL_SUCCEEDED) {
16712                cleanUp();
16713            }
16714            return status;
16715        }
16716
16717        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16718            if (status != PackageManager.INSTALL_SUCCEEDED) {
16719                cleanUp();
16720                return false;
16721            }
16722
16723            final File targetDir = codeFile.getParentFile();
16724            final File beforeCodeFile = codeFile;
16725            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16726
16727            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16728            try {
16729                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16730            } catch (ErrnoException e) {
16731                Slog.w(TAG, "Failed to rename", e);
16732                return false;
16733            }
16734
16735            if (!SELinux.restoreconRecursive(afterCodeFile)) {
16736                Slog.w(TAG, "Failed to restorecon");
16737                return false;
16738            }
16739
16740            // Reflect the rename internally
16741            codeFile = afterCodeFile;
16742            resourceFile = afterCodeFile;
16743
16744            // Reflect the rename in scanned details
16745            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16746            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16747                    afterCodeFile, pkg.baseCodePath));
16748            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16749                    afterCodeFile, pkg.splitCodePaths));
16750
16751            // Reflect the rename in app info
16752            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16753            pkg.setApplicationInfoCodePath(pkg.codePath);
16754            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16755            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16756            pkg.setApplicationInfoResourcePath(pkg.codePath);
16757            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16758            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16759
16760            return true;
16761        }
16762
16763        int doPostInstall(int status, int uid) {
16764            if (status != PackageManager.INSTALL_SUCCEEDED) {
16765                cleanUp();
16766            }
16767            return status;
16768        }
16769
16770        @Override
16771        String getCodePath() {
16772            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16773        }
16774
16775        @Override
16776        String getResourcePath() {
16777            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16778        }
16779
16780        private boolean cleanUp() {
16781            if (codeFile == null || !codeFile.exists()) {
16782                return false;
16783            }
16784
16785            removeCodePathLI(codeFile);
16786
16787            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16788                resourceFile.delete();
16789            }
16790
16791            return true;
16792        }
16793
16794        void cleanUpResourcesLI() {
16795            // Try enumerating all code paths before deleting
16796            List<String> allCodePaths = Collections.EMPTY_LIST;
16797            if (codeFile != null && codeFile.exists()) {
16798                try {
16799                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16800                    allCodePaths = pkg.getAllCodePaths();
16801                } catch (PackageParserException e) {
16802                    // Ignored; we tried our best
16803                }
16804            }
16805
16806            cleanUp();
16807            removeDexFiles(allCodePaths, instructionSets);
16808        }
16809
16810        boolean doPostDeleteLI(boolean delete) {
16811            // XXX err, shouldn't we respect the delete flag?
16812            cleanUpResourcesLI();
16813            return true;
16814        }
16815    }
16816
16817    private boolean isAsecExternal(String cid) {
16818        final String asecPath = PackageHelper.getSdFilesystem(cid);
16819        return !asecPath.startsWith(mAsecInternalPath);
16820    }
16821
16822    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16823            PackageManagerException {
16824        if (copyRet < 0) {
16825            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16826                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16827                throw new PackageManagerException(copyRet, message);
16828            }
16829        }
16830    }
16831
16832    /**
16833     * Extract the StorageManagerService "container ID" from the full code path of an
16834     * .apk.
16835     */
16836    static String cidFromCodePath(String fullCodePath) {
16837        int eidx = fullCodePath.lastIndexOf("/");
16838        String subStr1 = fullCodePath.substring(0, eidx);
16839        int sidx = subStr1.lastIndexOf("/");
16840        return subStr1.substring(sidx+1, eidx);
16841    }
16842
16843    /**
16844     * Logic to handle installation of ASEC applications, including copying and
16845     * renaming logic.
16846     */
16847    class AsecInstallArgs extends InstallArgs {
16848        static final String RES_FILE_NAME = "pkg.apk";
16849        static final String PUBLIC_RES_FILE_NAME = "res.zip";
16850
16851        String cid;
16852        String packagePath;
16853        String resourcePath;
16854
16855        /** New install */
16856        AsecInstallArgs(InstallParams params) {
16857            super(params.origin, params.move, params.observer, params.installFlags,
16858                    params.installerPackageName, params.volumeUuid,
16859                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16860                    params.grantedRuntimePermissions,
16861                    params.traceMethod, params.traceCookie, params.certificates,
16862                    params.installReason);
16863        }
16864
16865        /** Existing install */
16866        AsecInstallArgs(String fullCodePath, String[] instructionSets,
16867                        boolean isExternal, boolean isForwardLocked) {
16868            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
16869                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16870                    instructionSets, null, null, null, 0, null /*certificates*/,
16871                    PackageManager.INSTALL_REASON_UNKNOWN);
16872            // Hackily pretend we're still looking at a full code path
16873            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
16874                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
16875            }
16876
16877            // Extract cid from fullCodePath
16878            int eidx = fullCodePath.lastIndexOf("/");
16879            String subStr1 = fullCodePath.substring(0, eidx);
16880            int sidx = subStr1.lastIndexOf("/");
16881            cid = subStr1.substring(sidx+1, eidx);
16882            setMountPath(subStr1);
16883        }
16884
16885        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
16886            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
16887                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16888                    instructionSets, null, null, null, 0, null /*certificates*/,
16889                    PackageManager.INSTALL_REASON_UNKNOWN);
16890            this.cid = cid;
16891            setMountPath(PackageHelper.getSdDir(cid));
16892        }
16893
16894        void createCopyFile() {
16895            cid = mInstallerService.allocateExternalStageCidLegacy();
16896        }
16897
16898        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16899            if (origin.staged && origin.cid != null) {
16900                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
16901                cid = origin.cid;
16902                setMountPath(PackageHelper.getSdDir(cid));
16903                return PackageManager.INSTALL_SUCCEEDED;
16904            }
16905
16906            if (temp) {
16907                createCopyFile();
16908            } else {
16909                /*
16910                 * Pre-emptively destroy the container since it's destroyed if
16911                 * copying fails due to it existing anyway.
16912                 */
16913                PackageHelper.destroySdDir(cid);
16914            }
16915
16916            final String newMountPath = imcs.copyPackageToContainer(
16917                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
16918                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
16919
16920            if (newMountPath != null) {
16921                setMountPath(newMountPath);
16922                return PackageManager.INSTALL_SUCCEEDED;
16923            } else {
16924                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16925            }
16926        }
16927
16928        @Override
16929        String getCodePath() {
16930            return packagePath;
16931        }
16932
16933        @Override
16934        String getResourcePath() {
16935            return resourcePath;
16936        }
16937
16938        int doPreInstall(int status) {
16939            if (status != PackageManager.INSTALL_SUCCEEDED) {
16940                // Destroy container
16941                PackageHelper.destroySdDir(cid);
16942            } else {
16943                boolean mounted = PackageHelper.isContainerMounted(cid);
16944                if (!mounted) {
16945                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
16946                            Process.SYSTEM_UID);
16947                    if (newMountPath != null) {
16948                        setMountPath(newMountPath);
16949                    } else {
16950                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16951                    }
16952                }
16953            }
16954            return status;
16955        }
16956
16957        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16958            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
16959            String newMountPath = null;
16960            if (PackageHelper.isContainerMounted(cid)) {
16961                // Unmount the container
16962                if (!PackageHelper.unMountSdDir(cid)) {
16963                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
16964                    return false;
16965                }
16966            }
16967            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16968                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
16969                        " which might be stale. Will try to clean up.");
16970                // Clean up the stale container and proceed to recreate.
16971                if (!PackageHelper.destroySdDir(newCacheId)) {
16972                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
16973                    return false;
16974                }
16975                // Successfully cleaned up stale container. Try to rename again.
16976                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16977                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
16978                            + " inspite of cleaning it up.");
16979                    return false;
16980                }
16981            }
16982            if (!PackageHelper.isContainerMounted(newCacheId)) {
16983                Slog.w(TAG, "Mounting container " + newCacheId);
16984                newMountPath = PackageHelper.mountSdDir(newCacheId,
16985                        getEncryptKey(), Process.SYSTEM_UID);
16986            } else {
16987                newMountPath = PackageHelper.getSdDir(newCacheId);
16988            }
16989            if (newMountPath == null) {
16990                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
16991                return false;
16992            }
16993            Log.i(TAG, "Succesfully renamed " + cid +
16994                    " to " + newCacheId +
16995                    " at new path: " + newMountPath);
16996            cid = newCacheId;
16997
16998            final File beforeCodeFile = new File(packagePath);
16999            setMountPath(newMountPath);
17000            final File afterCodeFile = new File(packagePath);
17001
17002            // Reflect the rename in scanned details
17003            pkg.setCodePath(afterCodeFile.getAbsolutePath());
17004            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
17005                    afterCodeFile, pkg.baseCodePath));
17006            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
17007                    afterCodeFile, pkg.splitCodePaths));
17008
17009            // Reflect the rename in app info
17010            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
17011            pkg.setApplicationInfoCodePath(pkg.codePath);
17012            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
17013            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
17014            pkg.setApplicationInfoResourcePath(pkg.codePath);
17015            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
17016            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
17017
17018            return true;
17019        }
17020
17021        private void setMountPath(String mountPath) {
17022            final File mountFile = new File(mountPath);
17023
17024            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
17025            if (monolithicFile.exists()) {
17026                packagePath = monolithicFile.getAbsolutePath();
17027                if (isFwdLocked()) {
17028                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
17029                } else {
17030                    resourcePath = packagePath;
17031                }
17032            } else {
17033                packagePath = mountFile.getAbsolutePath();
17034                resourcePath = packagePath;
17035            }
17036        }
17037
17038        int doPostInstall(int status, int uid) {
17039            if (status != PackageManager.INSTALL_SUCCEEDED) {
17040                cleanUp();
17041            } else {
17042                final int groupOwner;
17043                final String protectedFile;
17044                if (isFwdLocked()) {
17045                    groupOwner = UserHandle.getSharedAppGid(uid);
17046                    protectedFile = RES_FILE_NAME;
17047                } else {
17048                    groupOwner = -1;
17049                    protectedFile = null;
17050                }
17051
17052                if (uid < Process.FIRST_APPLICATION_UID
17053                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
17054                    Slog.e(TAG, "Failed to finalize " + cid);
17055                    PackageHelper.destroySdDir(cid);
17056                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17057                }
17058
17059                boolean mounted = PackageHelper.isContainerMounted(cid);
17060                if (!mounted) {
17061                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
17062                }
17063            }
17064            return status;
17065        }
17066
17067        private void cleanUp() {
17068            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
17069
17070            // Destroy secure container
17071            PackageHelper.destroySdDir(cid);
17072        }
17073
17074        private List<String> getAllCodePaths() {
17075            final File codeFile = new File(getCodePath());
17076            if (codeFile != null && codeFile.exists()) {
17077                try {
17078                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
17079                    return pkg.getAllCodePaths();
17080                } catch (PackageParserException e) {
17081                    // Ignored; we tried our best
17082                }
17083            }
17084            return Collections.EMPTY_LIST;
17085        }
17086
17087        void cleanUpResourcesLI() {
17088            // Enumerate all code paths before deleting
17089            cleanUpResourcesLI(getAllCodePaths());
17090        }
17091
17092        private void cleanUpResourcesLI(List<String> allCodePaths) {
17093            cleanUp();
17094            removeDexFiles(allCodePaths, instructionSets);
17095        }
17096
17097        String getPackageName() {
17098            return getAsecPackageName(cid);
17099        }
17100
17101        boolean doPostDeleteLI(boolean delete) {
17102            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
17103            final List<String> allCodePaths = getAllCodePaths();
17104            boolean mounted = PackageHelper.isContainerMounted(cid);
17105            if (mounted) {
17106                // Unmount first
17107                if (PackageHelper.unMountSdDir(cid)) {
17108                    mounted = false;
17109                }
17110            }
17111            if (!mounted && delete) {
17112                cleanUpResourcesLI(allCodePaths);
17113            }
17114            return !mounted;
17115        }
17116
17117        @Override
17118        int doPreCopy() {
17119            if (isFwdLocked()) {
17120                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
17121                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
17122                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17123                }
17124            }
17125
17126            return PackageManager.INSTALL_SUCCEEDED;
17127        }
17128
17129        @Override
17130        int doPostCopy(int uid) {
17131            if (isFwdLocked()) {
17132                if (uid < Process.FIRST_APPLICATION_UID
17133                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
17134                                RES_FILE_NAME)) {
17135                    Slog.e(TAG, "Failed to finalize " + cid);
17136                    PackageHelper.destroySdDir(cid);
17137                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17138                }
17139            }
17140
17141            return PackageManager.INSTALL_SUCCEEDED;
17142        }
17143    }
17144
17145    /**
17146     * Logic to handle movement of existing installed applications.
17147     */
17148    class MoveInstallArgs extends InstallArgs {
17149        private File codeFile;
17150        private File resourceFile;
17151
17152        /** New install */
17153        MoveInstallArgs(InstallParams params) {
17154            super(params.origin, params.move, params.observer, params.installFlags,
17155                    params.installerPackageName, params.volumeUuid,
17156                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
17157                    params.grantedRuntimePermissions,
17158                    params.traceMethod, params.traceCookie, params.certificates,
17159                    params.installReason);
17160        }
17161
17162        int copyApk(IMediaContainerService imcs, boolean temp) {
17163            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
17164                    + move.fromUuid + " to " + move.toUuid);
17165            synchronized (mInstaller) {
17166                try {
17167                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
17168                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
17169                } catch (InstallerException e) {
17170                    Slog.w(TAG, "Failed to move app", e);
17171                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
17172                }
17173            }
17174
17175            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
17176            resourceFile = codeFile;
17177            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
17178
17179            return PackageManager.INSTALL_SUCCEEDED;
17180        }
17181
17182        int doPreInstall(int status) {
17183            if (status != PackageManager.INSTALL_SUCCEEDED) {
17184                cleanUp(move.toUuid);
17185            }
17186            return status;
17187        }
17188
17189        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
17190            if (status != PackageManager.INSTALL_SUCCEEDED) {
17191                cleanUp(move.toUuid);
17192                return false;
17193            }
17194
17195            // Reflect the move in app info
17196            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
17197            pkg.setApplicationInfoCodePath(pkg.codePath);
17198            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
17199            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
17200            pkg.setApplicationInfoResourcePath(pkg.codePath);
17201            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
17202            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
17203
17204            return true;
17205        }
17206
17207        int doPostInstall(int status, int uid) {
17208            if (status == PackageManager.INSTALL_SUCCEEDED) {
17209                cleanUp(move.fromUuid);
17210            } else {
17211                cleanUp(move.toUuid);
17212            }
17213            return status;
17214        }
17215
17216        @Override
17217        String getCodePath() {
17218            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
17219        }
17220
17221        @Override
17222        String getResourcePath() {
17223            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
17224        }
17225
17226        private boolean cleanUp(String volumeUuid) {
17227            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
17228                    move.dataAppName);
17229            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
17230            final int[] userIds = sUserManager.getUserIds();
17231            synchronized (mInstallLock) {
17232                // Clean up both app data and code
17233                // All package moves are frozen until finished
17234                for (int userId : userIds) {
17235                    try {
17236                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
17237                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
17238                    } catch (InstallerException e) {
17239                        Slog.w(TAG, String.valueOf(e));
17240                    }
17241                }
17242                removeCodePathLI(codeFile);
17243            }
17244            return true;
17245        }
17246
17247        void cleanUpResourcesLI() {
17248            throw new UnsupportedOperationException();
17249        }
17250
17251        boolean doPostDeleteLI(boolean delete) {
17252            throw new UnsupportedOperationException();
17253        }
17254    }
17255
17256    static String getAsecPackageName(String packageCid) {
17257        int idx = packageCid.lastIndexOf("-");
17258        if (idx == -1) {
17259            return packageCid;
17260        }
17261        return packageCid.substring(0, idx);
17262    }
17263
17264    // Utility method used to create code paths based on package name and available index.
17265    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
17266        String idxStr = "";
17267        int idx = 1;
17268        // Fall back to default value of idx=1 if prefix is not
17269        // part of oldCodePath
17270        if (oldCodePath != null) {
17271            String subStr = oldCodePath;
17272            // Drop the suffix right away
17273            if (suffix != null && subStr.endsWith(suffix)) {
17274                subStr = subStr.substring(0, subStr.length() - suffix.length());
17275            }
17276            // If oldCodePath already contains prefix find out the
17277            // ending index to either increment or decrement.
17278            int sidx = subStr.lastIndexOf(prefix);
17279            if (sidx != -1) {
17280                subStr = subStr.substring(sidx + prefix.length());
17281                if (subStr != null) {
17282                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
17283                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
17284                    }
17285                    try {
17286                        idx = Integer.parseInt(subStr);
17287                        if (idx <= 1) {
17288                            idx++;
17289                        } else {
17290                            idx--;
17291                        }
17292                    } catch(NumberFormatException e) {
17293                    }
17294                }
17295            }
17296        }
17297        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
17298        return prefix + idxStr;
17299    }
17300
17301    private File getNextCodePath(File targetDir, String packageName) {
17302        File result;
17303        SecureRandom random = new SecureRandom();
17304        byte[] bytes = new byte[16];
17305        do {
17306            random.nextBytes(bytes);
17307            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
17308            result = new File(targetDir, packageName + "-" + suffix);
17309        } while (result.exists());
17310        return result;
17311    }
17312
17313    // Utility method that returns the relative package path with respect
17314    // to the installation directory. Like say for /data/data/com.test-1.apk
17315    // string com.test-1 is returned.
17316    static String deriveCodePathName(String codePath) {
17317        if (codePath == null) {
17318            return null;
17319        }
17320        final File codeFile = new File(codePath);
17321        final String name = codeFile.getName();
17322        if (codeFile.isDirectory()) {
17323            return name;
17324        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
17325            final int lastDot = name.lastIndexOf('.');
17326            return name.substring(0, lastDot);
17327        } else {
17328            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
17329            return null;
17330        }
17331    }
17332
17333    static class PackageInstalledInfo {
17334        String name;
17335        int uid;
17336        // The set of users that originally had this package installed.
17337        int[] origUsers;
17338        // The set of users that now have this package installed.
17339        int[] newUsers;
17340        PackageParser.Package pkg;
17341        int returnCode;
17342        String returnMsg;
17343        PackageRemovedInfo removedInfo;
17344        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
17345
17346        public void setError(int code, String msg) {
17347            setReturnCode(code);
17348            setReturnMessage(msg);
17349            Slog.w(TAG, msg);
17350        }
17351
17352        public void setError(String msg, PackageParserException e) {
17353            setReturnCode(e.error);
17354            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17355            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17356            for (int i = 0; i < childCount; i++) {
17357                addedChildPackages.valueAt(i).setError(msg, e);
17358            }
17359            Slog.w(TAG, msg, e);
17360        }
17361
17362        public void setError(String msg, PackageManagerException e) {
17363            returnCode = e.error;
17364            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17365            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17366            for (int i = 0; i < childCount; i++) {
17367                addedChildPackages.valueAt(i).setError(msg, e);
17368            }
17369            Slog.w(TAG, msg, e);
17370        }
17371
17372        public void setReturnCode(int returnCode) {
17373            this.returnCode = returnCode;
17374            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17375            for (int i = 0; i < childCount; i++) {
17376                addedChildPackages.valueAt(i).returnCode = returnCode;
17377            }
17378        }
17379
17380        private void setReturnMessage(String returnMsg) {
17381            this.returnMsg = returnMsg;
17382            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17383            for (int i = 0; i < childCount; i++) {
17384                addedChildPackages.valueAt(i).returnMsg = returnMsg;
17385            }
17386        }
17387
17388        // In some error cases we want to convey more info back to the observer
17389        String origPackage;
17390        String origPermission;
17391    }
17392
17393    /*
17394     * Install a non-existing package.
17395     */
17396    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
17397            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
17398            PackageInstalledInfo res, int installReason) {
17399        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
17400
17401        // Remember this for later, in case we need to rollback this install
17402        String pkgName = pkg.packageName;
17403
17404        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
17405
17406        synchronized(mPackages) {
17407            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
17408            if (renamedPackage != null) {
17409                // A package with the same name is already installed, though
17410                // it has been renamed to an older name.  The package we
17411                // are trying to install should be installed as an update to
17412                // the existing one, but that has not been requested, so bail.
17413                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17414                        + " without first uninstalling package running as "
17415                        + renamedPackage);
17416                return;
17417            }
17418            if (mPackages.containsKey(pkgName)) {
17419                // Don't allow installation over an existing package with the same name.
17420                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17421                        + " without first uninstalling.");
17422                return;
17423            }
17424        }
17425
17426        try {
17427            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
17428                    System.currentTimeMillis(), user);
17429
17430            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
17431
17432            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17433                prepareAppDataAfterInstallLIF(newPackage);
17434
17435            } else {
17436                // Remove package from internal structures, but keep around any
17437                // data that might have already existed
17438                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
17439                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
17440            }
17441        } catch (PackageManagerException e) {
17442            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17443        }
17444
17445        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17446    }
17447
17448    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
17449        // Can't rotate keys during boot or if sharedUser.
17450        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
17451                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
17452            return false;
17453        }
17454        // app is using upgradeKeySets; make sure all are valid
17455        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17456        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
17457        for (int i = 0; i < upgradeKeySets.length; i++) {
17458            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
17459                Slog.wtf(TAG, "Package "
17460                         + (oldPs.name != null ? oldPs.name : "<null>")
17461                         + " contains upgrade-key-set reference to unknown key-set: "
17462                         + upgradeKeySets[i]
17463                         + " reverting to signatures check.");
17464                return false;
17465            }
17466        }
17467        return true;
17468    }
17469
17470    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
17471        // Upgrade keysets are being used.  Determine if new package has a superset of the
17472        // required keys.
17473        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
17474        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17475        for (int i = 0; i < upgradeKeySets.length; i++) {
17476            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
17477            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
17478                return true;
17479            }
17480        }
17481        return false;
17482    }
17483
17484    private static void updateDigest(MessageDigest digest, File file) throws IOException {
17485        try (DigestInputStream digestStream =
17486                new DigestInputStream(new FileInputStream(file), digest)) {
17487            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
17488        }
17489    }
17490
17491    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
17492            UserHandle user, String installerPackageName, PackageInstalledInfo res,
17493            int installReason) {
17494        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17495
17496        final PackageParser.Package oldPackage;
17497        final PackageSetting ps;
17498        final String pkgName = pkg.packageName;
17499        final int[] allUsers;
17500        final int[] installedUsers;
17501
17502        synchronized(mPackages) {
17503            oldPackage = mPackages.get(pkgName);
17504            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
17505
17506            // don't allow upgrade to target a release SDK from a pre-release SDK
17507            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
17508                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17509            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
17510                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17511            if (oldTargetsPreRelease
17512                    && !newTargetsPreRelease
17513                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
17514                Slog.w(TAG, "Can't install package targeting released sdk");
17515                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
17516                return;
17517            }
17518
17519            ps = mSettings.mPackages.get(pkgName);
17520
17521            // verify signatures are valid
17522            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17523                if (!checkUpgradeKeySetLP(ps, pkg)) {
17524                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17525                            "New package not signed by keys specified by upgrade-keysets: "
17526                                    + pkgName);
17527                    return;
17528                }
17529            } else {
17530                // default to original signature matching
17531                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17532                        != PackageManager.SIGNATURE_MATCH) {
17533                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17534                            "New package has a different signature: " + pkgName);
17535                    return;
17536                }
17537            }
17538
17539            // don't allow a system upgrade unless the upgrade hash matches
17540            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17541                byte[] digestBytes = null;
17542                try {
17543                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17544                    updateDigest(digest, new File(pkg.baseCodePath));
17545                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17546                        for (String path : pkg.splitCodePaths) {
17547                            updateDigest(digest, new File(path));
17548                        }
17549                    }
17550                    digestBytes = digest.digest();
17551                } catch (NoSuchAlgorithmException | IOException e) {
17552                    res.setError(INSTALL_FAILED_INVALID_APK,
17553                            "Could not compute hash: " + pkgName);
17554                    return;
17555                }
17556                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17557                    res.setError(INSTALL_FAILED_INVALID_APK,
17558                            "New package fails restrict-update check: " + pkgName);
17559                    return;
17560                }
17561                // retain upgrade restriction
17562                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17563            }
17564
17565            // Check for shared user id changes
17566            String invalidPackageName =
17567                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17568            if (invalidPackageName != null) {
17569                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17570                        "Package " + invalidPackageName + " tried to change user "
17571                                + oldPackage.mSharedUserId);
17572                return;
17573            }
17574
17575            // In case of rollback, remember per-user/profile install state
17576            allUsers = sUserManager.getUserIds();
17577            installedUsers = ps.queryInstalledUsers(allUsers, true);
17578
17579            // don't allow an upgrade from full to ephemeral
17580            if (isInstantApp) {
17581                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17582                    for (int currentUser : allUsers) {
17583                        if (!ps.getInstantApp(currentUser)) {
17584                            // can't downgrade from full to instant
17585                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17586                                    + " for user: " + currentUser);
17587                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17588                            return;
17589                        }
17590                    }
17591                } else if (!ps.getInstantApp(user.getIdentifier())) {
17592                    // can't downgrade from full to instant
17593                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17594                            + " for user: " + user.getIdentifier());
17595                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17596                    return;
17597                }
17598            }
17599        }
17600
17601        // Update what is removed
17602        res.removedInfo = new PackageRemovedInfo(this);
17603        res.removedInfo.uid = oldPackage.applicationInfo.uid;
17604        res.removedInfo.removedPackage = oldPackage.packageName;
17605        res.removedInfo.installerPackageName = ps.installerPackageName;
17606        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17607        res.removedInfo.isUpdate = true;
17608        res.removedInfo.origUsers = installedUsers;
17609        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17610        for (int i = 0; i < installedUsers.length; i++) {
17611            final int userId = installedUsers[i];
17612            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17613        }
17614
17615        final int childCount = (oldPackage.childPackages != null)
17616                ? oldPackage.childPackages.size() : 0;
17617        for (int i = 0; i < childCount; i++) {
17618            boolean childPackageUpdated = false;
17619            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17620            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17621            if (res.addedChildPackages != null) {
17622                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17623                if (childRes != null) {
17624                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17625                    childRes.removedInfo.removedPackage = childPkg.packageName;
17626                    if (childPs != null) {
17627                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17628                    }
17629                    childRes.removedInfo.isUpdate = true;
17630                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17631                    childPackageUpdated = true;
17632                }
17633            }
17634            if (!childPackageUpdated) {
17635                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17636                childRemovedRes.removedPackage = childPkg.packageName;
17637                if (childPs != null) {
17638                    childRemovedRes.installerPackageName = childPs.installerPackageName;
17639                }
17640                childRemovedRes.isUpdate = false;
17641                childRemovedRes.dataRemoved = true;
17642                synchronized (mPackages) {
17643                    if (childPs != null) {
17644                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17645                    }
17646                }
17647                if (res.removedInfo.removedChildPackages == null) {
17648                    res.removedInfo.removedChildPackages = new ArrayMap<>();
17649                }
17650                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17651            }
17652        }
17653
17654        boolean sysPkg = (isSystemApp(oldPackage));
17655        if (sysPkg) {
17656            // Set the system/privileged flags as needed
17657            final boolean privileged =
17658                    (oldPackage.applicationInfo.privateFlags
17659                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17660            final int systemPolicyFlags = policyFlags
17661                    | PackageParser.PARSE_IS_SYSTEM
17662                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
17663
17664            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17665                    user, allUsers, installerPackageName, res, installReason);
17666        } else {
17667            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17668                    user, allUsers, installerPackageName, res, installReason);
17669        }
17670    }
17671
17672    @Override
17673    public List<String> getPreviousCodePaths(String packageName) {
17674        final int callingUid = Binder.getCallingUid();
17675        final List<String> result = new ArrayList<>();
17676        if (getInstantAppPackageName(callingUid) != null) {
17677            return result;
17678        }
17679        final PackageSetting ps = mSettings.mPackages.get(packageName);
17680        if (ps != null
17681                && ps.oldCodePaths != null
17682                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17683            result.addAll(ps.oldCodePaths);
17684        }
17685        return result;
17686    }
17687
17688    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17689            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17690            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17691            int installReason) {
17692        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17693                + deletedPackage);
17694
17695        String pkgName = deletedPackage.packageName;
17696        boolean deletedPkg = true;
17697        boolean addedPkg = false;
17698        boolean updatedSettings = false;
17699        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17700        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17701                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17702
17703        final long origUpdateTime = (pkg.mExtras != null)
17704                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17705
17706        // First delete the existing package while retaining the data directory
17707        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17708                res.removedInfo, true, pkg)) {
17709            // If the existing package wasn't successfully deleted
17710            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17711            deletedPkg = false;
17712        } else {
17713            // Successfully deleted the old package; proceed with replace.
17714
17715            // If deleted package lived in a container, give users a chance to
17716            // relinquish resources before killing.
17717            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17718                if (DEBUG_INSTALL) {
17719                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17720                }
17721                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17722                final ArrayList<String> pkgList = new ArrayList<String>(1);
17723                pkgList.add(deletedPackage.applicationInfo.packageName);
17724                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17725            }
17726
17727            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17728                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17729            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17730
17731            try {
17732                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17733                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17734                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17735                        installReason);
17736
17737                // Update the in-memory copy of the previous code paths.
17738                PackageSetting ps = mSettings.mPackages.get(pkgName);
17739                if (!killApp) {
17740                    if (ps.oldCodePaths == null) {
17741                        ps.oldCodePaths = new ArraySet<>();
17742                    }
17743                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17744                    if (deletedPackage.splitCodePaths != null) {
17745                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17746                    }
17747                } else {
17748                    ps.oldCodePaths = null;
17749                }
17750                if (ps.childPackageNames != null) {
17751                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17752                        final String childPkgName = ps.childPackageNames.get(i);
17753                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17754                        childPs.oldCodePaths = ps.oldCodePaths;
17755                    }
17756                }
17757                // set instant app status, but, only if it's explicitly specified
17758                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17759                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17760                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17761                prepareAppDataAfterInstallLIF(newPackage);
17762                addedPkg = true;
17763                mDexManager.notifyPackageUpdated(newPackage.packageName,
17764                        newPackage.baseCodePath, newPackage.splitCodePaths);
17765            } catch (PackageManagerException e) {
17766                res.setError("Package couldn't be installed in " + pkg.codePath, e);
17767            }
17768        }
17769
17770        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17771            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17772
17773            // Revert all internal state mutations and added folders for the failed install
17774            if (addedPkg) {
17775                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17776                        res.removedInfo, true, null);
17777            }
17778
17779            // Restore the old package
17780            if (deletedPkg) {
17781                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17782                File restoreFile = new File(deletedPackage.codePath);
17783                // Parse old package
17784                boolean oldExternal = isExternal(deletedPackage);
17785                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
17786                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17787                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17788                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17789                try {
17790                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17791                            null);
17792                } catch (PackageManagerException e) {
17793                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17794                            + e.getMessage());
17795                    return;
17796                }
17797
17798                synchronized (mPackages) {
17799                    // Ensure the installer package name up to date
17800                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17801
17802                    // Update permissions for restored package
17803                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17804
17805                    mSettings.writeLPr();
17806                }
17807
17808                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17809            }
17810        } else {
17811            synchronized (mPackages) {
17812                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17813                if (ps != null) {
17814                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17815                    if (res.removedInfo.removedChildPackages != null) {
17816                        final int childCount = res.removedInfo.removedChildPackages.size();
17817                        // Iterate in reverse as we may modify the collection
17818                        for (int i = childCount - 1; i >= 0; i--) {
17819                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17820                            if (res.addedChildPackages.containsKey(childPackageName)) {
17821                                res.removedInfo.removedChildPackages.removeAt(i);
17822                            } else {
17823                                PackageRemovedInfo childInfo = res.removedInfo
17824                                        .removedChildPackages.valueAt(i);
17825                                childInfo.removedForAllUsers = mPackages.get(
17826                                        childInfo.removedPackage) == null;
17827                            }
17828                        }
17829                    }
17830                }
17831            }
17832        }
17833    }
17834
17835    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
17836            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17837            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17838            int installReason) {
17839        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
17840                + ", old=" + deletedPackage);
17841
17842        final boolean disabledSystem;
17843
17844        // Remove existing system package
17845        removePackageLI(deletedPackage, true);
17846
17847        synchronized (mPackages) {
17848            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
17849        }
17850        if (!disabledSystem) {
17851            // We didn't need to disable the .apk as a current system package,
17852            // which means we are replacing another update that is already
17853            // installed.  We need to make sure to delete the older one's .apk.
17854            res.removedInfo.args = createInstallArgsForExisting(0,
17855                    deletedPackage.applicationInfo.getCodePath(),
17856                    deletedPackage.applicationInfo.getResourcePath(),
17857                    getAppDexInstructionSets(deletedPackage.applicationInfo));
17858        } else {
17859            res.removedInfo.args = null;
17860        }
17861
17862        // Successfully disabled the old package. Now proceed with re-installation
17863        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17864                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17865        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17866
17867        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17868        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
17869                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
17870
17871        PackageParser.Package newPackage = null;
17872        try {
17873            // Add the package to the internal data structures
17874            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
17875
17876            // Set the update and install times
17877            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
17878            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
17879                    System.currentTimeMillis());
17880
17881            // Update the package dynamic state if succeeded
17882            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17883                // Now that the install succeeded make sure we remove data
17884                // directories for any child package the update removed.
17885                final int deletedChildCount = (deletedPackage.childPackages != null)
17886                        ? deletedPackage.childPackages.size() : 0;
17887                final int newChildCount = (newPackage.childPackages != null)
17888                        ? newPackage.childPackages.size() : 0;
17889                for (int i = 0; i < deletedChildCount; i++) {
17890                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
17891                    boolean childPackageDeleted = true;
17892                    for (int j = 0; j < newChildCount; j++) {
17893                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
17894                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
17895                            childPackageDeleted = false;
17896                            break;
17897                        }
17898                    }
17899                    if (childPackageDeleted) {
17900                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
17901                                deletedChildPkg.packageName);
17902                        if (ps != null && res.removedInfo.removedChildPackages != null) {
17903                            PackageRemovedInfo removedChildRes = res.removedInfo
17904                                    .removedChildPackages.get(deletedChildPkg.packageName);
17905                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
17906                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
17907                        }
17908                    }
17909                }
17910
17911                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17912                        installReason);
17913                prepareAppDataAfterInstallLIF(newPackage);
17914
17915                mDexManager.notifyPackageUpdated(newPackage.packageName,
17916                            newPackage.baseCodePath, newPackage.splitCodePaths);
17917            }
17918        } catch (PackageManagerException e) {
17919            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
17920            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17921        }
17922
17923        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17924            // Re installation failed. Restore old information
17925            // Remove new pkg information
17926            if (newPackage != null) {
17927                removeInstalledPackageLI(newPackage, true);
17928            }
17929            // Add back the old system package
17930            try {
17931                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
17932            } catch (PackageManagerException e) {
17933                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
17934            }
17935
17936            synchronized (mPackages) {
17937                if (disabledSystem) {
17938                    enableSystemPackageLPw(deletedPackage);
17939                }
17940
17941                // Ensure the installer package name up to date
17942                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17943
17944                // Update permissions for restored package
17945                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17946
17947                mSettings.writeLPr();
17948            }
17949
17950            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
17951                    + " after failed upgrade");
17952        }
17953    }
17954
17955    /**
17956     * Checks whether the parent or any of the child packages have a change shared
17957     * user. For a package to be a valid update the shred users of the parent and
17958     * the children should match. We may later support changing child shared users.
17959     * @param oldPkg The updated package.
17960     * @param newPkg The update package.
17961     * @return The shared user that change between the versions.
17962     */
17963    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
17964            PackageParser.Package newPkg) {
17965        // Check parent shared user
17966        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
17967            return newPkg.packageName;
17968        }
17969        // Check child shared users
17970        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17971        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
17972        for (int i = 0; i < newChildCount; i++) {
17973            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
17974            // If this child was present, did it have the same shared user?
17975            for (int j = 0; j < oldChildCount; j++) {
17976                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
17977                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
17978                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
17979                    return newChildPkg.packageName;
17980                }
17981            }
17982        }
17983        return null;
17984    }
17985
17986    private void removeNativeBinariesLI(PackageSetting ps) {
17987        // Remove the lib path for the parent package
17988        if (ps != null) {
17989            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
17990            // Remove the lib path for the child packages
17991            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17992            for (int i = 0; i < childCount; i++) {
17993                PackageSetting childPs = null;
17994                synchronized (mPackages) {
17995                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17996                }
17997                if (childPs != null) {
17998                    NativeLibraryHelper.removeNativeBinariesLI(childPs
17999                            .legacyNativeLibraryPathString);
18000                }
18001            }
18002        }
18003    }
18004
18005    private void enableSystemPackageLPw(PackageParser.Package pkg) {
18006        // Enable the parent package
18007        mSettings.enableSystemPackageLPw(pkg.packageName);
18008        // Enable the child packages
18009        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18010        for (int i = 0; i < childCount; i++) {
18011            PackageParser.Package childPkg = pkg.childPackages.get(i);
18012            mSettings.enableSystemPackageLPw(childPkg.packageName);
18013        }
18014    }
18015
18016    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
18017            PackageParser.Package newPkg) {
18018        // Disable the parent package (parent always replaced)
18019        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
18020        // Disable the child packages
18021        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
18022        for (int i = 0; i < childCount; i++) {
18023            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
18024            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
18025            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
18026        }
18027        return disabled;
18028    }
18029
18030    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
18031            String installerPackageName) {
18032        // Enable the parent package
18033        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
18034        // Enable the child packages
18035        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18036        for (int i = 0; i < childCount; i++) {
18037            PackageParser.Package childPkg = pkg.childPackages.get(i);
18038            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
18039        }
18040    }
18041
18042    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
18043        // Collect all used permissions in the UID
18044        ArraySet<String> usedPermissions = new ArraySet<>();
18045        final int packageCount = su.packages.size();
18046        for (int i = 0; i < packageCount; i++) {
18047            PackageSetting ps = su.packages.valueAt(i);
18048            if (ps.pkg == null) {
18049                continue;
18050            }
18051            final int requestedPermCount = ps.pkg.requestedPermissions.size();
18052            for (int j = 0; j < requestedPermCount; j++) {
18053                String permission = ps.pkg.requestedPermissions.get(j);
18054                BasePermission bp = mSettings.mPermissions.get(permission);
18055                if (bp != null) {
18056                    usedPermissions.add(permission);
18057                }
18058            }
18059        }
18060
18061        PermissionsState permissionsState = su.getPermissionsState();
18062        // Prune install permissions
18063        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
18064        final int installPermCount = installPermStates.size();
18065        for (int i = installPermCount - 1; i >= 0;  i--) {
18066            PermissionState permissionState = installPermStates.get(i);
18067            if (!usedPermissions.contains(permissionState.getName())) {
18068                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
18069                if (bp != null) {
18070                    permissionsState.revokeInstallPermission(bp);
18071                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
18072                            PackageManager.MASK_PERMISSION_FLAGS, 0);
18073                }
18074            }
18075        }
18076
18077        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
18078
18079        // Prune runtime permissions
18080        for (int userId : allUserIds) {
18081            List<PermissionState> runtimePermStates = permissionsState
18082                    .getRuntimePermissionStates(userId);
18083            final int runtimePermCount = runtimePermStates.size();
18084            for (int i = runtimePermCount - 1; i >= 0; i--) {
18085                PermissionState permissionState = runtimePermStates.get(i);
18086                if (!usedPermissions.contains(permissionState.getName())) {
18087                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
18088                    if (bp != null) {
18089                        permissionsState.revokeRuntimePermission(bp, userId);
18090                        permissionsState.updatePermissionFlags(bp, userId,
18091                                PackageManager.MASK_PERMISSION_FLAGS, 0);
18092                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
18093                                runtimePermissionChangedUserIds, userId);
18094                    }
18095                }
18096            }
18097        }
18098
18099        return runtimePermissionChangedUserIds;
18100    }
18101
18102    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
18103            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
18104        // Update the parent package setting
18105        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
18106                res, user, installReason);
18107        // Update the child packages setting
18108        final int childCount = (newPackage.childPackages != null)
18109                ? newPackage.childPackages.size() : 0;
18110        for (int i = 0; i < childCount; i++) {
18111            PackageParser.Package childPackage = newPackage.childPackages.get(i);
18112            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
18113            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
18114                    childRes.origUsers, childRes, user, installReason);
18115        }
18116    }
18117
18118    private void updateSettingsInternalLI(PackageParser.Package newPackage,
18119            String installerPackageName, int[] allUsers, int[] installedForUsers,
18120            PackageInstalledInfo res, UserHandle user, int installReason) {
18121        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
18122
18123        String pkgName = newPackage.packageName;
18124        synchronized (mPackages) {
18125            //write settings. the installStatus will be incomplete at this stage.
18126            //note that the new package setting would have already been
18127            //added to mPackages. It hasn't been persisted yet.
18128            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
18129            // TODO: Remove this write? It's also written at the end of this method
18130            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
18131            mSettings.writeLPr();
18132            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18133        }
18134
18135        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
18136        synchronized (mPackages) {
18137            updatePermissionsLPw(newPackage.packageName, newPackage,
18138                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
18139                            ? UPDATE_PERMISSIONS_ALL : 0));
18140            // For system-bundled packages, we assume that installing an upgraded version
18141            // of the package implies that the user actually wants to run that new code,
18142            // so we enable the package.
18143            PackageSetting ps = mSettings.mPackages.get(pkgName);
18144            final int userId = user.getIdentifier();
18145            if (ps != null) {
18146                if (isSystemApp(newPackage)) {
18147                    if (DEBUG_INSTALL) {
18148                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
18149                    }
18150                    // Enable system package for requested users
18151                    if (res.origUsers != null) {
18152                        for (int origUserId : res.origUsers) {
18153                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
18154                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
18155                                        origUserId, installerPackageName);
18156                            }
18157                        }
18158                    }
18159                    // Also convey the prior install/uninstall state
18160                    if (allUsers != null && installedForUsers != null) {
18161                        for (int currentUserId : allUsers) {
18162                            final boolean installed = ArrayUtils.contains(
18163                                    installedForUsers, currentUserId);
18164                            if (DEBUG_INSTALL) {
18165                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
18166                            }
18167                            ps.setInstalled(installed, currentUserId);
18168                        }
18169                        // these install state changes will be persisted in the
18170                        // upcoming call to mSettings.writeLPr().
18171                    }
18172                }
18173                // It's implied that when a user requests installation, they want the app to be
18174                // installed and enabled.
18175                if (userId != UserHandle.USER_ALL) {
18176                    ps.setInstalled(true, userId);
18177                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
18178                }
18179
18180                // When replacing an existing package, preserve the original install reason for all
18181                // users that had the package installed before.
18182                final Set<Integer> previousUserIds = new ArraySet<>();
18183                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
18184                    final int installReasonCount = res.removedInfo.installReasons.size();
18185                    for (int i = 0; i < installReasonCount; i++) {
18186                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
18187                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
18188                        ps.setInstallReason(previousInstallReason, previousUserId);
18189                        previousUserIds.add(previousUserId);
18190                    }
18191                }
18192
18193                // Set install reason for users that are having the package newly installed.
18194                if (userId == UserHandle.USER_ALL) {
18195                    for (int currentUserId : sUserManager.getUserIds()) {
18196                        if (!previousUserIds.contains(currentUserId)) {
18197                            ps.setInstallReason(installReason, currentUserId);
18198                        }
18199                    }
18200                } else if (!previousUserIds.contains(userId)) {
18201                    ps.setInstallReason(installReason, userId);
18202                }
18203                mSettings.writeKernelMappingLPr(ps);
18204            }
18205            res.name = pkgName;
18206            res.uid = newPackage.applicationInfo.uid;
18207            res.pkg = newPackage;
18208            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
18209            mSettings.setInstallerPackageName(pkgName, installerPackageName);
18210            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18211            //to update install status
18212            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
18213            mSettings.writeLPr();
18214            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18215        }
18216
18217        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18218    }
18219
18220    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
18221        try {
18222            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
18223            installPackageLI(args, res);
18224        } finally {
18225            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18226        }
18227    }
18228
18229    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
18230        final int installFlags = args.installFlags;
18231        final String installerPackageName = args.installerPackageName;
18232        final String volumeUuid = args.volumeUuid;
18233        final File tmpPackageFile = new File(args.getCodePath());
18234        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
18235        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
18236                || (args.volumeUuid != null));
18237        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
18238        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
18239        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
18240        final boolean virtualPreload =
18241                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
18242        boolean replace = false;
18243        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
18244        if (args.move != null) {
18245            // moving a complete application; perform an initial scan on the new install location
18246            scanFlags |= SCAN_INITIAL;
18247        }
18248        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
18249            scanFlags |= SCAN_DONT_KILL_APP;
18250        }
18251        if (instantApp) {
18252            scanFlags |= SCAN_AS_INSTANT_APP;
18253        }
18254        if (fullApp) {
18255            scanFlags |= SCAN_AS_FULL_APP;
18256        }
18257        if (virtualPreload) {
18258            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
18259        }
18260
18261        // Result object to be returned
18262        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18263
18264        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
18265
18266        // Sanity check
18267        if (instantApp && (forwardLocked || onExternal)) {
18268            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
18269                    + " external=" + onExternal);
18270            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
18271            return;
18272        }
18273
18274        // Retrieve PackageSettings and parse package
18275        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
18276                | PackageParser.PARSE_ENFORCE_CODE
18277                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
18278                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
18279                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
18280                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
18281        PackageParser pp = new PackageParser();
18282        pp.setSeparateProcesses(mSeparateProcesses);
18283        pp.setDisplayMetrics(mMetrics);
18284        pp.setCallback(mPackageParserCallback);
18285
18286        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
18287        final PackageParser.Package pkg;
18288        try {
18289            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
18290        } catch (PackageParserException e) {
18291            res.setError("Failed parse during installPackageLI", e);
18292            return;
18293        } finally {
18294            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18295        }
18296
18297        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
18298        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
18299            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
18300            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18301                    "Instant app package must target O");
18302            return;
18303        }
18304        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
18305            Slog.w(TAG, "Instant app package " + pkg.packageName
18306                    + " does not target targetSandboxVersion 2");
18307            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18308                    "Instant app package must use targetSanboxVersion 2");
18309            return;
18310        }
18311
18312        if (pkg.applicationInfo.isStaticSharedLibrary()) {
18313            // Static shared libraries have synthetic package names
18314            renameStaticSharedLibraryPackage(pkg);
18315
18316            // No static shared libs on external storage
18317            if (onExternal) {
18318                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
18319                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18320                        "Packages declaring static-shared libs cannot be updated");
18321                return;
18322            }
18323        }
18324
18325        // If we are installing a clustered package add results for the children
18326        if (pkg.childPackages != null) {
18327            synchronized (mPackages) {
18328                final int childCount = pkg.childPackages.size();
18329                for (int i = 0; i < childCount; i++) {
18330                    PackageParser.Package childPkg = pkg.childPackages.get(i);
18331                    PackageInstalledInfo childRes = new PackageInstalledInfo();
18332                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18333                    childRes.pkg = childPkg;
18334                    childRes.name = childPkg.packageName;
18335                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18336                    if (childPs != null) {
18337                        childRes.origUsers = childPs.queryInstalledUsers(
18338                                sUserManager.getUserIds(), true);
18339                    }
18340                    if ((mPackages.containsKey(childPkg.packageName))) {
18341                        childRes.removedInfo = new PackageRemovedInfo(this);
18342                        childRes.removedInfo.removedPackage = childPkg.packageName;
18343                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
18344                    }
18345                    if (res.addedChildPackages == null) {
18346                        res.addedChildPackages = new ArrayMap<>();
18347                    }
18348                    res.addedChildPackages.put(childPkg.packageName, childRes);
18349                }
18350            }
18351        }
18352
18353        // If package doesn't declare API override, mark that we have an install
18354        // time CPU ABI override.
18355        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
18356            pkg.cpuAbiOverride = args.abiOverride;
18357        }
18358
18359        String pkgName = res.name = pkg.packageName;
18360        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
18361            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
18362                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
18363                return;
18364            }
18365        }
18366
18367        try {
18368            // either use what we've been given or parse directly from the APK
18369            if (args.certificates != null) {
18370                try {
18371                    PackageParser.populateCertificates(pkg, args.certificates);
18372                } catch (PackageParserException e) {
18373                    // there was something wrong with the certificates we were given;
18374                    // try to pull them from the APK
18375                    PackageParser.collectCertificates(pkg, parseFlags);
18376                }
18377            } else {
18378                PackageParser.collectCertificates(pkg, parseFlags);
18379            }
18380        } catch (PackageParserException e) {
18381            res.setError("Failed collect during installPackageLI", e);
18382            return;
18383        }
18384
18385        // Get rid of all references to package scan path via parser.
18386        pp = null;
18387        String oldCodePath = null;
18388        boolean systemApp = false;
18389        synchronized (mPackages) {
18390            // Check if installing already existing package
18391            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
18392                String oldName = mSettings.getRenamedPackageLPr(pkgName);
18393                if (pkg.mOriginalPackages != null
18394                        && pkg.mOriginalPackages.contains(oldName)
18395                        && mPackages.containsKey(oldName)) {
18396                    // This package is derived from an original package,
18397                    // and this device has been updating from that original
18398                    // name.  We must continue using the original name, so
18399                    // rename the new package here.
18400                    pkg.setPackageName(oldName);
18401                    pkgName = pkg.packageName;
18402                    replace = true;
18403                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
18404                            + oldName + " pkgName=" + pkgName);
18405                } else if (mPackages.containsKey(pkgName)) {
18406                    // This package, under its official name, already exists
18407                    // on the device; we should replace it.
18408                    replace = true;
18409                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
18410                }
18411
18412                // Child packages are installed through the parent package
18413                if (pkg.parentPackage != null) {
18414                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18415                            "Package " + pkg.packageName + " is child of package "
18416                                    + pkg.parentPackage.parentPackage + ". Child packages "
18417                                    + "can be updated only through the parent package.");
18418                    return;
18419                }
18420
18421                if (replace) {
18422                    // Prevent apps opting out from runtime permissions
18423                    PackageParser.Package oldPackage = mPackages.get(pkgName);
18424                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
18425                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
18426                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
18427                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
18428                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
18429                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
18430                                        + " doesn't support runtime permissions but the old"
18431                                        + " target SDK " + oldTargetSdk + " does.");
18432                        return;
18433                    }
18434                    // Prevent apps from downgrading their targetSandbox.
18435                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
18436                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
18437                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
18438                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18439                                "Package " + pkg.packageName + " new target sandbox "
18440                                + newTargetSandbox + " is incompatible with the previous value of"
18441                                + oldTargetSandbox + ".");
18442                        return;
18443                    }
18444
18445                    // Prevent installing of child packages
18446                    if (oldPackage.parentPackage != null) {
18447                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18448                                "Package " + pkg.packageName + " is child of package "
18449                                        + oldPackage.parentPackage + ". Child packages "
18450                                        + "can be updated only through the parent package.");
18451                        return;
18452                    }
18453                }
18454            }
18455
18456            PackageSetting ps = mSettings.mPackages.get(pkgName);
18457            if (ps != null) {
18458                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
18459
18460                // Static shared libs have same package with different versions where
18461                // we internally use a synthetic package name to allow multiple versions
18462                // of the same package, therefore we need to compare signatures against
18463                // the package setting for the latest library version.
18464                PackageSetting signatureCheckPs = ps;
18465                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18466                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
18467                    if (libraryEntry != null) {
18468                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
18469                    }
18470                }
18471
18472                // Quick sanity check that we're signed correctly if updating;
18473                // we'll check this again later when scanning, but we want to
18474                // bail early here before tripping over redefined permissions.
18475                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
18476                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
18477                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
18478                                + pkg.packageName + " upgrade keys do not match the "
18479                                + "previously installed version");
18480                        return;
18481                    }
18482                } else {
18483                    try {
18484                        verifySignaturesLP(signatureCheckPs, pkg);
18485                    } catch (PackageManagerException e) {
18486                        res.setError(e.error, e.getMessage());
18487                        return;
18488                    }
18489                }
18490
18491                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
18492                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
18493                    systemApp = (ps.pkg.applicationInfo.flags &
18494                            ApplicationInfo.FLAG_SYSTEM) != 0;
18495                }
18496                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18497            }
18498
18499            int N = pkg.permissions.size();
18500            for (int i = N-1; i >= 0; i--) {
18501                PackageParser.Permission perm = pkg.permissions.get(i);
18502                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
18503
18504                // Don't allow anyone but the system to define ephemeral permissions.
18505                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
18506                        && !systemApp) {
18507                    Slog.w(TAG, "Non-System package " + pkg.packageName
18508                            + " attempting to delcare ephemeral permission "
18509                            + perm.info.name + "; Removing ephemeral.");
18510                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
18511                }
18512                // Check whether the newly-scanned package wants to define an already-defined perm
18513                if (bp != null) {
18514                    // If the defining package is signed with our cert, it's okay.  This
18515                    // also includes the "updating the same package" case, of course.
18516                    // "updating same package" could also involve key-rotation.
18517                    final boolean sigsOk;
18518                    if (bp.sourcePackage.equals(pkg.packageName)
18519                            && (bp.packageSetting instanceof PackageSetting)
18520                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
18521                                    scanFlags))) {
18522                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
18523                    } else {
18524                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
18525                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18526                    }
18527                    if (!sigsOk) {
18528                        // If the owning package is the system itself, we log but allow
18529                        // install to proceed; we fail the install on all other permission
18530                        // redefinitions.
18531                        if (!bp.sourcePackage.equals("android")) {
18532                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18533                                    + pkg.packageName + " attempting to redeclare permission "
18534                                    + perm.info.name + " already owned by " + bp.sourcePackage);
18535                            res.origPermission = perm.info.name;
18536                            res.origPackage = bp.sourcePackage;
18537                            return;
18538                        } else {
18539                            Slog.w(TAG, "Package " + pkg.packageName
18540                                    + " attempting to redeclare system permission "
18541                                    + perm.info.name + "; ignoring new declaration");
18542                            pkg.permissions.remove(i);
18543                        }
18544                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18545                        // Prevent apps to change protection level to dangerous from any other
18546                        // type as this would allow a privilege escalation where an app adds a
18547                        // normal/signature permission in other app's group and later redefines
18548                        // it as dangerous leading to the group auto-grant.
18549                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18550                                == PermissionInfo.PROTECTION_DANGEROUS) {
18551                            if (bp != null && !bp.isRuntime()) {
18552                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18553                                        + "non-runtime permission " + perm.info.name
18554                                        + " to runtime; keeping old protection level");
18555                                perm.info.protectionLevel = bp.protectionLevel;
18556                            }
18557                        }
18558                    }
18559                }
18560            }
18561        }
18562
18563        if (systemApp) {
18564            if (onExternal) {
18565                // Abort update; system app can't be replaced with app on sdcard
18566                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18567                        "Cannot install updates to system apps on sdcard");
18568                return;
18569            } else if (instantApp) {
18570                // Abort update; system app can't be replaced with an instant app
18571                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18572                        "Cannot update a system app with an instant app");
18573                return;
18574            }
18575        }
18576
18577        if (args.move != null) {
18578            // We did an in-place move, so dex is ready to roll
18579            scanFlags |= SCAN_NO_DEX;
18580            scanFlags |= SCAN_MOVE;
18581
18582            synchronized (mPackages) {
18583                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18584                if (ps == null) {
18585                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18586                            "Missing settings for moved package " + pkgName);
18587                }
18588
18589                // We moved the entire application as-is, so bring over the
18590                // previously derived ABI information.
18591                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18592                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18593            }
18594
18595        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18596            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18597            scanFlags |= SCAN_NO_DEX;
18598
18599            try {
18600                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18601                    args.abiOverride : pkg.cpuAbiOverride);
18602                final boolean extractNativeLibs = !pkg.isLibrary();
18603                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18604                        extractNativeLibs, mAppLib32InstallDir);
18605            } catch (PackageManagerException pme) {
18606                Slog.e(TAG, "Error deriving application ABI", pme);
18607                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18608                return;
18609            }
18610
18611            // Shared libraries for the package need to be updated.
18612            synchronized (mPackages) {
18613                try {
18614                    updateSharedLibrariesLPr(pkg, null);
18615                } catch (PackageManagerException e) {
18616                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18617                }
18618            }
18619
18620            // dexopt can take some time to complete, so, for instant apps, we skip this
18621            // step during installation. Instead, we'll take extra time the first time the
18622            // instant app starts. It's preferred to do it this way to provide continuous
18623            // progress to the user instead of mysteriously blocking somewhere in the
18624            // middle of running an instant app. The default behaviour can be overridden
18625            // via gservices.
18626            if (!instantApp || Global.getInt(
18627                        mContext.getContentResolver(), Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0) {
18628                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18629                // Do not run PackageDexOptimizer through the local performDexOpt
18630                // method because `pkg` may not be in `mPackages` yet.
18631                //
18632                // Also, don't fail application installs if the dexopt step fails.
18633                DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
18634                        REASON_INSTALL,
18635                        DexoptOptions.DEXOPT_BOOT_COMPLETE);
18636                mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18637                        null /* instructionSets */,
18638                        getOrCreateCompilerPackageStats(pkg),
18639                        mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
18640                        dexoptOptions);
18641                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18642            }
18643
18644            // Notify BackgroundDexOptService that the package has been changed.
18645            // If this is an update of a package which used to fail to compile,
18646            // BDOS will remove it from its blacklist.
18647            // TODO: Layering violation
18648            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18649        }
18650
18651        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18652            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18653            return;
18654        }
18655
18656        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18657
18658        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18659                "installPackageLI")) {
18660            if (replace) {
18661                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18662                    // Static libs have a synthetic package name containing the version
18663                    // and cannot be updated as an update would get a new package name,
18664                    // unless this is the exact same version code which is useful for
18665                    // development.
18666                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18667                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18668                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18669                                + "static-shared libs cannot be updated");
18670                        return;
18671                    }
18672                }
18673                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18674                        installerPackageName, res, args.installReason);
18675            } else {
18676                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18677                        args.user, installerPackageName, volumeUuid, res, args.installReason);
18678            }
18679        }
18680
18681        synchronized (mPackages) {
18682            final PackageSetting ps = mSettings.mPackages.get(pkgName);
18683            if (ps != null) {
18684                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18685                ps.setUpdateAvailable(false /*updateAvailable*/);
18686            }
18687
18688            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18689            for (int i = 0; i < childCount; i++) {
18690                PackageParser.Package childPkg = pkg.childPackages.get(i);
18691                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18692                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18693                if (childPs != null) {
18694                    childRes.newUsers = childPs.queryInstalledUsers(
18695                            sUserManager.getUserIds(), true);
18696                }
18697            }
18698
18699            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18700                updateSequenceNumberLP(ps, res.newUsers);
18701                updateInstantAppInstallerLocked(pkgName);
18702            }
18703        }
18704    }
18705
18706    private void startIntentFilterVerifications(int userId, boolean replacing,
18707            PackageParser.Package pkg) {
18708        if (mIntentFilterVerifierComponent == null) {
18709            Slog.w(TAG, "No IntentFilter verification will not be done as "
18710                    + "there is no IntentFilterVerifier available!");
18711            return;
18712        }
18713
18714        final int verifierUid = getPackageUid(
18715                mIntentFilterVerifierComponent.getPackageName(),
18716                MATCH_DEBUG_TRIAGED_MISSING,
18717                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18718
18719        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18720        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18721        mHandler.sendMessage(msg);
18722
18723        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18724        for (int i = 0; i < childCount; i++) {
18725            PackageParser.Package childPkg = pkg.childPackages.get(i);
18726            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18727            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18728            mHandler.sendMessage(msg);
18729        }
18730    }
18731
18732    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18733            PackageParser.Package pkg) {
18734        int size = pkg.activities.size();
18735        if (size == 0) {
18736            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18737                    "No activity, so no need to verify any IntentFilter!");
18738            return;
18739        }
18740
18741        final boolean hasDomainURLs = hasDomainURLs(pkg);
18742        if (!hasDomainURLs) {
18743            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18744                    "No domain URLs, so no need to verify any IntentFilter!");
18745            return;
18746        }
18747
18748        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18749                + " if any IntentFilter from the " + size
18750                + " Activities needs verification ...");
18751
18752        int count = 0;
18753        final String packageName = pkg.packageName;
18754
18755        synchronized (mPackages) {
18756            // If this is a new install and we see that we've already run verification for this
18757            // package, we have nothing to do: it means the state was restored from backup.
18758            if (!replacing) {
18759                IntentFilterVerificationInfo ivi =
18760                        mSettings.getIntentFilterVerificationLPr(packageName);
18761                if (ivi != null) {
18762                    if (DEBUG_DOMAIN_VERIFICATION) {
18763                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
18764                                + ivi.getStatusString());
18765                    }
18766                    return;
18767                }
18768            }
18769
18770            // If any filters need to be verified, then all need to be.
18771            boolean needToVerify = false;
18772            for (PackageParser.Activity a : pkg.activities) {
18773                for (ActivityIntentInfo filter : a.intents) {
18774                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18775                        if (DEBUG_DOMAIN_VERIFICATION) {
18776                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18777                        }
18778                        needToVerify = true;
18779                        break;
18780                    }
18781                }
18782            }
18783
18784            if (needToVerify) {
18785                final int verificationId = mIntentFilterVerificationToken++;
18786                for (PackageParser.Activity a : pkg.activities) {
18787                    for (ActivityIntentInfo filter : a.intents) {
18788                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
18789                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18790                                    "Verification needed for IntentFilter:" + filter.toString());
18791                            mIntentFilterVerifier.addOneIntentFilterVerification(
18792                                    verifierUid, userId, verificationId, filter, packageName);
18793                            count++;
18794                        }
18795                    }
18796                }
18797            }
18798        }
18799
18800        if (count > 0) {
18801            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
18802                    + " IntentFilter verification" + (count > 1 ? "s" : "")
18803                    +  " for userId:" + userId);
18804            mIntentFilterVerifier.startVerifications(userId);
18805        } else {
18806            if (DEBUG_DOMAIN_VERIFICATION) {
18807                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
18808            }
18809        }
18810    }
18811
18812    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
18813        final ComponentName cn  = filter.activity.getComponentName();
18814        final String packageName = cn.getPackageName();
18815
18816        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
18817                packageName);
18818        if (ivi == null) {
18819            return true;
18820        }
18821        int status = ivi.getStatus();
18822        switch (status) {
18823            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
18824            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
18825                return true;
18826
18827            default:
18828                // Nothing to do
18829                return false;
18830        }
18831    }
18832
18833    private static boolean isMultiArch(ApplicationInfo info) {
18834        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
18835    }
18836
18837    private static boolean isExternal(PackageParser.Package pkg) {
18838        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18839    }
18840
18841    private static boolean isExternal(PackageSetting ps) {
18842        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18843    }
18844
18845    private static boolean isSystemApp(PackageParser.Package pkg) {
18846        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
18847    }
18848
18849    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
18850        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
18851    }
18852
18853    private static boolean hasDomainURLs(PackageParser.Package pkg) {
18854        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
18855    }
18856
18857    private static boolean isSystemApp(PackageSetting ps) {
18858        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
18859    }
18860
18861    private static boolean isUpdatedSystemApp(PackageSetting ps) {
18862        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
18863    }
18864
18865    private int packageFlagsToInstallFlags(PackageSetting ps) {
18866        int installFlags = 0;
18867        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
18868            // This existing package was an external ASEC install when we have
18869            // the external flag without a UUID
18870            installFlags |= PackageManager.INSTALL_EXTERNAL;
18871        }
18872        if (ps.isForwardLocked()) {
18873            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
18874        }
18875        return installFlags;
18876    }
18877
18878    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
18879        if (isExternal(pkg)) {
18880            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18881                return StorageManager.UUID_PRIMARY_PHYSICAL;
18882            } else {
18883                return pkg.volumeUuid;
18884            }
18885        } else {
18886            return StorageManager.UUID_PRIVATE_INTERNAL;
18887        }
18888    }
18889
18890    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
18891        if (isExternal(pkg)) {
18892            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18893                return mSettings.getExternalVersion();
18894            } else {
18895                return mSettings.findOrCreateVersion(pkg.volumeUuid);
18896            }
18897        } else {
18898            return mSettings.getInternalVersion();
18899        }
18900    }
18901
18902    private void deleteTempPackageFiles() {
18903        final FilenameFilter filter = new FilenameFilter() {
18904            public boolean accept(File dir, String name) {
18905                return name.startsWith("vmdl") && name.endsWith(".tmp");
18906            }
18907        };
18908        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
18909            file.delete();
18910        }
18911    }
18912
18913    @Override
18914    public void deletePackageAsUser(String packageName, int versionCode,
18915            IPackageDeleteObserver observer, int userId, int flags) {
18916        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
18917                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
18918    }
18919
18920    @Override
18921    public void deletePackageVersioned(VersionedPackage versionedPackage,
18922            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
18923        final int callingUid = Binder.getCallingUid();
18924        mContext.enforceCallingOrSelfPermission(
18925                android.Manifest.permission.DELETE_PACKAGES, null);
18926        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
18927        Preconditions.checkNotNull(versionedPackage);
18928        Preconditions.checkNotNull(observer);
18929        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
18930                PackageManager.VERSION_CODE_HIGHEST,
18931                Integer.MAX_VALUE, "versionCode must be >= -1");
18932
18933        final String packageName = versionedPackage.getPackageName();
18934        final int versionCode = versionedPackage.getVersionCode();
18935        final String internalPackageName;
18936        synchronized (mPackages) {
18937            // Normalize package name to handle renamed packages and static libs
18938            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
18939                    versionedPackage.getVersionCode());
18940        }
18941
18942        final int uid = Binder.getCallingUid();
18943        if (!isOrphaned(internalPackageName)
18944                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
18945            try {
18946                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
18947                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
18948                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
18949                observer.onUserActionRequired(intent);
18950            } catch (RemoteException re) {
18951            }
18952            return;
18953        }
18954        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
18955        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
18956        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
18957            mContext.enforceCallingOrSelfPermission(
18958                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
18959                    "deletePackage for user " + userId);
18960        }
18961
18962        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
18963            try {
18964                observer.onPackageDeleted(packageName,
18965                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
18966            } catch (RemoteException re) {
18967            }
18968            return;
18969        }
18970
18971        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
18972            try {
18973                observer.onPackageDeleted(packageName,
18974                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
18975            } catch (RemoteException re) {
18976            }
18977            return;
18978        }
18979
18980        if (DEBUG_REMOVE) {
18981            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
18982                    + " deleteAllUsers: " + deleteAllUsers + " version="
18983                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
18984                    ? "VERSION_CODE_HIGHEST" : versionCode));
18985        }
18986        // Queue up an async operation since the package deletion may take a little while.
18987        mHandler.post(new Runnable() {
18988            public void run() {
18989                mHandler.removeCallbacks(this);
18990                int returnCode;
18991                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
18992                boolean doDeletePackage = true;
18993                if (ps != null) {
18994                    final boolean targetIsInstantApp =
18995                            ps.getInstantApp(UserHandle.getUserId(callingUid));
18996                    doDeletePackage = !targetIsInstantApp
18997                            || canViewInstantApps;
18998                }
18999                if (doDeletePackage) {
19000                    if (!deleteAllUsers) {
19001                        returnCode = deletePackageX(internalPackageName, versionCode,
19002                                userId, deleteFlags);
19003                    } else {
19004                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
19005                                internalPackageName, users);
19006                        // If nobody is blocking uninstall, proceed with delete for all users
19007                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
19008                            returnCode = deletePackageX(internalPackageName, versionCode,
19009                                    userId, deleteFlags);
19010                        } else {
19011                            // Otherwise uninstall individually for users with blockUninstalls=false
19012                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
19013                            for (int userId : users) {
19014                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
19015                                    returnCode = deletePackageX(internalPackageName, versionCode,
19016                                            userId, userFlags);
19017                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
19018                                        Slog.w(TAG, "Package delete failed for user " + userId
19019                                                + ", returnCode " + returnCode);
19020                                    }
19021                                }
19022                            }
19023                            // The app has only been marked uninstalled for certain users.
19024                            // We still need to report that delete was blocked
19025                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
19026                        }
19027                    }
19028                } else {
19029                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19030                }
19031                try {
19032                    observer.onPackageDeleted(packageName, returnCode, null);
19033                } catch (RemoteException e) {
19034                    Log.i(TAG, "Observer no longer exists.");
19035                } //end catch
19036            } //end run
19037        });
19038    }
19039
19040    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
19041        if (pkg.staticSharedLibName != null) {
19042            return pkg.manifestPackageName;
19043        }
19044        return pkg.packageName;
19045    }
19046
19047    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
19048        // Handle renamed packages
19049        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
19050        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
19051
19052        // Is this a static library?
19053        SparseArray<SharedLibraryEntry> versionedLib =
19054                mStaticLibsByDeclaringPackage.get(packageName);
19055        if (versionedLib == null || versionedLib.size() <= 0) {
19056            return packageName;
19057        }
19058
19059        // Figure out which lib versions the caller can see
19060        SparseIntArray versionsCallerCanSee = null;
19061        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
19062        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
19063                && callingAppId != Process.ROOT_UID) {
19064            versionsCallerCanSee = new SparseIntArray();
19065            String libName = versionedLib.valueAt(0).info.getName();
19066            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
19067            if (uidPackages != null) {
19068                for (String uidPackage : uidPackages) {
19069                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
19070                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
19071                    if (libIdx >= 0) {
19072                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
19073                        versionsCallerCanSee.append(libVersion, libVersion);
19074                    }
19075                }
19076            }
19077        }
19078
19079        // Caller can see nothing - done
19080        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
19081            return packageName;
19082        }
19083
19084        // Find the version the caller can see and the app version code
19085        SharedLibraryEntry highestVersion = null;
19086        final int versionCount = versionedLib.size();
19087        for (int i = 0; i < versionCount; i++) {
19088            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
19089            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
19090                    libEntry.info.getVersion()) < 0) {
19091                continue;
19092            }
19093            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
19094            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
19095                if (libVersionCode == versionCode) {
19096                    return libEntry.apk;
19097                }
19098            } else if (highestVersion == null) {
19099                highestVersion = libEntry;
19100            } else if (libVersionCode  > highestVersion.info
19101                    .getDeclaringPackage().getVersionCode()) {
19102                highestVersion = libEntry;
19103            }
19104        }
19105
19106        if (highestVersion != null) {
19107            return highestVersion.apk;
19108        }
19109
19110        return packageName;
19111    }
19112
19113    boolean isCallerVerifier(int callingUid) {
19114        final int callingUserId = UserHandle.getUserId(callingUid);
19115        return mRequiredVerifierPackage != null &&
19116                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
19117    }
19118
19119    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
19120        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
19121              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19122            return true;
19123        }
19124        final int callingUserId = UserHandle.getUserId(callingUid);
19125        // If the caller installed the pkgName, then allow it to silently uninstall.
19126        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
19127            return true;
19128        }
19129
19130        // Allow package verifier to silently uninstall.
19131        if (mRequiredVerifierPackage != null &&
19132                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
19133            return true;
19134        }
19135
19136        // Allow package uninstaller to silently uninstall.
19137        if (mRequiredUninstallerPackage != null &&
19138                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
19139            return true;
19140        }
19141
19142        // Allow storage manager to silently uninstall.
19143        if (mStorageManagerPackage != null &&
19144                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
19145            return true;
19146        }
19147
19148        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
19149        // uninstall for device owner provisioning.
19150        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
19151                == PERMISSION_GRANTED) {
19152            return true;
19153        }
19154
19155        return false;
19156    }
19157
19158    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
19159        int[] result = EMPTY_INT_ARRAY;
19160        for (int userId : userIds) {
19161            if (getBlockUninstallForUser(packageName, userId)) {
19162                result = ArrayUtils.appendInt(result, userId);
19163            }
19164        }
19165        return result;
19166    }
19167
19168    @Override
19169    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
19170        final int callingUid = Binder.getCallingUid();
19171        if (getInstantAppPackageName(callingUid) != null
19172                && !isCallerSameApp(packageName, callingUid)) {
19173            return false;
19174        }
19175        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
19176    }
19177
19178    private boolean isPackageDeviceAdmin(String packageName, int userId) {
19179        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
19180                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
19181        try {
19182            if (dpm != null) {
19183                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
19184                        /* callingUserOnly =*/ false);
19185                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
19186                        : deviceOwnerComponentName.getPackageName();
19187                // Does the package contains the device owner?
19188                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
19189                // this check is probably not needed, since DO should be registered as a device
19190                // admin on some user too. (Original bug for this: b/17657954)
19191                if (packageName.equals(deviceOwnerPackageName)) {
19192                    return true;
19193                }
19194                // Does it contain a device admin for any user?
19195                int[] users;
19196                if (userId == UserHandle.USER_ALL) {
19197                    users = sUserManager.getUserIds();
19198                } else {
19199                    users = new int[]{userId};
19200                }
19201                for (int i = 0; i < users.length; ++i) {
19202                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
19203                        return true;
19204                    }
19205                }
19206            }
19207        } catch (RemoteException e) {
19208        }
19209        return false;
19210    }
19211
19212    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
19213        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
19214    }
19215
19216    /**
19217     *  This method is an internal method that could be get invoked either
19218     *  to delete an installed package or to clean up a failed installation.
19219     *  After deleting an installed package, a broadcast is sent to notify any
19220     *  listeners that the package has been removed. For cleaning up a failed
19221     *  installation, the broadcast is not necessary since the package's
19222     *  installation wouldn't have sent the initial broadcast either
19223     *  The key steps in deleting a package are
19224     *  deleting the package information in internal structures like mPackages,
19225     *  deleting the packages base directories through installd
19226     *  updating mSettings to reflect current status
19227     *  persisting settings for later use
19228     *  sending a broadcast if necessary
19229     */
19230    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
19231        final PackageRemovedInfo info = new PackageRemovedInfo(this);
19232        final boolean res;
19233
19234        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
19235                ? UserHandle.USER_ALL : userId;
19236
19237        if (isPackageDeviceAdmin(packageName, removeUser)) {
19238            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
19239            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
19240        }
19241
19242        PackageSetting uninstalledPs = null;
19243        PackageParser.Package pkg = null;
19244
19245        // for the uninstall-updates case and restricted profiles, remember the per-
19246        // user handle installed state
19247        int[] allUsers;
19248        synchronized (mPackages) {
19249            uninstalledPs = mSettings.mPackages.get(packageName);
19250            if (uninstalledPs == null) {
19251                Slog.w(TAG, "Not removing non-existent package " + packageName);
19252                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19253            }
19254
19255            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
19256                    && uninstalledPs.versionCode != versionCode) {
19257                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
19258                        + uninstalledPs.versionCode + " != " + versionCode);
19259                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19260            }
19261
19262            // Static shared libs can be declared by any package, so let us not
19263            // allow removing a package if it provides a lib others depend on.
19264            pkg = mPackages.get(packageName);
19265
19266            allUsers = sUserManager.getUserIds();
19267
19268            if (pkg != null && pkg.staticSharedLibName != null) {
19269                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
19270                        pkg.staticSharedLibVersion);
19271                if (libEntry != null) {
19272                    for (int currUserId : allUsers) {
19273                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
19274                            continue;
19275                        }
19276                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
19277                                libEntry.info, 0, currUserId);
19278                        if (!ArrayUtils.isEmpty(libClientPackages)) {
19279                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
19280                                    + " hosting lib " + libEntry.info.getName() + " version "
19281                                    + libEntry.info.getVersion() + " used by " + libClientPackages
19282                                    + " for user " + currUserId);
19283                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
19284                        }
19285                    }
19286                }
19287            }
19288
19289            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
19290        }
19291
19292        final int freezeUser;
19293        if (isUpdatedSystemApp(uninstalledPs)
19294                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
19295            // We're downgrading a system app, which will apply to all users, so
19296            // freeze them all during the downgrade
19297            freezeUser = UserHandle.USER_ALL;
19298        } else {
19299            freezeUser = removeUser;
19300        }
19301
19302        synchronized (mInstallLock) {
19303            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
19304            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
19305                    deleteFlags, "deletePackageX")) {
19306                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
19307                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
19308            }
19309            synchronized (mPackages) {
19310                if (res) {
19311                    if (pkg != null) {
19312                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
19313                    }
19314                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
19315                    updateInstantAppInstallerLocked(packageName);
19316                }
19317            }
19318        }
19319
19320        if (res) {
19321            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
19322            info.sendPackageRemovedBroadcasts(killApp);
19323            info.sendSystemPackageUpdatedBroadcasts();
19324            info.sendSystemPackageAppearedBroadcasts();
19325        }
19326        // Force a gc here.
19327        Runtime.getRuntime().gc();
19328        // Delete the resources here after sending the broadcast to let
19329        // other processes clean up before deleting resources.
19330        if (info.args != null) {
19331            synchronized (mInstallLock) {
19332                info.args.doPostDeleteLI(true);
19333            }
19334        }
19335
19336        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19337    }
19338
19339    static class PackageRemovedInfo {
19340        final PackageSender packageSender;
19341        String removedPackage;
19342        String installerPackageName;
19343        int uid = -1;
19344        int removedAppId = -1;
19345        int[] origUsers;
19346        int[] removedUsers = null;
19347        int[] broadcastUsers = null;
19348        SparseArray<Integer> installReasons;
19349        boolean isRemovedPackageSystemUpdate = false;
19350        boolean isUpdate;
19351        boolean dataRemoved;
19352        boolean removedForAllUsers;
19353        boolean isStaticSharedLib;
19354        // Clean up resources deleted packages.
19355        InstallArgs args = null;
19356        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
19357        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
19358
19359        PackageRemovedInfo(PackageSender packageSender) {
19360            this.packageSender = packageSender;
19361        }
19362
19363        void sendPackageRemovedBroadcasts(boolean killApp) {
19364            sendPackageRemovedBroadcastInternal(killApp);
19365            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
19366            for (int i = 0; i < childCount; i++) {
19367                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19368                childInfo.sendPackageRemovedBroadcastInternal(killApp);
19369            }
19370        }
19371
19372        void sendSystemPackageUpdatedBroadcasts() {
19373            if (isRemovedPackageSystemUpdate) {
19374                sendSystemPackageUpdatedBroadcastsInternal();
19375                final int childCount = (removedChildPackages != null)
19376                        ? removedChildPackages.size() : 0;
19377                for (int i = 0; i < childCount; i++) {
19378                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19379                    if (childInfo.isRemovedPackageSystemUpdate) {
19380                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
19381                    }
19382                }
19383            }
19384        }
19385
19386        void sendSystemPackageAppearedBroadcasts() {
19387            final int packageCount = (appearedChildPackages != null)
19388                    ? appearedChildPackages.size() : 0;
19389            for (int i = 0; i < packageCount; i++) {
19390                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
19391                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
19392                    true /*sendBootCompleted*/, false /*startReceiver*/,
19393                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
19394            }
19395        }
19396
19397        private void sendSystemPackageUpdatedBroadcastsInternal() {
19398            Bundle extras = new Bundle(2);
19399            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
19400            extras.putBoolean(Intent.EXTRA_REPLACING, true);
19401            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19402                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19403            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19404                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19405            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
19406                null, null, 0, removedPackage, null, null);
19407            if (installerPackageName != null) {
19408                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19409                        removedPackage, extras, 0 /*flags*/,
19410                        installerPackageName, null, null);
19411                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19412                        removedPackage, extras, 0 /*flags*/,
19413                        installerPackageName, null, null);
19414            }
19415        }
19416
19417        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
19418            // Don't send static shared library removal broadcasts as these
19419            // libs are visible only the the apps that depend on them an one
19420            // cannot remove the library if it has a dependency.
19421            if (isStaticSharedLib) {
19422                return;
19423            }
19424            Bundle extras = new Bundle(2);
19425            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
19426            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
19427            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
19428            if (isUpdate || isRemovedPackageSystemUpdate) {
19429                extras.putBoolean(Intent.EXTRA_REPLACING, true);
19430            }
19431            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
19432            if (removedPackage != null) {
19433                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19434                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
19435                if (installerPackageName != null) {
19436                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19437                            removedPackage, extras, 0 /*flags*/,
19438                            installerPackageName, null, broadcastUsers);
19439                }
19440                if (dataRemoved && !isRemovedPackageSystemUpdate) {
19441                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
19442                        removedPackage, extras,
19443                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19444                        null, null, broadcastUsers);
19445                }
19446            }
19447            if (removedAppId >= 0) {
19448                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
19449                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19450                    null, null, broadcastUsers);
19451            }
19452        }
19453
19454        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
19455            removedUsers = userIds;
19456            if (removedUsers == null) {
19457                broadcastUsers = null;
19458                return;
19459            }
19460
19461            broadcastUsers = EMPTY_INT_ARRAY;
19462            for (int i = userIds.length - 1; i >= 0; --i) {
19463                final int userId = userIds[i];
19464                if (deletedPackageSetting.getInstantApp(userId)) {
19465                    continue;
19466                }
19467                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
19468            }
19469        }
19470    }
19471
19472    /*
19473     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
19474     * flag is not set, the data directory is removed as well.
19475     * make sure this flag is set for partially installed apps. If not its meaningless to
19476     * delete a partially installed application.
19477     */
19478    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
19479            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
19480        String packageName = ps.name;
19481        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
19482        // Retrieve object to delete permissions for shared user later on
19483        final PackageParser.Package deletedPkg;
19484        final PackageSetting deletedPs;
19485        // reader
19486        synchronized (mPackages) {
19487            deletedPkg = mPackages.get(packageName);
19488            deletedPs = mSettings.mPackages.get(packageName);
19489            if (outInfo != null) {
19490                outInfo.removedPackage = packageName;
19491                outInfo.installerPackageName = ps.installerPackageName;
19492                outInfo.isStaticSharedLib = deletedPkg != null
19493                        && deletedPkg.staticSharedLibName != null;
19494                outInfo.populateUsers(deletedPs == null ? null
19495                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
19496            }
19497        }
19498
19499        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
19500
19501        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
19502            final PackageParser.Package resolvedPkg;
19503            if (deletedPkg != null) {
19504                resolvedPkg = deletedPkg;
19505            } else {
19506                // We don't have a parsed package when it lives on an ejected
19507                // adopted storage device, so fake something together
19508                resolvedPkg = new PackageParser.Package(ps.name);
19509                resolvedPkg.setVolumeUuid(ps.volumeUuid);
19510            }
19511            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
19512                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19513            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
19514            if (outInfo != null) {
19515                outInfo.dataRemoved = true;
19516            }
19517            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
19518        }
19519
19520        int removedAppId = -1;
19521
19522        // writer
19523        synchronized (mPackages) {
19524            boolean installedStateChanged = false;
19525            if (deletedPs != null) {
19526                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
19527                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
19528                    clearDefaultBrowserIfNeeded(packageName);
19529                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
19530                    removedAppId = mSettings.removePackageLPw(packageName);
19531                    if (outInfo != null) {
19532                        outInfo.removedAppId = removedAppId;
19533                    }
19534                    updatePermissionsLPw(deletedPs.name, null, 0);
19535                    if (deletedPs.sharedUser != null) {
19536                        // Remove permissions associated with package. Since runtime
19537                        // permissions are per user we have to kill the removed package
19538                        // or packages running under the shared user of the removed
19539                        // package if revoking the permissions requested only by the removed
19540                        // package is successful and this causes a change in gids.
19541                        for (int userId : UserManagerService.getInstance().getUserIds()) {
19542                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19543                                    userId);
19544                            if (userIdToKill == UserHandle.USER_ALL
19545                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
19546                                // If gids changed for this user, kill all affected packages.
19547                                mHandler.post(new Runnable() {
19548                                    @Override
19549                                    public void run() {
19550                                        // This has to happen with no lock held.
19551                                        killApplication(deletedPs.name, deletedPs.appId,
19552                                                KILL_APP_REASON_GIDS_CHANGED);
19553                                    }
19554                                });
19555                                break;
19556                            }
19557                        }
19558                    }
19559                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19560                }
19561                // make sure to preserve per-user disabled state if this removal was just
19562                // a downgrade of a system app to the factory package
19563                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19564                    if (DEBUG_REMOVE) {
19565                        Slog.d(TAG, "Propagating install state across downgrade");
19566                    }
19567                    for (int userId : allUserHandles) {
19568                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19569                        if (DEBUG_REMOVE) {
19570                            Slog.d(TAG, "    user " + userId + " => " + installed);
19571                        }
19572                        if (installed != ps.getInstalled(userId)) {
19573                            installedStateChanged = true;
19574                        }
19575                        ps.setInstalled(installed, userId);
19576                    }
19577                }
19578            }
19579            // can downgrade to reader
19580            if (writeSettings) {
19581                // Save settings now
19582                mSettings.writeLPr();
19583            }
19584            if (installedStateChanged) {
19585                mSettings.writeKernelMappingLPr(ps);
19586            }
19587        }
19588        if (removedAppId != -1) {
19589            // A user ID was deleted here. Go through all users and remove it
19590            // from KeyStore.
19591            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19592        }
19593    }
19594
19595    static boolean locationIsPrivileged(File path) {
19596        try {
19597            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19598                    .getCanonicalPath();
19599            return path.getCanonicalPath().startsWith(privilegedAppDir);
19600        } catch (IOException e) {
19601            Slog.e(TAG, "Unable to access code path " + path);
19602        }
19603        return false;
19604    }
19605
19606    /*
19607     * Tries to delete system package.
19608     */
19609    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19610            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19611            boolean writeSettings) {
19612        if (deletedPs.parentPackageName != null) {
19613            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19614            return false;
19615        }
19616
19617        final boolean applyUserRestrictions
19618                = (allUserHandles != null) && (outInfo.origUsers != null);
19619        final PackageSetting disabledPs;
19620        // Confirm if the system package has been updated
19621        // An updated system app can be deleted. This will also have to restore
19622        // the system pkg from system partition
19623        // reader
19624        synchronized (mPackages) {
19625            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19626        }
19627
19628        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19629                + " disabledPs=" + disabledPs);
19630
19631        if (disabledPs == null) {
19632            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19633            return false;
19634        } else if (DEBUG_REMOVE) {
19635            Slog.d(TAG, "Deleting system pkg from data partition");
19636        }
19637
19638        if (DEBUG_REMOVE) {
19639            if (applyUserRestrictions) {
19640                Slog.d(TAG, "Remembering install states:");
19641                for (int userId : allUserHandles) {
19642                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19643                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
19644                }
19645            }
19646        }
19647
19648        // Delete the updated package
19649        outInfo.isRemovedPackageSystemUpdate = true;
19650        if (outInfo.removedChildPackages != null) {
19651            final int childCount = (deletedPs.childPackageNames != null)
19652                    ? deletedPs.childPackageNames.size() : 0;
19653            for (int i = 0; i < childCount; i++) {
19654                String childPackageName = deletedPs.childPackageNames.get(i);
19655                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19656                        .contains(childPackageName)) {
19657                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19658                            childPackageName);
19659                    if (childInfo != null) {
19660                        childInfo.isRemovedPackageSystemUpdate = true;
19661                    }
19662                }
19663            }
19664        }
19665
19666        if (disabledPs.versionCode < deletedPs.versionCode) {
19667            // Delete data for downgrades
19668            flags &= ~PackageManager.DELETE_KEEP_DATA;
19669        } else {
19670            // Preserve data by setting flag
19671            flags |= PackageManager.DELETE_KEEP_DATA;
19672        }
19673
19674        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19675                outInfo, writeSettings, disabledPs.pkg);
19676        if (!ret) {
19677            return false;
19678        }
19679
19680        // writer
19681        synchronized (mPackages) {
19682            // Reinstate the old system package
19683            enableSystemPackageLPw(disabledPs.pkg);
19684            // Remove any native libraries from the upgraded package.
19685            removeNativeBinariesLI(deletedPs);
19686        }
19687
19688        // Install the system package
19689        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19690        int parseFlags = mDefParseFlags
19691                | PackageParser.PARSE_MUST_BE_APK
19692                | PackageParser.PARSE_IS_SYSTEM
19693                | PackageParser.PARSE_IS_SYSTEM_DIR;
19694        if (locationIsPrivileged(disabledPs.codePath)) {
19695            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19696        }
19697
19698        final PackageParser.Package newPkg;
19699        try {
19700            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
19701                0 /* currentTime */, null);
19702        } catch (PackageManagerException e) {
19703            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19704                    + e.getMessage());
19705            return false;
19706        }
19707
19708        try {
19709            // update shared libraries for the newly re-installed system package
19710            updateSharedLibrariesLPr(newPkg, null);
19711        } catch (PackageManagerException e) {
19712            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19713        }
19714
19715        prepareAppDataAfterInstallLIF(newPkg);
19716
19717        // writer
19718        synchronized (mPackages) {
19719            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19720
19721            // Propagate the permissions state as we do not want to drop on the floor
19722            // runtime permissions. The update permissions method below will take
19723            // care of removing obsolete permissions and grant install permissions.
19724            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
19725            updatePermissionsLPw(newPkg.packageName, newPkg,
19726                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19727
19728            if (applyUserRestrictions) {
19729                boolean installedStateChanged = false;
19730                if (DEBUG_REMOVE) {
19731                    Slog.d(TAG, "Propagating install state across reinstall");
19732                }
19733                for (int userId : allUserHandles) {
19734                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19735                    if (DEBUG_REMOVE) {
19736                        Slog.d(TAG, "    user " + userId + " => " + installed);
19737                    }
19738                    if (installed != ps.getInstalled(userId)) {
19739                        installedStateChanged = true;
19740                    }
19741                    ps.setInstalled(installed, userId);
19742
19743                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19744                }
19745                // Regardless of writeSettings we need to ensure that this restriction
19746                // state propagation is persisted
19747                mSettings.writeAllUsersPackageRestrictionsLPr();
19748                if (installedStateChanged) {
19749                    mSettings.writeKernelMappingLPr(ps);
19750                }
19751            }
19752            // can downgrade to reader here
19753            if (writeSettings) {
19754                mSettings.writeLPr();
19755            }
19756        }
19757        return true;
19758    }
19759
19760    private boolean deleteInstalledPackageLIF(PackageSetting ps,
19761            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19762            PackageRemovedInfo outInfo, boolean writeSettings,
19763            PackageParser.Package replacingPackage) {
19764        synchronized (mPackages) {
19765            if (outInfo != null) {
19766                outInfo.uid = ps.appId;
19767            }
19768
19769            if (outInfo != null && outInfo.removedChildPackages != null) {
19770                final int childCount = (ps.childPackageNames != null)
19771                        ? ps.childPackageNames.size() : 0;
19772                for (int i = 0; i < childCount; i++) {
19773                    String childPackageName = ps.childPackageNames.get(i);
19774                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
19775                    if (childPs == null) {
19776                        return false;
19777                    }
19778                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19779                            childPackageName);
19780                    if (childInfo != null) {
19781                        childInfo.uid = childPs.appId;
19782                    }
19783                }
19784            }
19785        }
19786
19787        // Delete package data from internal structures and also remove data if flag is set
19788        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
19789
19790        // Delete the child packages data
19791        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
19792        for (int i = 0; i < childCount; i++) {
19793            PackageSetting childPs;
19794            synchronized (mPackages) {
19795                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
19796            }
19797            if (childPs != null) {
19798                PackageRemovedInfo childOutInfo = (outInfo != null
19799                        && outInfo.removedChildPackages != null)
19800                        ? outInfo.removedChildPackages.get(childPs.name) : null;
19801                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
19802                        && (replacingPackage != null
19803                        && !replacingPackage.hasChildPackage(childPs.name))
19804                        ? flags & ~DELETE_KEEP_DATA : flags;
19805                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
19806                        deleteFlags, writeSettings);
19807            }
19808        }
19809
19810        // Delete application code and resources only for parent packages
19811        if (ps.parentPackageName == null) {
19812            if (deleteCodeAndResources && (outInfo != null)) {
19813                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
19814                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
19815                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
19816            }
19817        }
19818
19819        return true;
19820    }
19821
19822    @Override
19823    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
19824            int userId) {
19825        mContext.enforceCallingOrSelfPermission(
19826                android.Manifest.permission.DELETE_PACKAGES, null);
19827        synchronized (mPackages) {
19828            // Cannot block uninstall of static shared libs as they are
19829            // considered a part of the using app (emulating static linking).
19830            // Also static libs are installed always on internal storage.
19831            PackageParser.Package pkg = mPackages.get(packageName);
19832            if (pkg != null && pkg.staticSharedLibName != null) {
19833                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
19834                        + " providing static shared library: " + pkg.staticSharedLibName);
19835                return false;
19836            }
19837            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
19838            mSettings.writePackageRestrictionsLPr(userId);
19839        }
19840        return true;
19841    }
19842
19843    @Override
19844    public boolean getBlockUninstallForUser(String packageName, int userId) {
19845        synchronized (mPackages) {
19846            final PackageSetting ps = mSettings.mPackages.get(packageName);
19847            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
19848                return false;
19849            }
19850            return mSettings.getBlockUninstallLPr(userId, packageName);
19851        }
19852    }
19853
19854    @Override
19855    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
19856        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
19857        synchronized (mPackages) {
19858            PackageSetting ps = mSettings.mPackages.get(packageName);
19859            if (ps == null) {
19860                Log.w(TAG, "Package doesn't exist: " + packageName);
19861                return false;
19862            }
19863            if (systemUserApp) {
19864                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19865            } else {
19866                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19867            }
19868            mSettings.writeLPr();
19869        }
19870        return true;
19871    }
19872
19873    /*
19874     * This method handles package deletion in general
19875     */
19876    private boolean deletePackageLIF(String packageName, UserHandle user,
19877            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
19878            PackageRemovedInfo outInfo, boolean writeSettings,
19879            PackageParser.Package replacingPackage) {
19880        if (packageName == null) {
19881            Slog.w(TAG, "Attempt to delete null packageName.");
19882            return false;
19883        }
19884
19885        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
19886
19887        PackageSetting ps;
19888        synchronized (mPackages) {
19889            ps = mSettings.mPackages.get(packageName);
19890            if (ps == null) {
19891                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19892                return false;
19893            }
19894
19895            if (ps.parentPackageName != null && (!isSystemApp(ps)
19896                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
19897                if (DEBUG_REMOVE) {
19898                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
19899                            + ((user == null) ? UserHandle.USER_ALL : user));
19900                }
19901                final int removedUserId = (user != null) ? user.getIdentifier()
19902                        : UserHandle.USER_ALL;
19903                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
19904                    return false;
19905                }
19906                markPackageUninstalledForUserLPw(ps, user);
19907                scheduleWritePackageRestrictionsLocked(user);
19908                return true;
19909            }
19910        }
19911
19912        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
19913                && user.getIdentifier() != UserHandle.USER_ALL)) {
19914            // The caller is asking that the package only be deleted for a single
19915            // user.  To do this, we just mark its uninstalled state and delete
19916            // its data. If this is a system app, we only allow this to happen if
19917            // they have set the special DELETE_SYSTEM_APP which requests different
19918            // semantics than normal for uninstalling system apps.
19919            markPackageUninstalledForUserLPw(ps, user);
19920
19921            if (!isSystemApp(ps)) {
19922                // Do not uninstall the APK if an app should be cached
19923                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
19924                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
19925                    // Other user still have this package installed, so all
19926                    // we need to do is clear this user's data and save that
19927                    // it is uninstalled.
19928                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
19929                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19930                        return false;
19931                    }
19932                    scheduleWritePackageRestrictionsLocked(user);
19933                    return true;
19934                } else {
19935                    // We need to set it back to 'installed' so the uninstall
19936                    // broadcasts will be sent correctly.
19937                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
19938                    ps.setInstalled(true, user.getIdentifier());
19939                    mSettings.writeKernelMappingLPr(ps);
19940                }
19941            } else {
19942                // This is a system app, so we assume that the
19943                // other users still have this package installed, so all
19944                // we need to do is clear this user's data and save that
19945                // it is uninstalled.
19946                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
19947                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19948                    return false;
19949                }
19950                scheduleWritePackageRestrictionsLocked(user);
19951                return true;
19952            }
19953        }
19954
19955        // If we are deleting a composite package for all users, keep track
19956        // of result for each child.
19957        if (ps.childPackageNames != null && outInfo != null) {
19958            synchronized (mPackages) {
19959                final int childCount = ps.childPackageNames.size();
19960                outInfo.removedChildPackages = new ArrayMap<>(childCount);
19961                for (int i = 0; i < childCount; i++) {
19962                    String childPackageName = ps.childPackageNames.get(i);
19963                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
19964                    childInfo.removedPackage = childPackageName;
19965                    childInfo.installerPackageName = ps.installerPackageName;
19966                    outInfo.removedChildPackages.put(childPackageName, childInfo);
19967                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19968                    if (childPs != null) {
19969                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
19970                    }
19971                }
19972            }
19973        }
19974
19975        boolean ret = false;
19976        if (isSystemApp(ps)) {
19977            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
19978            // When an updated system application is deleted we delete the existing resources
19979            // as well and fall back to existing code in system partition
19980            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
19981        } else {
19982            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
19983            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
19984                    outInfo, writeSettings, replacingPackage);
19985        }
19986
19987        // Take a note whether we deleted the package for all users
19988        if (outInfo != null) {
19989            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
19990            if (outInfo.removedChildPackages != null) {
19991                synchronized (mPackages) {
19992                    final int childCount = outInfo.removedChildPackages.size();
19993                    for (int i = 0; i < childCount; i++) {
19994                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
19995                        if (childInfo != null) {
19996                            childInfo.removedForAllUsers = mPackages.get(
19997                                    childInfo.removedPackage) == null;
19998                        }
19999                    }
20000                }
20001            }
20002            // If we uninstalled an update to a system app there may be some
20003            // child packages that appeared as they are declared in the system
20004            // app but were not declared in the update.
20005            if (isSystemApp(ps)) {
20006                synchronized (mPackages) {
20007                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
20008                    final int childCount = (updatedPs.childPackageNames != null)
20009                            ? updatedPs.childPackageNames.size() : 0;
20010                    for (int i = 0; i < childCount; i++) {
20011                        String childPackageName = updatedPs.childPackageNames.get(i);
20012                        if (outInfo.removedChildPackages == null
20013                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
20014                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
20015                            if (childPs == null) {
20016                                continue;
20017                            }
20018                            PackageInstalledInfo installRes = new PackageInstalledInfo();
20019                            installRes.name = childPackageName;
20020                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
20021                            installRes.pkg = mPackages.get(childPackageName);
20022                            installRes.uid = childPs.pkg.applicationInfo.uid;
20023                            if (outInfo.appearedChildPackages == null) {
20024                                outInfo.appearedChildPackages = new ArrayMap<>();
20025                            }
20026                            outInfo.appearedChildPackages.put(childPackageName, installRes);
20027                        }
20028                    }
20029                }
20030            }
20031        }
20032
20033        return ret;
20034    }
20035
20036    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
20037        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
20038                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
20039        for (int nextUserId : userIds) {
20040            if (DEBUG_REMOVE) {
20041                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
20042            }
20043            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
20044                    false /*installed*/,
20045                    true /*stopped*/,
20046                    true /*notLaunched*/,
20047                    false /*hidden*/,
20048                    false /*suspended*/,
20049                    false /*instantApp*/,
20050                    false /*virtualPreload*/,
20051                    null /*lastDisableAppCaller*/,
20052                    null /*enabledComponents*/,
20053                    null /*disabledComponents*/,
20054                    ps.readUserState(nextUserId).domainVerificationStatus,
20055                    0, PackageManager.INSTALL_REASON_UNKNOWN);
20056        }
20057        mSettings.writeKernelMappingLPr(ps);
20058    }
20059
20060    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
20061            PackageRemovedInfo outInfo) {
20062        final PackageParser.Package pkg;
20063        synchronized (mPackages) {
20064            pkg = mPackages.get(ps.name);
20065        }
20066
20067        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
20068                : new int[] {userId};
20069        for (int nextUserId : userIds) {
20070            if (DEBUG_REMOVE) {
20071                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
20072                        + nextUserId);
20073            }
20074
20075            destroyAppDataLIF(pkg, userId,
20076                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20077            destroyAppProfilesLIF(pkg, userId);
20078            clearDefaultBrowserIfNeededForUser(ps.name, userId);
20079            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
20080            schedulePackageCleaning(ps.name, nextUserId, false);
20081            synchronized (mPackages) {
20082                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
20083                    scheduleWritePackageRestrictionsLocked(nextUserId);
20084                }
20085                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
20086            }
20087        }
20088
20089        if (outInfo != null) {
20090            outInfo.removedPackage = ps.name;
20091            outInfo.installerPackageName = ps.installerPackageName;
20092            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
20093            outInfo.removedAppId = ps.appId;
20094            outInfo.removedUsers = userIds;
20095            outInfo.broadcastUsers = userIds;
20096        }
20097
20098        return true;
20099    }
20100
20101    private final class ClearStorageConnection implements ServiceConnection {
20102        IMediaContainerService mContainerService;
20103
20104        @Override
20105        public void onServiceConnected(ComponentName name, IBinder service) {
20106            synchronized (this) {
20107                mContainerService = IMediaContainerService.Stub
20108                        .asInterface(Binder.allowBlocking(service));
20109                notifyAll();
20110            }
20111        }
20112
20113        @Override
20114        public void onServiceDisconnected(ComponentName name) {
20115        }
20116    }
20117
20118    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
20119        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
20120
20121        final boolean mounted;
20122        if (Environment.isExternalStorageEmulated()) {
20123            mounted = true;
20124        } else {
20125            final String status = Environment.getExternalStorageState();
20126
20127            mounted = status.equals(Environment.MEDIA_MOUNTED)
20128                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
20129        }
20130
20131        if (!mounted) {
20132            return;
20133        }
20134
20135        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
20136        int[] users;
20137        if (userId == UserHandle.USER_ALL) {
20138            users = sUserManager.getUserIds();
20139        } else {
20140            users = new int[] { userId };
20141        }
20142        final ClearStorageConnection conn = new ClearStorageConnection();
20143        if (mContext.bindServiceAsUser(
20144                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
20145            try {
20146                for (int curUser : users) {
20147                    long timeout = SystemClock.uptimeMillis() + 5000;
20148                    synchronized (conn) {
20149                        long now;
20150                        while (conn.mContainerService == null &&
20151                                (now = SystemClock.uptimeMillis()) < timeout) {
20152                            try {
20153                                conn.wait(timeout - now);
20154                            } catch (InterruptedException e) {
20155                            }
20156                        }
20157                    }
20158                    if (conn.mContainerService == null) {
20159                        return;
20160                    }
20161
20162                    final UserEnvironment userEnv = new UserEnvironment(curUser);
20163                    clearDirectory(conn.mContainerService,
20164                            userEnv.buildExternalStorageAppCacheDirs(packageName));
20165                    if (allData) {
20166                        clearDirectory(conn.mContainerService,
20167                                userEnv.buildExternalStorageAppDataDirs(packageName));
20168                        clearDirectory(conn.mContainerService,
20169                                userEnv.buildExternalStorageAppMediaDirs(packageName));
20170                    }
20171                }
20172            } finally {
20173                mContext.unbindService(conn);
20174            }
20175        }
20176    }
20177
20178    @Override
20179    public void clearApplicationProfileData(String packageName) {
20180        enforceSystemOrRoot("Only the system can clear all profile data");
20181
20182        final PackageParser.Package pkg;
20183        synchronized (mPackages) {
20184            pkg = mPackages.get(packageName);
20185        }
20186
20187        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
20188            synchronized (mInstallLock) {
20189                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
20190            }
20191        }
20192    }
20193
20194    @Override
20195    public void clearApplicationUserData(final String packageName,
20196            final IPackageDataObserver observer, final int userId) {
20197        mContext.enforceCallingOrSelfPermission(
20198                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
20199
20200        final int callingUid = Binder.getCallingUid();
20201        enforceCrossUserPermission(callingUid, userId,
20202                true /* requireFullPermission */, false /* checkShell */, "clear application data");
20203
20204        final PackageSetting ps = mSettings.getPackageLPr(packageName);
20205        if (ps != null && filterAppAccessLPr(ps, callingUid, userId)) {
20206            return;
20207        }
20208        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
20209            throw new SecurityException("Cannot clear data for a protected package: "
20210                    + packageName);
20211        }
20212        // Queue up an async operation since the package deletion may take a little while.
20213        mHandler.post(new Runnable() {
20214            public void run() {
20215                mHandler.removeCallbacks(this);
20216                final boolean succeeded;
20217                try (PackageFreezer freezer = freezePackage(packageName,
20218                        "clearApplicationUserData")) {
20219                    synchronized (mInstallLock) {
20220                        succeeded = clearApplicationUserDataLIF(packageName, userId);
20221                    }
20222                    clearExternalStorageDataSync(packageName, userId, true);
20223                    synchronized (mPackages) {
20224                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
20225                                packageName, userId);
20226                    }
20227                }
20228                if (succeeded) {
20229                    // invoke DeviceStorageMonitor's update method to clear any notifications
20230                    DeviceStorageMonitorInternal dsm = LocalServices
20231                            .getService(DeviceStorageMonitorInternal.class);
20232                    if (dsm != null) {
20233                        dsm.checkMemory();
20234                    }
20235                }
20236                if(observer != null) {
20237                    try {
20238                        observer.onRemoveCompleted(packageName, succeeded);
20239                    } catch (RemoteException e) {
20240                        Log.i(TAG, "Observer no longer exists.");
20241                    }
20242                } //end if observer
20243            } //end run
20244        });
20245    }
20246
20247    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
20248        if (packageName == null) {
20249            Slog.w(TAG, "Attempt to delete null packageName.");
20250            return false;
20251        }
20252
20253        // Try finding details about the requested package
20254        PackageParser.Package pkg;
20255        synchronized (mPackages) {
20256            pkg = mPackages.get(packageName);
20257            if (pkg == null) {
20258                final PackageSetting ps = mSettings.mPackages.get(packageName);
20259                if (ps != null) {
20260                    pkg = ps.pkg;
20261                }
20262            }
20263
20264            if (pkg == null) {
20265                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
20266                return false;
20267            }
20268
20269            PackageSetting ps = (PackageSetting) pkg.mExtras;
20270            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
20271        }
20272
20273        clearAppDataLIF(pkg, userId,
20274                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20275
20276        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20277        removeKeystoreDataIfNeeded(userId, appId);
20278
20279        UserManagerInternal umInternal = getUserManagerInternal();
20280        final int flags;
20281        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
20282            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
20283        } else if (umInternal.isUserRunning(userId)) {
20284            flags = StorageManager.FLAG_STORAGE_DE;
20285        } else {
20286            flags = 0;
20287        }
20288        prepareAppDataContentsLIF(pkg, userId, flags);
20289
20290        return true;
20291    }
20292
20293    /**
20294     * Reverts user permission state changes (permissions and flags) in
20295     * all packages for a given user.
20296     *
20297     * @param userId The device user for which to do a reset.
20298     */
20299    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
20300        final int packageCount = mPackages.size();
20301        for (int i = 0; i < packageCount; i++) {
20302            PackageParser.Package pkg = mPackages.valueAt(i);
20303            PackageSetting ps = (PackageSetting) pkg.mExtras;
20304            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
20305        }
20306    }
20307
20308    private void resetNetworkPolicies(int userId) {
20309        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
20310    }
20311
20312    /**
20313     * Reverts user permission state changes (permissions and flags).
20314     *
20315     * @param ps The package for which to reset.
20316     * @param userId The device user for which to do a reset.
20317     */
20318    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
20319            final PackageSetting ps, final int userId) {
20320        if (ps.pkg == null) {
20321            return;
20322        }
20323
20324        // These are flags that can change base on user actions.
20325        final int userSettableMask = FLAG_PERMISSION_USER_SET
20326                | FLAG_PERMISSION_USER_FIXED
20327                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
20328                | FLAG_PERMISSION_REVIEW_REQUIRED;
20329
20330        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
20331                | FLAG_PERMISSION_POLICY_FIXED;
20332
20333        boolean writeInstallPermissions = false;
20334        boolean writeRuntimePermissions = false;
20335
20336        final int permissionCount = ps.pkg.requestedPermissions.size();
20337        for (int i = 0; i < permissionCount; i++) {
20338            String permission = ps.pkg.requestedPermissions.get(i);
20339
20340            BasePermission bp = mSettings.mPermissions.get(permission);
20341            if (bp == null) {
20342                continue;
20343            }
20344
20345            // If shared user we just reset the state to which only this app contributed.
20346            if (ps.sharedUser != null) {
20347                boolean used = false;
20348                final int packageCount = ps.sharedUser.packages.size();
20349                for (int j = 0; j < packageCount; j++) {
20350                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
20351                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
20352                            && pkg.pkg.requestedPermissions.contains(permission)) {
20353                        used = true;
20354                        break;
20355                    }
20356                }
20357                if (used) {
20358                    continue;
20359                }
20360            }
20361
20362            PermissionsState permissionsState = ps.getPermissionsState();
20363
20364            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
20365
20366            // Always clear the user settable flags.
20367            final boolean hasInstallState = permissionsState.getInstallPermissionState(
20368                    bp.name) != null;
20369            // If permission review is enabled and this is a legacy app, mark the
20370            // permission as requiring a review as this is the initial state.
20371            int flags = 0;
20372            if (mPermissionReviewRequired
20373                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
20374                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
20375            }
20376            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
20377                if (hasInstallState) {
20378                    writeInstallPermissions = true;
20379                } else {
20380                    writeRuntimePermissions = true;
20381                }
20382            }
20383
20384            // Below is only runtime permission handling.
20385            if (!bp.isRuntime()) {
20386                continue;
20387            }
20388
20389            // Never clobber system or policy.
20390            if ((oldFlags & policyOrSystemFlags) != 0) {
20391                continue;
20392            }
20393
20394            // If this permission was granted by default, make sure it is.
20395            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
20396                if (permissionsState.grantRuntimePermission(bp, userId)
20397                        != PERMISSION_OPERATION_FAILURE) {
20398                    writeRuntimePermissions = true;
20399                }
20400            // If permission review is enabled the permissions for a legacy apps
20401            // are represented as constantly granted runtime ones, so don't revoke.
20402            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
20403                // Otherwise, reset the permission.
20404                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
20405                switch (revokeResult) {
20406                    case PERMISSION_OPERATION_SUCCESS:
20407                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
20408                        writeRuntimePermissions = true;
20409                        final int appId = ps.appId;
20410                        mHandler.post(new Runnable() {
20411                            @Override
20412                            public void run() {
20413                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
20414                            }
20415                        });
20416                    } break;
20417                }
20418            }
20419        }
20420
20421        // Synchronously write as we are taking permissions away.
20422        if (writeRuntimePermissions) {
20423            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
20424        }
20425
20426        // Synchronously write as we are taking permissions away.
20427        if (writeInstallPermissions) {
20428            mSettings.writeLPr();
20429        }
20430    }
20431
20432    /**
20433     * Remove entries from the keystore daemon. Will only remove it if the
20434     * {@code appId} is valid.
20435     */
20436    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
20437        if (appId < 0) {
20438            return;
20439        }
20440
20441        final KeyStore keyStore = KeyStore.getInstance();
20442        if (keyStore != null) {
20443            if (userId == UserHandle.USER_ALL) {
20444                for (final int individual : sUserManager.getUserIds()) {
20445                    keyStore.clearUid(UserHandle.getUid(individual, appId));
20446                }
20447            } else {
20448                keyStore.clearUid(UserHandle.getUid(userId, appId));
20449            }
20450        } else {
20451            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
20452        }
20453    }
20454
20455    @Override
20456    public void deleteApplicationCacheFiles(final String packageName,
20457            final IPackageDataObserver observer) {
20458        final int userId = UserHandle.getCallingUserId();
20459        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
20460    }
20461
20462    @Override
20463    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
20464            final IPackageDataObserver observer) {
20465        final int callingUid = Binder.getCallingUid();
20466        mContext.enforceCallingOrSelfPermission(
20467                android.Manifest.permission.DELETE_CACHE_FILES, null);
20468        enforceCrossUserPermission(callingUid, userId,
20469                /* requireFullPermission= */ true, /* checkShell= */ false,
20470                "delete application cache files");
20471        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
20472                android.Manifest.permission.ACCESS_INSTANT_APPS);
20473
20474        final PackageParser.Package pkg;
20475        synchronized (mPackages) {
20476            pkg = mPackages.get(packageName);
20477        }
20478
20479        // Queue up an async operation since the package deletion may take a little while.
20480        mHandler.post(new Runnable() {
20481            public void run() {
20482                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
20483                boolean doClearData = true;
20484                if (ps != null) {
20485                    final boolean targetIsInstantApp =
20486                            ps.getInstantApp(UserHandle.getUserId(callingUid));
20487                    doClearData = !targetIsInstantApp
20488                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
20489                }
20490                if (doClearData) {
20491                    synchronized (mInstallLock) {
20492                        final int flags = StorageManager.FLAG_STORAGE_DE
20493                                | StorageManager.FLAG_STORAGE_CE;
20494                        // We're only clearing cache files, so we don't care if the
20495                        // app is unfrozen and still able to run
20496                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
20497                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20498                    }
20499                    clearExternalStorageDataSync(packageName, userId, false);
20500                }
20501                if (observer != null) {
20502                    try {
20503                        observer.onRemoveCompleted(packageName, true);
20504                    } catch (RemoteException e) {
20505                        Log.i(TAG, "Observer no longer exists.");
20506                    }
20507                }
20508            }
20509        });
20510    }
20511
20512    @Override
20513    public void getPackageSizeInfo(final String packageName, int userHandle,
20514            final IPackageStatsObserver observer) {
20515        throw new UnsupportedOperationException(
20516                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
20517    }
20518
20519    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
20520        final PackageSetting ps;
20521        synchronized (mPackages) {
20522            ps = mSettings.mPackages.get(packageName);
20523            if (ps == null) {
20524                Slog.w(TAG, "Failed to find settings for " + packageName);
20525                return false;
20526            }
20527        }
20528
20529        final String[] packageNames = { packageName };
20530        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
20531        final String[] codePaths = { ps.codePathString };
20532
20533        try {
20534            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20535                    ps.appId, ceDataInodes, codePaths, stats);
20536
20537            // For now, ignore code size of packages on system partition
20538            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20539                stats.codeSize = 0;
20540            }
20541
20542            // External clients expect these to be tracked separately
20543            stats.dataSize -= stats.cacheSize;
20544
20545        } catch (InstallerException e) {
20546            Slog.w(TAG, String.valueOf(e));
20547            return false;
20548        }
20549
20550        return true;
20551    }
20552
20553    private int getUidTargetSdkVersionLockedLPr(int uid) {
20554        Object obj = mSettings.getUserIdLPr(uid);
20555        if (obj instanceof SharedUserSetting) {
20556            final SharedUserSetting sus = (SharedUserSetting) obj;
20557            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20558            final Iterator<PackageSetting> it = sus.packages.iterator();
20559            while (it.hasNext()) {
20560                final PackageSetting ps = it.next();
20561                if (ps.pkg != null) {
20562                    int v = ps.pkg.applicationInfo.targetSdkVersion;
20563                    if (v < vers) vers = v;
20564                }
20565            }
20566            return vers;
20567        } else if (obj instanceof PackageSetting) {
20568            final PackageSetting ps = (PackageSetting) obj;
20569            if (ps.pkg != null) {
20570                return ps.pkg.applicationInfo.targetSdkVersion;
20571            }
20572        }
20573        return Build.VERSION_CODES.CUR_DEVELOPMENT;
20574    }
20575
20576    @Override
20577    public void addPreferredActivity(IntentFilter filter, int match,
20578            ComponentName[] set, ComponentName activity, int userId) {
20579        addPreferredActivityInternal(filter, match, set, activity, true, userId,
20580                "Adding preferred");
20581    }
20582
20583    private void addPreferredActivityInternal(IntentFilter filter, int match,
20584            ComponentName[] set, ComponentName activity, boolean always, int userId,
20585            String opname) {
20586        // writer
20587        int callingUid = Binder.getCallingUid();
20588        enforceCrossUserPermission(callingUid, userId,
20589                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20590        if (filter.countActions() == 0) {
20591            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20592            return;
20593        }
20594        synchronized (mPackages) {
20595            if (mContext.checkCallingOrSelfPermission(
20596                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20597                    != PackageManager.PERMISSION_GRANTED) {
20598                if (getUidTargetSdkVersionLockedLPr(callingUid)
20599                        < Build.VERSION_CODES.FROYO) {
20600                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20601                            + callingUid);
20602                    return;
20603                }
20604                mContext.enforceCallingOrSelfPermission(
20605                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20606            }
20607
20608            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20609            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20610                    + userId + ":");
20611            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20612            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20613            scheduleWritePackageRestrictionsLocked(userId);
20614            postPreferredActivityChangedBroadcast(userId);
20615        }
20616    }
20617
20618    private void postPreferredActivityChangedBroadcast(int userId) {
20619        mHandler.post(() -> {
20620            final IActivityManager am = ActivityManager.getService();
20621            if (am == null) {
20622                return;
20623            }
20624
20625            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20626            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20627            try {
20628                am.broadcastIntent(null, intent, null, null,
20629                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
20630                        null, false, false, userId);
20631            } catch (RemoteException e) {
20632            }
20633        });
20634    }
20635
20636    @Override
20637    public void replacePreferredActivity(IntentFilter filter, int match,
20638            ComponentName[] set, ComponentName activity, int userId) {
20639        if (filter.countActions() != 1) {
20640            throw new IllegalArgumentException(
20641                    "replacePreferredActivity expects filter to have only 1 action.");
20642        }
20643        if (filter.countDataAuthorities() != 0
20644                || filter.countDataPaths() != 0
20645                || filter.countDataSchemes() > 1
20646                || filter.countDataTypes() != 0) {
20647            throw new IllegalArgumentException(
20648                    "replacePreferredActivity expects filter to have no data authorities, " +
20649                    "paths, or types; and at most one scheme.");
20650        }
20651
20652        final int callingUid = Binder.getCallingUid();
20653        enforceCrossUserPermission(callingUid, userId,
20654                true /* requireFullPermission */, false /* checkShell */,
20655                "replace preferred activity");
20656        synchronized (mPackages) {
20657            if (mContext.checkCallingOrSelfPermission(
20658                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20659                    != PackageManager.PERMISSION_GRANTED) {
20660                if (getUidTargetSdkVersionLockedLPr(callingUid)
20661                        < Build.VERSION_CODES.FROYO) {
20662                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20663                            + Binder.getCallingUid());
20664                    return;
20665                }
20666                mContext.enforceCallingOrSelfPermission(
20667                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20668            }
20669
20670            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20671            if (pir != null) {
20672                // Get all of the existing entries that exactly match this filter.
20673                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20674                if (existing != null && existing.size() == 1) {
20675                    PreferredActivity cur = existing.get(0);
20676                    if (DEBUG_PREFERRED) {
20677                        Slog.i(TAG, "Checking replace of preferred:");
20678                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20679                        if (!cur.mPref.mAlways) {
20680                            Slog.i(TAG, "  -- CUR; not mAlways!");
20681                        } else {
20682                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
20683                            Slog.i(TAG, "  -- CUR: mSet="
20684                                    + Arrays.toString(cur.mPref.mSetComponents));
20685                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
20686                            Slog.i(TAG, "  -- NEW: mMatch="
20687                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
20688                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
20689                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
20690                        }
20691                    }
20692                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20693                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20694                            && cur.mPref.sameSet(set)) {
20695                        // Setting the preferred activity to what it happens to be already
20696                        if (DEBUG_PREFERRED) {
20697                            Slog.i(TAG, "Replacing with same preferred activity "
20698                                    + cur.mPref.mShortComponent + " for user "
20699                                    + userId + ":");
20700                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20701                        }
20702                        return;
20703                    }
20704                }
20705
20706                if (existing != null) {
20707                    if (DEBUG_PREFERRED) {
20708                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
20709                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20710                    }
20711                    for (int i = 0; i < existing.size(); i++) {
20712                        PreferredActivity pa = existing.get(i);
20713                        if (DEBUG_PREFERRED) {
20714                            Slog.i(TAG, "Removing existing preferred activity "
20715                                    + pa.mPref.mComponent + ":");
20716                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
20717                        }
20718                        pir.removeFilter(pa);
20719                    }
20720                }
20721            }
20722            addPreferredActivityInternal(filter, match, set, activity, true, userId,
20723                    "Replacing preferred");
20724        }
20725    }
20726
20727    @Override
20728    public void clearPackagePreferredActivities(String packageName) {
20729        final int callingUid = Binder.getCallingUid();
20730        if (getInstantAppPackageName(callingUid) != null) {
20731            return;
20732        }
20733        // writer
20734        synchronized (mPackages) {
20735            PackageParser.Package pkg = mPackages.get(packageName);
20736            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20737                if (mContext.checkCallingOrSelfPermission(
20738                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20739                        != PackageManager.PERMISSION_GRANTED) {
20740                    if (getUidTargetSdkVersionLockedLPr(callingUid)
20741                            < Build.VERSION_CODES.FROYO) {
20742                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20743                                + callingUid);
20744                        return;
20745                    }
20746                    mContext.enforceCallingOrSelfPermission(
20747                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20748                }
20749            }
20750            final PackageSetting ps = mSettings.getPackageLPr(packageName);
20751            if (ps != null
20752                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20753                return;
20754            }
20755            int user = UserHandle.getCallingUserId();
20756            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20757                scheduleWritePackageRestrictionsLocked(user);
20758            }
20759        }
20760    }
20761
20762    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20763    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
20764        ArrayList<PreferredActivity> removed = null;
20765        boolean changed = false;
20766        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20767            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
20768            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20769            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
20770                continue;
20771            }
20772            Iterator<PreferredActivity> it = pir.filterIterator();
20773            while (it.hasNext()) {
20774                PreferredActivity pa = it.next();
20775                // Mark entry for removal only if it matches the package name
20776                // and the entry is of type "always".
20777                if (packageName == null ||
20778                        (pa.mPref.mComponent.getPackageName().equals(packageName)
20779                                && pa.mPref.mAlways)) {
20780                    if (removed == null) {
20781                        removed = new ArrayList<PreferredActivity>();
20782                    }
20783                    removed.add(pa);
20784                }
20785            }
20786            if (removed != null) {
20787                for (int j=0; j<removed.size(); j++) {
20788                    PreferredActivity pa = removed.get(j);
20789                    pir.removeFilter(pa);
20790                }
20791                changed = true;
20792            }
20793        }
20794        if (changed) {
20795            postPreferredActivityChangedBroadcast(userId);
20796        }
20797        return changed;
20798    }
20799
20800    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20801    private void clearIntentFilterVerificationsLPw(int userId) {
20802        final int packageCount = mPackages.size();
20803        for (int i = 0; i < packageCount; i++) {
20804            PackageParser.Package pkg = mPackages.valueAt(i);
20805            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
20806        }
20807    }
20808
20809    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20810    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
20811        if (userId == UserHandle.USER_ALL) {
20812            if (mSettings.removeIntentFilterVerificationLPw(packageName,
20813                    sUserManager.getUserIds())) {
20814                for (int oneUserId : sUserManager.getUserIds()) {
20815                    scheduleWritePackageRestrictionsLocked(oneUserId);
20816                }
20817            }
20818        } else {
20819            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
20820                scheduleWritePackageRestrictionsLocked(userId);
20821            }
20822        }
20823    }
20824
20825    /** Clears state for all users, and touches intent filter verification policy */
20826    void clearDefaultBrowserIfNeeded(String packageName) {
20827        for (int oneUserId : sUserManager.getUserIds()) {
20828            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
20829        }
20830    }
20831
20832    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
20833        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
20834        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
20835            if (packageName.equals(defaultBrowserPackageName)) {
20836                setDefaultBrowserPackageName(null, userId);
20837            }
20838        }
20839    }
20840
20841    @Override
20842    public void resetApplicationPreferences(int userId) {
20843        mContext.enforceCallingOrSelfPermission(
20844                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20845        final long identity = Binder.clearCallingIdentity();
20846        // writer
20847        try {
20848            synchronized (mPackages) {
20849                clearPackagePreferredActivitiesLPw(null, userId);
20850                mSettings.applyDefaultPreferredAppsLPw(this, userId);
20851                // TODO: We have to reset the default SMS and Phone. This requires
20852                // significant refactoring to keep all default apps in the package
20853                // manager (cleaner but more work) or have the services provide
20854                // callbacks to the package manager to request a default app reset.
20855                applyFactoryDefaultBrowserLPw(userId);
20856                clearIntentFilterVerificationsLPw(userId);
20857                primeDomainVerificationsLPw(userId);
20858                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
20859                scheduleWritePackageRestrictionsLocked(userId);
20860            }
20861            resetNetworkPolicies(userId);
20862        } finally {
20863            Binder.restoreCallingIdentity(identity);
20864        }
20865    }
20866
20867    @Override
20868    public int getPreferredActivities(List<IntentFilter> outFilters,
20869            List<ComponentName> outActivities, String packageName) {
20870        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20871            return 0;
20872        }
20873        int num = 0;
20874        final int userId = UserHandle.getCallingUserId();
20875        // reader
20876        synchronized (mPackages) {
20877            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20878            if (pir != null) {
20879                final Iterator<PreferredActivity> it = pir.filterIterator();
20880                while (it.hasNext()) {
20881                    final PreferredActivity pa = it.next();
20882                    if (packageName == null
20883                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
20884                                    && pa.mPref.mAlways)) {
20885                        if (outFilters != null) {
20886                            outFilters.add(new IntentFilter(pa));
20887                        }
20888                        if (outActivities != null) {
20889                            outActivities.add(pa.mPref.mComponent);
20890                        }
20891                    }
20892                }
20893            }
20894        }
20895
20896        return num;
20897    }
20898
20899    @Override
20900    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
20901            int userId) {
20902        int callingUid = Binder.getCallingUid();
20903        if (callingUid != Process.SYSTEM_UID) {
20904            throw new SecurityException(
20905                    "addPersistentPreferredActivity can only be run by the system");
20906        }
20907        if (filter.countActions() == 0) {
20908            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20909            return;
20910        }
20911        synchronized (mPackages) {
20912            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
20913                    ":");
20914            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20915            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
20916                    new PersistentPreferredActivity(filter, activity));
20917            scheduleWritePackageRestrictionsLocked(userId);
20918            postPreferredActivityChangedBroadcast(userId);
20919        }
20920    }
20921
20922    @Override
20923    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
20924        int callingUid = Binder.getCallingUid();
20925        if (callingUid != Process.SYSTEM_UID) {
20926            throw new SecurityException(
20927                    "clearPackagePersistentPreferredActivities can only be run by the system");
20928        }
20929        ArrayList<PersistentPreferredActivity> removed = null;
20930        boolean changed = false;
20931        synchronized (mPackages) {
20932            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
20933                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
20934                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
20935                        .valueAt(i);
20936                if (userId != thisUserId) {
20937                    continue;
20938                }
20939                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
20940                while (it.hasNext()) {
20941                    PersistentPreferredActivity ppa = it.next();
20942                    // Mark entry for removal only if it matches the package name.
20943                    if (ppa.mComponent.getPackageName().equals(packageName)) {
20944                        if (removed == null) {
20945                            removed = new ArrayList<PersistentPreferredActivity>();
20946                        }
20947                        removed.add(ppa);
20948                    }
20949                }
20950                if (removed != null) {
20951                    for (int j=0; j<removed.size(); j++) {
20952                        PersistentPreferredActivity ppa = removed.get(j);
20953                        ppir.removeFilter(ppa);
20954                    }
20955                    changed = true;
20956                }
20957            }
20958
20959            if (changed) {
20960                scheduleWritePackageRestrictionsLocked(userId);
20961                postPreferredActivityChangedBroadcast(userId);
20962            }
20963        }
20964    }
20965
20966    /**
20967     * Common machinery for picking apart a restored XML blob and passing
20968     * it to a caller-supplied functor to be applied to the running system.
20969     */
20970    private void restoreFromXml(XmlPullParser parser, int userId,
20971            String expectedStartTag, BlobXmlRestorer functor)
20972            throws IOException, XmlPullParserException {
20973        int type;
20974        while ((type = parser.next()) != XmlPullParser.START_TAG
20975                && type != XmlPullParser.END_DOCUMENT) {
20976        }
20977        if (type != XmlPullParser.START_TAG) {
20978            // oops didn't find a start tag?!
20979            if (DEBUG_BACKUP) {
20980                Slog.e(TAG, "Didn't find start tag during restore");
20981            }
20982            return;
20983        }
20984Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
20985        // this is supposed to be TAG_PREFERRED_BACKUP
20986        if (!expectedStartTag.equals(parser.getName())) {
20987            if (DEBUG_BACKUP) {
20988                Slog.e(TAG, "Found unexpected tag " + parser.getName());
20989            }
20990            return;
20991        }
20992
20993        // skip interfering stuff, then we're aligned with the backing implementation
20994        while ((type = parser.next()) == XmlPullParser.TEXT) { }
20995Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
20996        functor.apply(parser, userId);
20997    }
20998
20999    private interface BlobXmlRestorer {
21000        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
21001    }
21002
21003    /**
21004     * Non-Binder method, support for the backup/restore mechanism: write the
21005     * full set of preferred activities in its canonical XML format.  Returns the
21006     * XML output as a byte array, or null if there is none.
21007     */
21008    @Override
21009    public byte[] getPreferredActivityBackup(int userId) {
21010        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21011            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
21012        }
21013
21014        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21015        try {
21016            final XmlSerializer serializer = new FastXmlSerializer();
21017            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21018            serializer.startDocument(null, true);
21019            serializer.startTag(null, TAG_PREFERRED_BACKUP);
21020
21021            synchronized (mPackages) {
21022                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
21023            }
21024
21025            serializer.endTag(null, TAG_PREFERRED_BACKUP);
21026            serializer.endDocument();
21027            serializer.flush();
21028        } catch (Exception e) {
21029            if (DEBUG_BACKUP) {
21030                Slog.e(TAG, "Unable to write preferred activities for backup", e);
21031            }
21032            return null;
21033        }
21034
21035        return dataStream.toByteArray();
21036    }
21037
21038    @Override
21039    public void restorePreferredActivities(byte[] backup, int userId) {
21040        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21041            throw new SecurityException("Only the system may call restorePreferredActivities()");
21042        }
21043
21044        try {
21045            final XmlPullParser parser = Xml.newPullParser();
21046            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21047            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
21048                    new BlobXmlRestorer() {
21049                        @Override
21050                        public void apply(XmlPullParser parser, int userId)
21051                                throws XmlPullParserException, IOException {
21052                            synchronized (mPackages) {
21053                                mSettings.readPreferredActivitiesLPw(parser, userId);
21054                            }
21055                        }
21056                    } );
21057        } catch (Exception e) {
21058            if (DEBUG_BACKUP) {
21059                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21060            }
21061        }
21062    }
21063
21064    /**
21065     * Non-Binder method, support for the backup/restore mechanism: write the
21066     * default browser (etc) settings in its canonical XML format.  Returns the default
21067     * browser XML representation as a byte array, or null if there is none.
21068     */
21069    @Override
21070    public byte[] getDefaultAppsBackup(int userId) {
21071        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21072            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
21073        }
21074
21075        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21076        try {
21077            final XmlSerializer serializer = new FastXmlSerializer();
21078            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21079            serializer.startDocument(null, true);
21080            serializer.startTag(null, TAG_DEFAULT_APPS);
21081
21082            synchronized (mPackages) {
21083                mSettings.writeDefaultAppsLPr(serializer, userId);
21084            }
21085
21086            serializer.endTag(null, TAG_DEFAULT_APPS);
21087            serializer.endDocument();
21088            serializer.flush();
21089        } catch (Exception e) {
21090            if (DEBUG_BACKUP) {
21091                Slog.e(TAG, "Unable to write default apps for backup", e);
21092            }
21093            return null;
21094        }
21095
21096        return dataStream.toByteArray();
21097    }
21098
21099    @Override
21100    public void restoreDefaultApps(byte[] backup, int userId) {
21101        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21102            throw new SecurityException("Only the system may call restoreDefaultApps()");
21103        }
21104
21105        try {
21106            final XmlPullParser parser = Xml.newPullParser();
21107            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21108            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
21109                    new BlobXmlRestorer() {
21110                        @Override
21111                        public void apply(XmlPullParser parser, int userId)
21112                                throws XmlPullParserException, IOException {
21113                            synchronized (mPackages) {
21114                                mSettings.readDefaultAppsLPw(parser, userId);
21115                            }
21116                        }
21117                    } );
21118        } catch (Exception e) {
21119            if (DEBUG_BACKUP) {
21120                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
21121            }
21122        }
21123    }
21124
21125    @Override
21126    public byte[] getIntentFilterVerificationBackup(int userId) {
21127        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21128            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
21129        }
21130
21131        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21132        try {
21133            final XmlSerializer serializer = new FastXmlSerializer();
21134            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21135            serializer.startDocument(null, true);
21136            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
21137
21138            synchronized (mPackages) {
21139                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
21140            }
21141
21142            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
21143            serializer.endDocument();
21144            serializer.flush();
21145        } catch (Exception e) {
21146            if (DEBUG_BACKUP) {
21147                Slog.e(TAG, "Unable to write default apps for backup", e);
21148            }
21149            return null;
21150        }
21151
21152        return dataStream.toByteArray();
21153    }
21154
21155    @Override
21156    public void restoreIntentFilterVerification(byte[] backup, int userId) {
21157        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21158            throw new SecurityException("Only the system may call restorePreferredActivities()");
21159        }
21160
21161        try {
21162            final XmlPullParser parser = Xml.newPullParser();
21163            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21164            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
21165                    new BlobXmlRestorer() {
21166                        @Override
21167                        public void apply(XmlPullParser parser, int userId)
21168                                throws XmlPullParserException, IOException {
21169                            synchronized (mPackages) {
21170                                mSettings.readAllDomainVerificationsLPr(parser, userId);
21171                                mSettings.writeLPr();
21172                            }
21173                        }
21174                    } );
21175        } catch (Exception e) {
21176            if (DEBUG_BACKUP) {
21177                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21178            }
21179        }
21180    }
21181
21182    @Override
21183    public byte[] getPermissionGrantBackup(int userId) {
21184        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21185            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
21186        }
21187
21188        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21189        try {
21190            final XmlSerializer serializer = new FastXmlSerializer();
21191            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21192            serializer.startDocument(null, true);
21193            serializer.startTag(null, TAG_PERMISSION_BACKUP);
21194
21195            synchronized (mPackages) {
21196                serializeRuntimePermissionGrantsLPr(serializer, userId);
21197            }
21198
21199            serializer.endTag(null, TAG_PERMISSION_BACKUP);
21200            serializer.endDocument();
21201            serializer.flush();
21202        } catch (Exception e) {
21203            if (DEBUG_BACKUP) {
21204                Slog.e(TAG, "Unable to write default apps for backup", e);
21205            }
21206            return null;
21207        }
21208
21209        return dataStream.toByteArray();
21210    }
21211
21212    @Override
21213    public void restorePermissionGrants(byte[] backup, int userId) {
21214        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21215            throw new SecurityException("Only the system may call restorePermissionGrants()");
21216        }
21217
21218        try {
21219            final XmlPullParser parser = Xml.newPullParser();
21220            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21221            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
21222                    new BlobXmlRestorer() {
21223                        @Override
21224                        public void apply(XmlPullParser parser, int userId)
21225                                throws XmlPullParserException, IOException {
21226                            synchronized (mPackages) {
21227                                processRestoredPermissionGrantsLPr(parser, userId);
21228                            }
21229                        }
21230                    } );
21231        } catch (Exception e) {
21232            if (DEBUG_BACKUP) {
21233                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21234            }
21235        }
21236    }
21237
21238    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
21239            throws IOException {
21240        serializer.startTag(null, TAG_ALL_GRANTS);
21241
21242        final int N = mSettings.mPackages.size();
21243        for (int i = 0; i < N; i++) {
21244            final PackageSetting ps = mSettings.mPackages.valueAt(i);
21245            boolean pkgGrantsKnown = false;
21246
21247            PermissionsState packagePerms = ps.getPermissionsState();
21248
21249            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
21250                final int grantFlags = state.getFlags();
21251                // only look at grants that are not system/policy fixed
21252                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
21253                    final boolean isGranted = state.isGranted();
21254                    // And only back up the user-twiddled state bits
21255                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
21256                        final String packageName = mSettings.mPackages.keyAt(i);
21257                        if (!pkgGrantsKnown) {
21258                            serializer.startTag(null, TAG_GRANT);
21259                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
21260                            pkgGrantsKnown = true;
21261                        }
21262
21263                        final boolean userSet =
21264                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
21265                        final boolean userFixed =
21266                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
21267                        final boolean revoke =
21268                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
21269
21270                        serializer.startTag(null, TAG_PERMISSION);
21271                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
21272                        if (isGranted) {
21273                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
21274                        }
21275                        if (userSet) {
21276                            serializer.attribute(null, ATTR_USER_SET, "true");
21277                        }
21278                        if (userFixed) {
21279                            serializer.attribute(null, ATTR_USER_FIXED, "true");
21280                        }
21281                        if (revoke) {
21282                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
21283                        }
21284                        serializer.endTag(null, TAG_PERMISSION);
21285                    }
21286                }
21287            }
21288
21289            if (pkgGrantsKnown) {
21290                serializer.endTag(null, TAG_GRANT);
21291            }
21292        }
21293
21294        serializer.endTag(null, TAG_ALL_GRANTS);
21295    }
21296
21297    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
21298            throws XmlPullParserException, IOException {
21299        String pkgName = null;
21300        int outerDepth = parser.getDepth();
21301        int type;
21302        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
21303                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
21304            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
21305                continue;
21306            }
21307
21308            final String tagName = parser.getName();
21309            if (tagName.equals(TAG_GRANT)) {
21310                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
21311                if (DEBUG_BACKUP) {
21312                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
21313                }
21314            } else if (tagName.equals(TAG_PERMISSION)) {
21315
21316                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
21317                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
21318
21319                int newFlagSet = 0;
21320                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
21321                    newFlagSet |= FLAG_PERMISSION_USER_SET;
21322                }
21323                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
21324                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
21325                }
21326                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
21327                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
21328                }
21329                if (DEBUG_BACKUP) {
21330                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
21331                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
21332                }
21333                final PackageSetting ps = mSettings.mPackages.get(pkgName);
21334                if (ps != null) {
21335                    // Already installed so we apply the grant immediately
21336                    if (DEBUG_BACKUP) {
21337                        Slog.v(TAG, "        + already installed; applying");
21338                    }
21339                    PermissionsState perms = ps.getPermissionsState();
21340                    BasePermission bp = mSettings.mPermissions.get(permName);
21341                    if (bp != null) {
21342                        if (isGranted) {
21343                            perms.grantRuntimePermission(bp, userId);
21344                        }
21345                        if (newFlagSet != 0) {
21346                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
21347                        }
21348                    }
21349                } else {
21350                    // Need to wait for post-restore install to apply the grant
21351                    if (DEBUG_BACKUP) {
21352                        Slog.v(TAG, "        - not yet installed; saving for later");
21353                    }
21354                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
21355                            isGranted, newFlagSet, userId);
21356                }
21357            } else {
21358                PackageManagerService.reportSettingsProblem(Log.WARN,
21359                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
21360                XmlUtils.skipCurrentTag(parser);
21361            }
21362        }
21363
21364        scheduleWriteSettingsLocked();
21365        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
21366    }
21367
21368    @Override
21369    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
21370            int sourceUserId, int targetUserId, int flags) {
21371        mContext.enforceCallingOrSelfPermission(
21372                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21373        int callingUid = Binder.getCallingUid();
21374        enforceOwnerRights(ownerPackage, callingUid);
21375        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21376        if (intentFilter.countActions() == 0) {
21377            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
21378            return;
21379        }
21380        synchronized (mPackages) {
21381            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
21382                    ownerPackage, targetUserId, flags);
21383            CrossProfileIntentResolver resolver =
21384                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21385            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
21386            // We have all those whose filter is equal. Now checking if the rest is equal as well.
21387            if (existing != null) {
21388                int size = existing.size();
21389                for (int i = 0; i < size; i++) {
21390                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
21391                        return;
21392                    }
21393                }
21394            }
21395            resolver.addFilter(newFilter);
21396            scheduleWritePackageRestrictionsLocked(sourceUserId);
21397        }
21398    }
21399
21400    @Override
21401    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
21402        mContext.enforceCallingOrSelfPermission(
21403                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21404        final int callingUid = Binder.getCallingUid();
21405        enforceOwnerRights(ownerPackage, callingUid);
21406        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21407        synchronized (mPackages) {
21408            CrossProfileIntentResolver resolver =
21409                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21410            ArraySet<CrossProfileIntentFilter> set =
21411                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
21412            for (CrossProfileIntentFilter filter : set) {
21413                if (filter.getOwnerPackage().equals(ownerPackage)) {
21414                    resolver.removeFilter(filter);
21415                }
21416            }
21417            scheduleWritePackageRestrictionsLocked(sourceUserId);
21418        }
21419    }
21420
21421    // Enforcing that callingUid is owning pkg on userId
21422    private void enforceOwnerRights(String pkg, int callingUid) {
21423        // The system owns everything.
21424        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
21425            return;
21426        }
21427        final int callingUserId = UserHandle.getUserId(callingUid);
21428        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
21429        if (pi == null) {
21430            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
21431                    + callingUserId);
21432        }
21433        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
21434            throw new SecurityException("Calling uid " + callingUid
21435                    + " does not own package " + pkg);
21436        }
21437    }
21438
21439    @Override
21440    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
21441        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21442            return null;
21443        }
21444        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
21445    }
21446
21447    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
21448        UserManagerService ums = UserManagerService.getInstance();
21449        if (ums != null) {
21450            final UserInfo parent = ums.getProfileParent(userId);
21451            final int launcherUid = (parent != null) ? parent.id : userId;
21452            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
21453            if (launcherComponent != null) {
21454                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
21455                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
21456                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
21457                        .setPackage(launcherComponent.getPackageName());
21458                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
21459            }
21460        }
21461    }
21462
21463    /**
21464     * Report the 'Home' activity which is currently set as "always use this one". If non is set
21465     * then reports the most likely home activity or null if there are more than one.
21466     */
21467    private ComponentName getDefaultHomeActivity(int userId) {
21468        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
21469        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
21470        if (cn != null) {
21471            return cn;
21472        }
21473
21474        // Find the launcher with the highest priority and return that component if there are no
21475        // other home activity with the same priority.
21476        int lastPriority = Integer.MIN_VALUE;
21477        ComponentName lastComponent = null;
21478        final int size = allHomeCandidates.size();
21479        for (int i = 0; i < size; i++) {
21480            final ResolveInfo ri = allHomeCandidates.get(i);
21481            if (ri.priority > lastPriority) {
21482                lastComponent = ri.activityInfo.getComponentName();
21483                lastPriority = ri.priority;
21484            } else if (ri.priority == lastPriority) {
21485                // Two components found with same priority.
21486                lastComponent = null;
21487            }
21488        }
21489        return lastComponent;
21490    }
21491
21492    private Intent getHomeIntent() {
21493        Intent intent = new Intent(Intent.ACTION_MAIN);
21494        intent.addCategory(Intent.CATEGORY_HOME);
21495        intent.addCategory(Intent.CATEGORY_DEFAULT);
21496        return intent;
21497    }
21498
21499    private IntentFilter getHomeFilter() {
21500        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
21501        filter.addCategory(Intent.CATEGORY_HOME);
21502        filter.addCategory(Intent.CATEGORY_DEFAULT);
21503        return filter;
21504    }
21505
21506    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21507            int userId) {
21508        Intent intent  = getHomeIntent();
21509        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
21510                PackageManager.GET_META_DATA, userId);
21511        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
21512                true, false, false, userId);
21513
21514        allHomeCandidates.clear();
21515        if (list != null) {
21516            for (ResolveInfo ri : list) {
21517                allHomeCandidates.add(ri);
21518            }
21519        }
21520        return (preferred == null || preferred.activityInfo == null)
21521                ? null
21522                : new ComponentName(preferred.activityInfo.packageName,
21523                        preferred.activityInfo.name);
21524    }
21525
21526    @Override
21527    public void setHomeActivity(ComponentName comp, int userId) {
21528        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21529            return;
21530        }
21531        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21532        getHomeActivitiesAsUser(homeActivities, userId);
21533
21534        boolean found = false;
21535
21536        final int size = homeActivities.size();
21537        final ComponentName[] set = new ComponentName[size];
21538        for (int i = 0; i < size; i++) {
21539            final ResolveInfo candidate = homeActivities.get(i);
21540            final ActivityInfo info = candidate.activityInfo;
21541            final ComponentName activityName = new ComponentName(info.packageName, info.name);
21542            set[i] = activityName;
21543            if (!found && activityName.equals(comp)) {
21544                found = true;
21545            }
21546        }
21547        if (!found) {
21548            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21549                    + userId);
21550        }
21551        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21552                set, comp, userId);
21553    }
21554
21555    private @Nullable String getSetupWizardPackageName() {
21556        final Intent intent = new Intent(Intent.ACTION_MAIN);
21557        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21558
21559        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21560                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21561                        | MATCH_DISABLED_COMPONENTS,
21562                UserHandle.myUserId());
21563        if (matches.size() == 1) {
21564            return matches.get(0).getComponentInfo().packageName;
21565        } else {
21566            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21567                    + ": matches=" + matches);
21568            return null;
21569        }
21570    }
21571
21572    private @Nullable String getStorageManagerPackageName() {
21573        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21574
21575        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21576                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21577                        | MATCH_DISABLED_COMPONENTS,
21578                UserHandle.myUserId());
21579        if (matches.size() == 1) {
21580            return matches.get(0).getComponentInfo().packageName;
21581        } else {
21582            Slog.e(TAG, "There should probably be exactly one storage manager; found "
21583                    + matches.size() + ": matches=" + matches);
21584            return null;
21585        }
21586    }
21587
21588    @Override
21589    public void setApplicationEnabledSetting(String appPackageName,
21590            int newState, int flags, int userId, String callingPackage) {
21591        if (!sUserManager.exists(userId)) return;
21592        if (callingPackage == null) {
21593            callingPackage = Integer.toString(Binder.getCallingUid());
21594        }
21595        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21596    }
21597
21598    @Override
21599    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21600        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21601        synchronized (mPackages) {
21602            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21603            if (pkgSetting != null) {
21604                pkgSetting.setUpdateAvailable(updateAvailable);
21605            }
21606        }
21607    }
21608
21609    @Override
21610    public void setComponentEnabledSetting(ComponentName componentName,
21611            int newState, int flags, int userId) {
21612        if (!sUserManager.exists(userId)) return;
21613        setEnabledSetting(componentName.getPackageName(),
21614                componentName.getClassName(), newState, flags, userId, null);
21615    }
21616
21617    private void setEnabledSetting(final String packageName, String className, int newState,
21618            final int flags, int userId, String callingPackage) {
21619        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21620              || newState == COMPONENT_ENABLED_STATE_ENABLED
21621              || newState == COMPONENT_ENABLED_STATE_DISABLED
21622              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21623              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21624            throw new IllegalArgumentException("Invalid new component state: "
21625                    + newState);
21626        }
21627        PackageSetting pkgSetting;
21628        final int callingUid = Binder.getCallingUid();
21629        final int permission;
21630        if (callingUid == Process.SYSTEM_UID) {
21631            permission = PackageManager.PERMISSION_GRANTED;
21632        } else {
21633            permission = mContext.checkCallingOrSelfPermission(
21634                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21635        }
21636        enforceCrossUserPermission(callingUid, userId,
21637                false /* requireFullPermission */, true /* checkShell */, "set enabled");
21638        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21639        boolean sendNow = false;
21640        boolean isApp = (className == null);
21641        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21642        String componentName = isApp ? packageName : className;
21643        int packageUid = -1;
21644        ArrayList<String> components;
21645
21646        // reader
21647        synchronized (mPackages) {
21648            pkgSetting = mSettings.mPackages.get(packageName);
21649            if (pkgSetting == null) {
21650                if (!isCallerInstantApp) {
21651                    if (className == null) {
21652                        throw new IllegalArgumentException("Unknown package: " + packageName);
21653                    }
21654                    throw new IllegalArgumentException(
21655                            "Unknown component: " + packageName + "/" + className);
21656                } else {
21657                    // throw SecurityException to prevent leaking package information
21658                    throw new SecurityException(
21659                            "Attempt to change component state; "
21660                            + "pid=" + Binder.getCallingPid()
21661                            + ", uid=" + callingUid
21662                            + (className == null
21663                                    ? ", package=" + packageName
21664                                    : ", component=" + packageName + "/" + className));
21665                }
21666            }
21667        }
21668
21669        // Limit who can change which apps
21670        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21671            // Don't allow apps that don't have permission to modify other apps
21672            if (!allowedByPermission
21673                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21674                throw new SecurityException(
21675                        "Attempt to change component state; "
21676                        + "pid=" + Binder.getCallingPid()
21677                        + ", uid=" + callingUid
21678                        + (className == null
21679                                ? ", package=" + packageName
21680                                : ", component=" + packageName + "/" + className));
21681            }
21682            // Don't allow changing protected packages.
21683            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21684                throw new SecurityException("Cannot disable a protected package: " + packageName);
21685            }
21686        }
21687
21688        synchronized (mPackages) {
21689            if (callingUid == Process.SHELL_UID
21690                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21691                // Shell can only change whole packages between ENABLED and DISABLED_USER states
21692                // unless it is a test package.
21693                int oldState = pkgSetting.getEnabled(userId);
21694                if (className == null
21695                    &&
21696                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21697                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21698                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21699                    &&
21700                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21701                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
21702                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21703                    // ok
21704                } else {
21705                    throw new SecurityException(
21706                            "Shell cannot change component state for " + packageName + "/"
21707                            + className + " to " + newState);
21708                }
21709            }
21710            if (className == null) {
21711                // We're dealing with an application/package level state change
21712                if (pkgSetting.getEnabled(userId) == newState) {
21713                    // Nothing to do
21714                    return;
21715                }
21716                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21717                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
21718                    // Don't care about who enables an app.
21719                    callingPackage = null;
21720                }
21721                pkgSetting.setEnabled(newState, userId, callingPackage);
21722                // pkgSetting.pkg.mSetEnabled = newState;
21723            } else {
21724                // We're dealing with a component level state change
21725                // First, verify that this is a valid class name.
21726                PackageParser.Package pkg = pkgSetting.pkg;
21727                if (pkg == null || !pkg.hasComponentClassName(className)) {
21728                    if (pkg != null &&
21729                            pkg.applicationInfo.targetSdkVersion >=
21730                                    Build.VERSION_CODES.JELLY_BEAN) {
21731                        throw new IllegalArgumentException("Component class " + className
21732                                + " does not exist in " + packageName);
21733                    } else {
21734                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
21735                                + className + " does not exist in " + packageName);
21736                    }
21737                }
21738                switch (newState) {
21739                case COMPONENT_ENABLED_STATE_ENABLED:
21740                    if (!pkgSetting.enableComponentLPw(className, userId)) {
21741                        return;
21742                    }
21743                    break;
21744                case COMPONENT_ENABLED_STATE_DISABLED:
21745                    if (!pkgSetting.disableComponentLPw(className, userId)) {
21746                        return;
21747                    }
21748                    break;
21749                case COMPONENT_ENABLED_STATE_DEFAULT:
21750                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
21751                        return;
21752                    }
21753                    break;
21754                default:
21755                    Slog.e(TAG, "Invalid new component state: " + newState);
21756                    return;
21757                }
21758            }
21759            scheduleWritePackageRestrictionsLocked(userId);
21760            updateSequenceNumberLP(pkgSetting, new int[] { userId });
21761            final long callingId = Binder.clearCallingIdentity();
21762            try {
21763                updateInstantAppInstallerLocked(packageName);
21764            } finally {
21765                Binder.restoreCallingIdentity(callingId);
21766            }
21767            components = mPendingBroadcasts.get(userId, packageName);
21768            final boolean newPackage = components == null;
21769            if (newPackage) {
21770                components = new ArrayList<String>();
21771            }
21772            if (!components.contains(componentName)) {
21773                components.add(componentName);
21774            }
21775            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
21776                sendNow = true;
21777                // Purge entry from pending broadcast list if another one exists already
21778                // since we are sending one right away.
21779                mPendingBroadcasts.remove(userId, packageName);
21780            } else {
21781                if (newPackage) {
21782                    mPendingBroadcasts.put(userId, packageName, components);
21783                }
21784                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
21785                    // Schedule a message
21786                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
21787                }
21788            }
21789        }
21790
21791        long callingId = Binder.clearCallingIdentity();
21792        try {
21793            if (sendNow) {
21794                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
21795                sendPackageChangedBroadcast(packageName,
21796                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
21797            }
21798        } finally {
21799            Binder.restoreCallingIdentity(callingId);
21800        }
21801    }
21802
21803    @Override
21804    public void flushPackageRestrictionsAsUser(int userId) {
21805        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21806            return;
21807        }
21808        if (!sUserManager.exists(userId)) {
21809            return;
21810        }
21811        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
21812                false /* checkShell */, "flushPackageRestrictions");
21813        synchronized (mPackages) {
21814            mSettings.writePackageRestrictionsLPr(userId);
21815            mDirtyUsers.remove(userId);
21816            if (mDirtyUsers.isEmpty()) {
21817                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
21818            }
21819        }
21820    }
21821
21822    private void sendPackageChangedBroadcast(String packageName,
21823            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
21824        if (DEBUG_INSTALL)
21825            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
21826                    + componentNames);
21827        Bundle extras = new Bundle(4);
21828        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
21829        String nameList[] = new String[componentNames.size()];
21830        componentNames.toArray(nameList);
21831        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
21832        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
21833        extras.putInt(Intent.EXTRA_UID, packageUid);
21834        // If this is not reporting a change of the overall package, then only send it
21835        // to registered receivers.  We don't want to launch a swath of apps for every
21836        // little component state change.
21837        final int flags = !componentNames.contains(packageName)
21838                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
21839        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
21840                new int[] {UserHandle.getUserId(packageUid)});
21841    }
21842
21843    @Override
21844    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
21845        if (!sUserManager.exists(userId)) return;
21846        final int callingUid = Binder.getCallingUid();
21847        if (getInstantAppPackageName(callingUid) != null) {
21848            return;
21849        }
21850        final int permission = mContext.checkCallingOrSelfPermission(
21851                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21852        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21853        enforceCrossUserPermission(callingUid, userId,
21854                true /* requireFullPermission */, true /* checkShell */, "stop package");
21855        // writer
21856        synchronized (mPackages) {
21857            final PackageSetting ps = mSettings.mPackages.get(packageName);
21858            if (!filterAppAccessLPr(ps, callingUid, userId)
21859                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
21860                            allowedByPermission, callingUid, userId)) {
21861                scheduleWritePackageRestrictionsLocked(userId);
21862            }
21863        }
21864    }
21865
21866    @Override
21867    public String getInstallerPackageName(String packageName) {
21868        final int callingUid = Binder.getCallingUid();
21869        if (getInstantAppPackageName(callingUid) != null) {
21870            return null;
21871        }
21872        // reader
21873        synchronized (mPackages) {
21874            final PackageSetting ps = mSettings.mPackages.get(packageName);
21875            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
21876                return null;
21877            }
21878            return mSettings.getInstallerPackageNameLPr(packageName);
21879        }
21880    }
21881
21882    public boolean isOrphaned(String packageName) {
21883        // reader
21884        synchronized (mPackages) {
21885            return mSettings.isOrphaned(packageName);
21886        }
21887    }
21888
21889    @Override
21890    public int getApplicationEnabledSetting(String packageName, int userId) {
21891        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21892        int callingUid = Binder.getCallingUid();
21893        enforceCrossUserPermission(callingUid, userId,
21894                false /* requireFullPermission */, false /* checkShell */, "get enabled");
21895        // reader
21896        synchronized (mPackages) {
21897            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
21898                return COMPONENT_ENABLED_STATE_DISABLED;
21899            }
21900            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
21901        }
21902    }
21903
21904    @Override
21905    public int getComponentEnabledSetting(ComponentName component, int userId) {
21906        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21907        int callingUid = Binder.getCallingUid();
21908        enforceCrossUserPermission(callingUid, userId,
21909                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
21910        synchronized (mPackages) {
21911            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
21912                    component, TYPE_UNKNOWN, userId)) {
21913                return COMPONENT_ENABLED_STATE_DISABLED;
21914            }
21915            return mSettings.getComponentEnabledSettingLPr(component, userId);
21916        }
21917    }
21918
21919    @Override
21920    public void enterSafeMode() {
21921        enforceSystemOrRoot("Only the system can request entering safe mode");
21922
21923        if (!mSystemReady) {
21924            mSafeMode = true;
21925        }
21926    }
21927
21928    @Override
21929    public void systemReady() {
21930        enforceSystemOrRoot("Only the system can claim the system is ready");
21931
21932        mSystemReady = true;
21933        final ContentResolver resolver = mContext.getContentResolver();
21934        ContentObserver co = new ContentObserver(mHandler) {
21935            @Override
21936            public void onChange(boolean selfChange) {
21937                mEphemeralAppsDisabled =
21938                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
21939                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
21940            }
21941        };
21942        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21943                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
21944                false, co, UserHandle.USER_SYSTEM);
21945        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21946                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
21947        co.onChange(true);
21948
21949        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
21950        // disabled after already being started.
21951        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
21952                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
21953
21954        // Read the compatibilty setting when the system is ready.
21955        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
21956                mContext.getContentResolver(),
21957                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
21958        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
21959        if (DEBUG_SETTINGS) {
21960            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
21961        }
21962
21963        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
21964
21965        synchronized (mPackages) {
21966            // Verify that all of the preferred activity components actually
21967            // exist.  It is possible for applications to be updated and at
21968            // that point remove a previously declared activity component that
21969            // had been set as a preferred activity.  We try to clean this up
21970            // the next time we encounter that preferred activity, but it is
21971            // possible for the user flow to never be able to return to that
21972            // situation so here we do a sanity check to make sure we haven't
21973            // left any junk around.
21974            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21975            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21976                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21977                removed.clear();
21978                for (PreferredActivity pa : pir.filterSet()) {
21979                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21980                        removed.add(pa);
21981                    }
21982                }
21983                if (removed.size() > 0) {
21984                    for (int r=0; r<removed.size(); r++) {
21985                        PreferredActivity pa = removed.get(r);
21986                        Slog.w(TAG, "Removing dangling preferred activity: "
21987                                + pa.mPref.mComponent);
21988                        pir.removeFilter(pa);
21989                    }
21990                    mSettings.writePackageRestrictionsLPr(
21991                            mSettings.mPreferredActivities.keyAt(i));
21992                }
21993            }
21994
21995            for (int userId : UserManagerService.getInstance().getUserIds()) {
21996                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21997                    grantPermissionsUserIds = ArrayUtils.appendInt(
21998                            grantPermissionsUserIds, userId);
21999                }
22000            }
22001        }
22002        sUserManager.systemReady();
22003
22004        // If we upgraded grant all default permissions before kicking off.
22005        for (int userId : grantPermissionsUserIds) {
22006            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22007        }
22008
22009        // If we did not grant default permissions, we preload from this the
22010        // default permission exceptions lazily to ensure we don't hit the
22011        // disk on a new user creation.
22012        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
22013            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
22014        }
22015
22016        // Kick off any messages waiting for system ready
22017        if (mPostSystemReadyMessages != null) {
22018            for (Message msg : mPostSystemReadyMessages) {
22019                msg.sendToTarget();
22020            }
22021            mPostSystemReadyMessages = null;
22022        }
22023
22024        // Watch for external volumes that come and go over time
22025        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22026        storage.registerListener(mStorageListener);
22027
22028        mInstallerService.systemReady();
22029        mPackageDexOptimizer.systemReady();
22030
22031        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
22032                StorageManagerInternal.class);
22033        StorageManagerInternal.addExternalStoragePolicy(
22034                new StorageManagerInternal.ExternalStorageMountPolicy() {
22035            @Override
22036            public int getMountMode(int uid, String packageName) {
22037                if (Process.isIsolated(uid)) {
22038                    return Zygote.MOUNT_EXTERNAL_NONE;
22039                }
22040                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
22041                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
22042                }
22043                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
22044                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
22045                }
22046                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
22047                    return Zygote.MOUNT_EXTERNAL_READ;
22048                }
22049                return Zygote.MOUNT_EXTERNAL_WRITE;
22050            }
22051
22052            @Override
22053            public boolean hasExternalStorage(int uid, String packageName) {
22054                return true;
22055            }
22056        });
22057
22058        // Now that we're mostly running, clean up stale users and apps
22059        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
22060        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
22061
22062        if (mPrivappPermissionsViolations != null) {
22063            Slog.wtf(TAG,"Signature|privileged permissions not in "
22064                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
22065            mPrivappPermissionsViolations = null;
22066        }
22067    }
22068
22069    public void waitForAppDataPrepared() {
22070        if (mPrepareAppDataFuture == null) {
22071            return;
22072        }
22073        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
22074        mPrepareAppDataFuture = null;
22075    }
22076
22077    @Override
22078    public boolean isSafeMode() {
22079        // allow instant applications
22080        return mSafeMode;
22081    }
22082
22083    @Override
22084    public boolean hasSystemUidErrors() {
22085        // allow instant applications
22086        return mHasSystemUidErrors;
22087    }
22088
22089    static String arrayToString(int[] array) {
22090        StringBuffer buf = new StringBuffer(128);
22091        buf.append('[');
22092        if (array != null) {
22093            for (int i=0; i<array.length; i++) {
22094                if (i > 0) buf.append(", ");
22095                buf.append(array[i]);
22096            }
22097        }
22098        buf.append(']');
22099        return buf.toString();
22100    }
22101
22102    static class DumpState {
22103        public static final int DUMP_LIBS = 1 << 0;
22104        public static final int DUMP_FEATURES = 1 << 1;
22105        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
22106        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
22107        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
22108        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
22109        public static final int DUMP_PERMISSIONS = 1 << 6;
22110        public static final int DUMP_PACKAGES = 1 << 7;
22111        public static final int DUMP_SHARED_USERS = 1 << 8;
22112        public static final int DUMP_MESSAGES = 1 << 9;
22113        public static final int DUMP_PROVIDERS = 1 << 10;
22114        public static final int DUMP_VERIFIERS = 1 << 11;
22115        public static final int DUMP_PREFERRED = 1 << 12;
22116        public static final int DUMP_PREFERRED_XML = 1 << 13;
22117        public static final int DUMP_KEYSETS = 1 << 14;
22118        public static final int DUMP_VERSION = 1 << 15;
22119        public static final int DUMP_INSTALLS = 1 << 16;
22120        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
22121        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
22122        public static final int DUMP_FROZEN = 1 << 19;
22123        public static final int DUMP_DEXOPT = 1 << 20;
22124        public static final int DUMP_COMPILER_STATS = 1 << 21;
22125        public static final int DUMP_CHANGES = 1 << 22;
22126        public static final int DUMP_VOLUMES = 1 << 23;
22127
22128        public static final int OPTION_SHOW_FILTERS = 1 << 0;
22129
22130        private int mTypes;
22131
22132        private int mOptions;
22133
22134        private boolean mTitlePrinted;
22135
22136        private SharedUserSetting mSharedUser;
22137
22138        public boolean isDumping(int type) {
22139            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
22140                return true;
22141            }
22142
22143            return (mTypes & type) != 0;
22144        }
22145
22146        public void setDump(int type) {
22147            mTypes |= type;
22148        }
22149
22150        public boolean isOptionEnabled(int option) {
22151            return (mOptions & option) != 0;
22152        }
22153
22154        public void setOptionEnabled(int option) {
22155            mOptions |= option;
22156        }
22157
22158        public boolean onTitlePrinted() {
22159            final boolean printed = mTitlePrinted;
22160            mTitlePrinted = true;
22161            return printed;
22162        }
22163
22164        public boolean getTitlePrinted() {
22165            return mTitlePrinted;
22166        }
22167
22168        public void setTitlePrinted(boolean enabled) {
22169            mTitlePrinted = enabled;
22170        }
22171
22172        public SharedUserSetting getSharedUser() {
22173            return mSharedUser;
22174        }
22175
22176        public void setSharedUser(SharedUserSetting user) {
22177            mSharedUser = user;
22178        }
22179    }
22180
22181    @Override
22182    public void onShellCommand(FileDescriptor in, FileDescriptor out,
22183            FileDescriptor err, String[] args, ShellCallback callback,
22184            ResultReceiver resultReceiver) {
22185        (new PackageManagerShellCommand(this)).exec(
22186                this, in, out, err, args, callback, resultReceiver);
22187    }
22188
22189    @Override
22190    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
22191        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
22192
22193        DumpState dumpState = new DumpState();
22194        boolean fullPreferred = false;
22195        boolean checkin = false;
22196
22197        String packageName = null;
22198        ArraySet<String> permissionNames = null;
22199
22200        int opti = 0;
22201        while (opti < args.length) {
22202            String opt = args[opti];
22203            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
22204                break;
22205            }
22206            opti++;
22207
22208            if ("-a".equals(opt)) {
22209                // Right now we only know how to print all.
22210            } else if ("-h".equals(opt)) {
22211                pw.println("Package manager dump options:");
22212                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
22213                pw.println("    --checkin: dump for a checkin");
22214                pw.println("    -f: print details of intent filters");
22215                pw.println("    -h: print this help");
22216                pw.println("  cmd may be one of:");
22217                pw.println("    l[ibraries]: list known shared libraries");
22218                pw.println("    f[eatures]: list device features");
22219                pw.println("    k[eysets]: print known keysets");
22220                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
22221                pw.println("    perm[issions]: dump permissions");
22222                pw.println("    permission [name ...]: dump declaration and use of given permission");
22223                pw.println("    pref[erred]: print preferred package settings");
22224                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
22225                pw.println("    prov[iders]: dump content providers");
22226                pw.println("    p[ackages]: dump installed packages");
22227                pw.println("    s[hared-users]: dump shared user IDs");
22228                pw.println("    m[essages]: print collected runtime messages");
22229                pw.println("    v[erifiers]: print package verifier info");
22230                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
22231                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
22232                pw.println("    version: print database version info");
22233                pw.println("    write: write current settings now");
22234                pw.println("    installs: details about install sessions");
22235                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
22236                pw.println("    dexopt: dump dexopt state");
22237                pw.println("    compiler-stats: dump compiler statistics");
22238                pw.println("    enabled-overlays: dump list of enabled overlay packages");
22239                pw.println("    <package.name>: info about given package");
22240                return;
22241            } else if ("--checkin".equals(opt)) {
22242                checkin = true;
22243            } else if ("-f".equals(opt)) {
22244                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
22245            } else if ("--proto".equals(opt)) {
22246                dumpProto(fd);
22247                return;
22248            } else {
22249                pw.println("Unknown argument: " + opt + "; use -h for help");
22250            }
22251        }
22252
22253        // Is the caller requesting to dump a particular piece of data?
22254        if (opti < args.length) {
22255            String cmd = args[opti];
22256            opti++;
22257            // Is this a package name?
22258            if ("android".equals(cmd) || cmd.contains(".")) {
22259                packageName = cmd;
22260                // When dumping a single package, we always dump all of its
22261                // filter information since the amount of data will be reasonable.
22262                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
22263            } else if ("check-permission".equals(cmd)) {
22264                if (opti >= args.length) {
22265                    pw.println("Error: check-permission missing permission argument");
22266                    return;
22267                }
22268                String perm = args[opti];
22269                opti++;
22270                if (opti >= args.length) {
22271                    pw.println("Error: check-permission missing package argument");
22272                    return;
22273                }
22274
22275                String pkg = args[opti];
22276                opti++;
22277                int user = UserHandle.getUserId(Binder.getCallingUid());
22278                if (opti < args.length) {
22279                    try {
22280                        user = Integer.parseInt(args[opti]);
22281                    } catch (NumberFormatException e) {
22282                        pw.println("Error: check-permission user argument is not a number: "
22283                                + args[opti]);
22284                        return;
22285                    }
22286                }
22287
22288                // Normalize package name to handle renamed packages and static libs
22289                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
22290
22291                pw.println(checkPermission(perm, pkg, user));
22292                return;
22293            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
22294                dumpState.setDump(DumpState.DUMP_LIBS);
22295            } else if ("f".equals(cmd) || "features".equals(cmd)) {
22296                dumpState.setDump(DumpState.DUMP_FEATURES);
22297            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
22298                if (opti >= args.length) {
22299                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
22300                            | DumpState.DUMP_SERVICE_RESOLVERS
22301                            | DumpState.DUMP_RECEIVER_RESOLVERS
22302                            | DumpState.DUMP_CONTENT_RESOLVERS);
22303                } else {
22304                    while (opti < args.length) {
22305                        String name = args[opti];
22306                        if ("a".equals(name) || "activity".equals(name)) {
22307                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
22308                        } else if ("s".equals(name) || "service".equals(name)) {
22309                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
22310                        } else if ("r".equals(name) || "receiver".equals(name)) {
22311                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
22312                        } else if ("c".equals(name) || "content".equals(name)) {
22313                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
22314                        } else {
22315                            pw.println("Error: unknown resolver table type: " + name);
22316                            return;
22317                        }
22318                        opti++;
22319                    }
22320                }
22321            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
22322                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
22323            } else if ("permission".equals(cmd)) {
22324                if (opti >= args.length) {
22325                    pw.println("Error: permission requires permission name");
22326                    return;
22327                }
22328                permissionNames = new ArraySet<>();
22329                while (opti < args.length) {
22330                    permissionNames.add(args[opti]);
22331                    opti++;
22332                }
22333                dumpState.setDump(DumpState.DUMP_PERMISSIONS
22334                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
22335            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
22336                dumpState.setDump(DumpState.DUMP_PREFERRED);
22337            } else if ("preferred-xml".equals(cmd)) {
22338                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
22339                if (opti < args.length && "--full".equals(args[opti])) {
22340                    fullPreferred = true;
22341                    opti++;
22342                }
22343            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
22344                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
22345            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
22346                dumpState.setDump(DumpState.DUMP_PACKAGES);
22347            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
22348                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
22349            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
22350                dumpState.setDump(DumpState.DUMP_PROVIDERS);
22351            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
22352                dumpState.setDump(DumpState.DUMP_MESSAGES);
22353            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
22354                dumpState.setDump(DumpState.DUMP_VERIFIERS);
22355            } else if ("i".equals(cmd) || "ifv".equals(cmd)
22356                    || "intent-filter-verifiers".equals(cmd)) {
22357                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
22358            } else if ("version".equals(cmd)) {
22359                dumpState.setDump(DumpState.DUMP_VERSION);
22360            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
22361                dumpState.setDump(DumpState.DUMP_KEYSETS);
22362            } else if ("installs".equals(cmd)) {
22363                dumpState.setDump(DumpState.DUMP_INSTALLS);
22364            } else if ("frozen".equals(cmd)) {
22365                dumpState.setDump(DumpState.DUMP_FROZEN);
22366            } else if ("volumes".equals(cmd)) {
22367                dumpState.setDump(DumpState.DUMP_VOLUMES);
22368            } else if ("dexopt".equals(cmd)) {
22369                dumpState.setDump(DumpState.DUMP_DEXOPT);
22370            } else if ("compiler-stats".equals(cmd)) {
22371                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
22372            } else if ("changes".equals(cmd)) {
22373                dumpState.setDump(DumpState.DUMP_CHANGES);
22374            } else if ("write".equals(cmd)) {
22375                synchronized (mPackages) {
22376                    mSettings.writeLPr();
22377                    pw.println("Settings written.");
22378                    return;
22379                }
22380            }
22381        }
22382
22383        if (checkin) {
22384            pw.println("vers,1");
22385        }
22386
22387        // reader
22388        synchronized (mPackages) {
22389            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
22390                if (!checkin) {
22391                    if (dumpState.onTitlePrinted())
22392                        pw.println();
22393                    pw.println("Database versions:");
22394                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
22395                }
22396            }
22397
22398            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
22399                if (!checkin) {
22400                    if (dumpState.onTitlePrinted())
22401                        pw.println();
22402                    pw.println("Verifiers:");
22403                    pw.print("  Required: ");
22404                    pw.print(mRequiredVerifierPackage);
22405                    pw.print(" (uid=");
22406                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22407                            UserHandle.USER_SYSTEM));
22408                    pw.println(")");
22409                } else if (mRequiredVerifierPackage != null) {
22410                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
22411                    pw.print(",");
22412                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22413                            UserHandle.USER_SYSTEM));
22414                }
22415            }
22416
22417            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
22418                    packageName == null) {
22419                if (mIntentFilterVerifierComponent != null) {
22420                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22421                    if (!checkin) {
22422                        if (dumpState.onTitlePrinted())
22423                            pw.println();
22424                        pw.println("Intent Filter Verifier:");
22425                        pw.print("  Using: ");
22426                        pw.print(verifierPackageName);
22427                        pw.print(" (uid=");
22428                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22429                                UserHandle.USER_SYSTEM));
22430                        pw.println(")");
22431                    } else if (verifierPackageName != null) {
22432                        pw.print("ifv,"); pw.print(verifierPackageName);
22433                        pw.print(",");
22434                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22435                                UserHandle.USER_SYSTEM));
22436                    }
22437                } else {
22438                    pw.println();
22439                    pw.println("No Intent Filter Verifier available!");
22440                }
22441            }
22442
22443            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
22444                boolean printedHeader = false;
22445                final Iterator<String> it = mSharedLibraries.keySet().iterator();
22446                while (it.hasNext()) {
22447                    String libName = it.next();
22448                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22449                    if (versionedLib == null) {
22450                        continue;
22451                    }
22452                    final int versionCount = versionedLib.size();
22453                    for (int i = 0; i < versionCount; i++) {
22454                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
22455                        if (!checkin) {
22456                            if (!printedHeader) {
22457                                if (dumpState.onTitlePrinted())
22458                                    pw.println();
22459                                pw.println("Libraries:");
22460                                printedHeader = true;
22461                            }
22462                            pw.print("  ");
22463                        } else {
22464                            pw.print("lib,");
22465                        }
22466                        pw.print(libEntry.info.getName());
22467                        if (libEntry.info.isStatic()) {
22468                            pw.print(" version=" + libEntry.info.getVersion());
22469                        }
22470                        if (!checkin) {
22471                            pw.print(" -> ");
22472                        }
22473                        if (libEntry.path != null) {
22474                            pw.print(" (jar) ");
22475                            pw.print(libEntry.path);
22476                        } else {
22477                            pw.print(" (apk) ");
22478                            pw.print(libEntry.apk);
22479                        }
22480                        pw.println();
22481                    }
22482                }
22483            }
22484
22485            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
22486                if (dumpState.onTitlePrinted())
22487                    pw.println();
22488                if (!checkin) {
22489                    pw.println("Features:");
22490                }
22491
22492                synchronized (mAvailableFeatures) {
22493                    for (FeatureInfo feat : mAvailableFeatures.values()) {
22494                        if (checkin) {
22495                            pw.print("feat,");
22496                            pw.print(feat.name);
22497                            pw.print(",");
22498                            pw.println(feat.version);
22499                        } else {
22500                            pw.print("  ");
22501                            pw.print(feat.name);
22502                            if (feat.version > 0) {
22503                                pw.print(" version=");
22504                                pw.print(feat.version);
22505                            }
22506                            pw.println();
22507                        }
22508                    }
22509                }
22510            }
22511
22512            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
22513                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
22514                        : "Activity Resolver Table:", "  ", packageName,
22515                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22516                    dumpState.setTitlePrinted(true);
22517                }
22518            }
22519            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
22520                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
22521                        : "Receiver Resolver Table:", "  ", packageName,
22522                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22523                    dumpState.setTitlePrinted(true);
22524                }
22525            }
22526            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
22527                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
22528                        : "Service Resolver Table:", "  ", packageName,
22529                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22530                    dumpState.setTitlePrinted(true);
22531                }
22532            }
22533            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
22534                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
22535                        : "Provider Resolver Table:", "  ", packageName,
22536                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22537                    dumpState.setTitlePrinted(true);
22538                }
22539            }
22540
22541            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22542                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22543                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22544                    int user = mSettings.mPreferredActivities.keyAt(i);
22545                    if (pir.dump(pw,
22546                            dumpState.getTitlePrinted()
22547                                ? "\nPreferred Activities User " + user + ":"
22548                                : "Preferred Activities User " + user + ":", "  ",
22549                            packageName, true, false)) {
22550                        dumpState.setTitlePrinted(true);
22551                    }
22552                }
22553            }
22554
22555            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22556                pw.flush();
22557                FileOutputStream fout = new FileOutputStream(fd);
22558                BufferedOutputStream str = new BufferedOutputStream(fout);
22559                XmlSerializer serializer = new FastXmlSerializer();
22560                try {
22561                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
22562                    serializer.startDocument(null, true);
22563                    serializer.setFeature(
22564                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22565                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22566                    serializer.endDocument();
22567                    serializer.flush();
22568                } catch (IllegalArgumentException e) {
22569                    pw.println("Failed writing: " + e);
22570                } catch (IllegalStateException e) {
22571                    pw.println("Failed writing: " + e);
22572                } catch (IOException e) {
22573                    pw.println("Failed writing: " + e);
22574                }
22575            }
22576
22577            if (!checkin
22578                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22579                    && packageName == null) {
22580                pw.println();
22581                int count = mSettings.mPackages.size();
22582                if (count == 0) {
22583                    pw.println("No applications!");
22584                    pw.println();
22585                } else {
22586                    final String prefix = "  ";
22587                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22588                    if (allPackageSettings.size() == 0) {
22589                        pw.println("No domain preferred apps!");
22590                        pw.println();
22591                    } else {
22592                        pw.println("App verification status:");
22593                        pw.println();
22594                        count = 0;
22595                        for (PackageSetting ps : allPackageSettings) {
22596                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22597                            if (ivi == null || ivi.getPackageName() == null) continue;
22598                            pw.println(prefix + "Package: " + ivi.getPackageName());
22599                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
22600                            pw.println(prefix + "Status:  " + ivi.getStatusString());
22601                            pw.println();
22602                            count++;
22603                        }
22604                        if (count == 0) {
22605                            pw.println(prefix + "No app verification established.");
22606                            pw.println();
22607                        }
22608                        for (int userId : sUserManager.getUserIds()) {
22609                            pw.println("App linkages for user " + userId + ":");
22610                            pw.println();
22611                            count = 0;
22612                            for (PackageSetting ps : allPackageSettings) {
22613                                final long status = ps.getDomainVerificationStatusForUser(userId);
22614                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22615                                        && !DEBUG_DOMAIN_VERIFICATION) {
22616                                    continue;
22617                                }
22618                                pw.println(prefix + "Package: " + ps.name);
22619                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22620                                String statusStr = IntentFilterVerificationInfo.
22621                                        getStatusStringFromValue(status);
22622                                pw.println(prefix + "Status:  " + statusStr);
22623                                pw.println();
22624                                count++;
22625                            }
22626                            if (count == 0) {
22627                                pw.println(prefix + "No configured app linkages.");
22628                                pw.println();
22629                            }
22630                        }
22631                    }
22632                }
22633            }
22634
22635            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22636                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22637                if (packageName == null && permissionNames == null) {
22638                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22639                        if (iperm == 0) {
22640                            if (dumpState.onTitlePrinted())
22641                                pw.println();
22642                            pw.println("AppOp Permissions:");
22643                        }
22644                        pw.print("  AppOp Permission ");
22645                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
22646                        pw.println(":");
22647                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
22648                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
22649                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
22650                        }
22651                    }
22652                }
22653            }
22654
22655            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
22656                boolean printedSomething = false;
22657                for (PackageParser.Provider p : mProviders.mProviders.values()) {
22658                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22659                        continue;
22660                    }
22661                    if (!printedSomething) {
22662                        if (dumpState.onTitlePrinted())
22663                            pw.println();
22664                        pw.println("Registered ContentProviders:");
22665                        printedSomething = true;
22666                    }
22667                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
22668                    pw.print("    "); pw.println(p.toString());
22669                }
22670                printedSomething = false;
22671                for (Map.Entry<String, PackageParser.Provider> entry :
22672                        mProvidersByAuthority.entrySet()) {
22673                    PackageParser.Provider p = entry.getValue();
22674                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22675                        continue;
22676                    }
22677                    if (!printedSomething) {
22678                        if (dumpState.onTitlePrinted())
22679                            pw.println();
22680                        pw.println("ContentProvider Authorities:");
22681                        printedSomething = true;
22682                    }
22683                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
22684                    pw.print("    "); pw.println(p.toString());
22685                    if (p.info != null && p.info.applicationInfo != null) {
22686                        final String appInfo = p.info.applicationInfo.toString();
22687                        pw.print("      applicationInfo="); pw.println(appInfo);
22688                    }
22689                }
22690            }
22691
22692            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
22693                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
22694            }
22695
22696            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
22697                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
22698            }
22699
22700            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
22701                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
22702            }
22703
22704            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
22705                if (dumpState.onTitlePrinted()) pw.println();
22706                pw.println("Package Changes:");
22707                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
22708                final int K = mChangedPackages.size();
22709                for (int i = 0; i < K; i++) {
22710                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
22711                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
22712                    final int N = changes.size();
22713                    if (N == 0) {
22714                        pw.print("    "); pw.println("No packages changed");
22715                    } else {
22716                        for (int j = 0; j < N; j++) {
22717                            final String pkgName = changes.valueAt(j);
22718                            final int sequenceNumber = changes.keyAt(j);
22719                            pw.print("    ");
22720                            pw.print("seq=");
22721                            pw.print(sequenceNumber);
22722                            pw.print(", package=");
22723                            pw.println(pkgName);
22724                        }
22725                    }
22726                }
22727            }
22728
22729            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
22730                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
22731            }
22732
22733            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
22734                // XXX should handle packageName != null by dumping only install data that
22735                // the given package is involved with.
22736                if (dumpState.onTitlePrinted()) pw.println();
22737
22738                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22739                ipw.println();
22740                ipw.println("Frozen packages:");
22741                ipw.increaseIndent();
22742                if (mFrozenPackages.size() == 0) {
22743                    ipw.println("(none)");
22744                } else {
22745                    for (int i = 0; i < mFrozenPackages.size(); i++) {
22746                        ipw.println(mFrozenPackages.valueAt(i));
22747                    }
22748                }
22749                ipw.decreaseIndent();
22750            }
22751
22752            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
22753                if (dumpState.onTitlePrinted()) pw.println();
22754
22755                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22756                ipw.println();
22757                ipw.println("Loaded volumes:");
22758                ipw.increaseIndent();
22759                if (mLoadedVolumes.size() == 0) {
22760                    ipw.println("(none)");
22761                } else {
22762                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
22763                        ipw.println(mLoadedVolumes.valueAt(i));
22764                    }
22765                }
22766                ipw.decreaseIndent();
22767            }
22768
22769            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
22770                if (dumpState.onTitlePrinted()) pw.println();
22771                dumpDexoptStateLPr(pw, packageName);
22772            }
22773
22774            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
22775                if (dumpState.onTitlePrinted()) pw.println();
22776                dumpCompilerStatsLPr(pw, packageName);
22777            }
22778
22779            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
22780                if (dumpState.onTitlePrinted()) pw.println();
22781                mSettings.dumpReadMessagesLPr(pw, dumpState);
22782
22783                pw.println();
22784                pw.println("Package warning messages:");
22785                BufferedReader in = null;
22786                String line = null;
22787                try {
22788                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22789                    while ((line = in.readLine()) != null) {
22790                        if (line.contains("ignored: updated version")) continue;
22791                        pw.println(line);
22792                    }
22793                } catch (IOException ignored) {
22794                } finally {
22795                    IoUtils.closeQuietly(in);
22796                }
22797            }
22798
22799            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
22800                BufferedReader in = null;
22801                String line = null;
22802                try {
22803                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22804                    while ((line = in.readLine()) != null) {
22805                        if (line.contains("ignored: updated version")) continue;
22806                        pw.print("msg,");
22807                        pw.println(line);
22808                    }
22809                } catch (IOException ignored) {
22810                } finally {
22811                    IoUtils.closeQuietly(in);
22812                }
22813            }
22814        }
22815
22816        // PackageInstaller should be called outside of mPackages lock
22817        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
22818            // XXX should handle packageName != null by dumping only install data that
22819            // the given package is involved with.
22820            if (dumpState.onTitlePrinted()) pw.println();
22821            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
22822        }
22823    }
22824
22825    private void dumpProto(FileDescriptor fd) {
22826        final ProtoOutputStream proto = new ProtoOutputStream(fd);
22827
22828        synchronized (mPackages) {
22829            final long requiredVerifierPackageToken =
22830                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
22831            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
22832            proto.write(
22833                    PackageServiceDumpProto.PackageShortProto.UID,
22834                    getPackageUid(
22835                            mRequiredVerifierPackage,
22836                            MATCH_DEBUG_TRIAGED_MISSING,
22837                            UserHandle.USER_SYSTEM));
22838            proto.end(requiredVerifierPackageToken);
22839
22840            if (mIntentFilterVerifierComponent != null) {
22841                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22842                final long verifierPackageToken =
22843                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
22844                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
22845                proto.write(
22846                        PackageServiceDumpProto.PackageShortProto.UID,
22847                        getPackageUid(
22848                                verifierPackageName,
22849                                MATCH_DEBUG_TRIAGED_MISSING,
22850                                UserHandle.USER_SYSTEM));
22851                proto.end(verifierPackageToken);
22852            }
22853
22854            dumpSharedLibrariesProto(proto);
22855            dumpFeaturesProto(proto);
22856            mSettings.dumpPackagesProto(proto);
22857            mSettings.dumpSharedUsersProto(proto);
22858            dumpMessagesProto(proto);
22859        }
22860        proto.flush();
22861    }
22862
22863    private void dumpMessagesProto(ProtoOutputStream proto) {
22864        BufferedReader in = null;
22865        String line = null;
22866        try {
22867            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22868            while ((line = in.readLine()) != null) {
22869                if (line.contains("ignored: updated version")) continue;
22870                proto.write(PackageServiceDumpProto.MESSAGES, line);
22871            }
22872        } catch (IOException ignored) {
22873        } finally {
22874            IoUtils.closeQuietly(in);
22875        }
22876    }
22877
22878    private void dumpFeaturesProto(ProtoOutputStream proto) {
22879        synchronized (mAvailableFeatures) {
22880            final int count = mAvailableFeatures.size();
22881            for (int i = 0; i < count; i++) {
22882                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
22883                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
22884                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
22885                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
22886                proto.end(featureToken);
22887            }
22888        }
22889    }
22890
22891    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
22892        final int count = mSharedLibraries.size();
22893        for (int i = 0; i < count; i++) {
22894            final String libName = mSharedLibraries.keyAt(i);
22895            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22896            if (versionedLib == null) {
22897                continue;
22898            }
22899            final int versionCount = versionedLib.size();
22900            for (int j = 0; j < versionCount; j++) {
22901                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
22902                final long sharedLibraryToken =
22903                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
22904                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
22905                final boolean isJar = (libEntry.path != null);
22906                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
22907                if (isJar) {
22908                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
22909                } else {
22910                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
22911                }
22912                proto.end(sharedLibraryToken);
22913            }
22914        }
22915    }
22916
22917    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
22918        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22919        ipw.println();
22920        ipw.println("Dexopt state:");
22921        ipw.increaseIndent();
22922        Collection<PackageParser.Package> packages = null;
22923        if (packageName != null) {
22924            PackageParser.Package targetPackage = mPackages.get(packageName);
22925            if (targetPackage != null) {
22926                packages = Collections.singletonList(targetPackage);
22927            } else {
22928                ipw.println("Unable to find package: " + packageName);
22929                return;
22930            }
22931        } else {
22932            packages = mPackages.values();
22933        }
22934
22935        for (PackageParser.Package pkg : packages) {
22936            ipw.println("[" + pkg.packageName + "]");
22937            ipw.increaseIndent();
22938            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
22939                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
22940            ipw.decreaseIndent();
22941        }
22942    }
22943
22944    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
22945        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22946        ipw.println();
22947        ipw.println("Compiler stats:");
22948        ipw.increaseIndent();
22949        Collection<PackageParser.Package> packages = null;
22950        if (packageName != null) {
22951            PackageParser.Package targetPackage = mPackages.get(packageName);
22952            if (targetPackage != null) {
22953                packages = Collections.singletonList(targetPackage);
22954            } else {
22955                ipw.println("Unable to find package: " + packageName);
22956                return;
22957            }
22958        } else {
22959            packages = mPackages.values();
22960        }
22961
22962        for (PackageParser.Package pkg : packages) {
22963            ipw.println("[" + pkg.packageName + "]");
22964            ipw.increaseIndent();
22965
22966            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
22967            if (stats == null) {
22968                ipw.println("(No recorded stats)");
22969            } else {
22970                stats.dump(ipw);
22971            }
22972            ipw.decreaseIndent();
22973        }
22974    }
22975
22976    private String dumpDomainString(String packageName) {
22977        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
22978                .getList();
22979        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
22980
22981        ArraySet<String> result = new ArraySet<>();
22982        if (iviList.size() > 0) {
22983            for (IntentFilterVerificationInfo ivi : iviList) {
22984                for (String host : ivi.getDomains()) {
22985                    result.add(host);
22986                }
22987            }
22988        }
22989        if (filters != null && filters.size() > 0) {
22990            for (IntentFilter filter : filters) {
22991                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
22992                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
22993                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
22994                    result.addAll(filter.getHostsList());
22995                }
22996            }
22997        }
22998
22999        StringBuilder sb = new StringBuilder(result.size() * 16);
23000        for (String domain : result) {
23001            if (sb.length() > 0) sb.append(" ");
23002            sb.append(domain);
23003        }
23004        return sb.toString();
23005    }
23006
23007    // ------- apps on sdcard specific code -------
23008    static final boolean DEBUG_SD_INSTALL = false;
23009
23010    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
23011
23012    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
23013
23014    private boolean mMediaMounted = false;
23015
23016    static String getEncryptKey() {
23017        try {
23018            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
23019                    SD_ENCRYPTION_KEYSTORE_NAME);
23020            if (sdEncKey == null) {
23021                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
23022                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
23023                if (sdEncKey == null) {
23024                    Slog.e(TAG, "Failed to create encryption keys");
23025                    return null;
23026                }
23027            }
23028            return sdEncKey;
23029        } catch (NoSuchAlgorithmException nsae) {
23030            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
23031            return null;
23032        } catch (IOException ioe) {
23033            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
23034            return null;
23035        }
23036    }
23037
23038    /*
23039     * Update media status on PackageManager.
23040     */
23041    @Override
23042    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
23043        enforceSystemOrRoot("Media status can only be updated by the system");
23044        // reader; this apparently protects mMediaMounted, but should probably
23045        // be a different lock in that case.
23046        synchronized (mPackages) {
23047            Log.i(TAG, "Updating external media status from "
23048                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
23049                    + (mediaStatus ? "mounted" : "unmounted"));
23050            if (DEBUG_SD_INSTALL)
23051                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
23052                        + ", mMediaMounted=" + mMediaMounted);
23053            if (mediaStatus == mMediaMounted) {
23054                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
23055                        : 0, -1);
23056                mHandler.sendMessage(msg);
23057                return;
23058            }
23059            mMediaMounted = mediaStatus;
23060        }
23061        // Queue up an async operation since the package installation may take a
23062        // little while.
23063        mHandler.post(new Runnable() {
23064            public void run() {
23065                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
23066            }
23067        });
23068    }
23069
23070    /**
23071     * Called by StorageManagerService when the initial ASECs to scan are available.
23072     * Should block until all the ASEC containers are finished being scanned.
23073     */
23074    public void scanAvailableAsecs() {
23075        updateExternalMediaStatusInner(true, false, false);
23076    }
23077
23078    /*
23079     * Collect information of applications on external media, map them against
23080     * existing containers and update information based on current mount status.
23081     * Please note that we always have to report status if reportStatus has been
23082     * set to true especially when unloading packages.
23083     */
23084    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
23085            boolean externalStorage) {
23086        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
23087        int[] uidArr = EmptyArray.INT;
23088
23089        final String[] list = PackageHelper.getSecureContainerList();
23090        if (ArrayUtils.isEmpty(list)) {
23091            Log.i(TAG, "No secure containers found");
23092        } else {
23093            // Process list of secure containers and categorize them
23094            // as active or stale based on their package internal state.
23095
23096            // reader
23097            synchronized (mPackages) {
23098                for (String cid : list) {
23099                    // Leave stages untouched for now; installer service owns them
23100                    if (PackageInstallerService.isStageName(cid)) continue;
23101
23102                    if (DEBUG_SD_INSTALL)
23103                        Log.i(TAG, "Processing container " + cid);
23104                    String pkgName = getAsecPackageName(cid);
23105                    if (pkgName == null) {
23106                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
23107                        continue;
23108                    }
23109                    if (DEBUG_SD_INSTALL)
23110                        Log.i(TAG, "Looking for pkg : " + pkgName);
23111
23112                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
23113                    if (ps == null) {
23114                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
23115                        continue;
23116                    }
23117
23118                    /*
23119                     * Skip packages that are not external if we're unmounting
23120                     * external storage.
23121                     */
23122                    if (externalStorage && !isMounted && !isExternal(ps)) {
23123                        continue;
23124                    }
23125
23126                    final AsecInstallArgs args = new AsecInstallArgs(cid,
23127                            getAppDexInstructionSets(ps), ps.isForwardLocked());
23128                    // The package status is changed only if the code path
23129                    // matches between settings and the container id.
23130                    if (ps.codePathString != null
23131                            && ps.codePathString.startsWith(args.getCodePath())) {
23132                        if (DEBUG_SD_INSTALL) {
23133                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
23134                                    + " at code path: " + ps.codePathString);
23135                        }
23136
23137                        // We do have a valid package installed on sdcard
23138                        processCids.put(args, ps.codePathString);
23139                        final int uid = ps.appId;
23140                        if (uid != -1) {
23141                            uidArr = ArrayUtils.appendInt(uidArr, uid);
23142                        }
23143                    } else {
23144                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
23145                                + ps.codePathString);
23146                    }
23147                }
23148            }
23149
23150            Arrays.sort(uidArr);
23151        }
23152
23153        // Process packages with valid entries.
23154        if (isMounted) {
23155            if (DEBUG_SD_INSTALL)
23156                Log.i(TAG, "Loading packages");
23157            loadMediaPackages(processCids, uidArr, externalStorage);
23158            startCleaningPackages();
23159            mInstallerService.onSecureContainersAvailable();
23160        } else {
23161            if (DEBUG_SD_INSTALL)
23162                Log.i(TAG, "Unloading packages");
23163            unloadMediaPackages(processCids, uidArr, reportStatus);
23164        }
23165    }
23166
23167    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23168            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
23169        final int size = infos.size();
23170        final String[] packageNames = new String[size];
23171        final int[] packageUids = new int[size];
23172        for (int i = 0; i < size; i++) {
23173            final ApplicationInfo info = infos.get(i);
23174            packageNames[i] = info.packageName;
23175            packageUids[i] = info.uid;
23176        }
23177        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
23178                finishedReceiver);
23179    }
23180
23181    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23182            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
23183        sendResourcesChangedBroadcast(mediaStatus, replacing,
23184                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
23185    }
23186
23187    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23188            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
23189        int size = pkgList.length;
23190        if (size > 0) {
23191            // Send broadcasts here
23192            Bundle extras = new Bundle();
23193            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
23194            if (uidArr != null) {
23195                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
23196            }
23197            if (replacing) {
23198                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
23199            }
23200            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
23201                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
23202            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
23203        }
23204    }
23205
23206   /*
23207     * Look at potentially valid container ids from processCids If package
23208     * information doesn't match the one on record or package scanning fails,
23209     * the cid is added to list of removeCids. We currently don't delete stale
23210     * containers.
23211     */
23212    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
23213            boolean externalStorage) {
23214        ArrayList<String> pkgList = new ArrayList<String>();
23215        Set<AsecInstallArgs> keys = processCids.keySet();
23216
23217        for (AsecInstallArgs args : keys) {
23218            String codePath = processCids.get(args);
23219            if (DEBUG_SD_INSTALL)
23220                Log.i(TAG, "Loading container : " + args.cid);
23221            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
23222            try {
23223                // Make sure there are no container errors first.
23224                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
23225                    Slog.e(TAG, "Failed to mount cid : " + args.cid
23226                            + " when installing from sdcard");
23227                    continue;
23228                }
23229                // Check code path here.
23230                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
23231                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
23232                            + " does not match one in settings " + codePath);
23233                    continue;
23234                }
23235                // Parse package
23236                int parseFlags = mDefParseFlags;
23237                if (args.isExternalAsec()) {
23238                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
23239                }
23240                if (args.isFwdLocked()) {
23241                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
23242                }
23243
23244                synchronized (mInstallLock) {
23245                    PackageParser.Package pkg = null;
23246                    try {
23247                        // Sadly we don't know the package name yet to freeze it
23248                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
23249                                SCAN_IGNORE_FROZEN, 0, null);
23250                    } catch (PackageManagerException e) {
23251                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
23252                    }
23253                    // Scan the package
23254                    if (pkg != null) {
23255                        /*
23256                         * TODO why is the lock being held? doPostInstall is
23257                         * called in other places without the lock. This needs
23258                         * to be straightened out.
23259                         */
23260                        // writer
23261                        synchronized (mPackages) {
23262                            retCode = PackageManager.INSTALL_SUCCEEDED;
23263                            pkgList.add(pkg.packageName);
23264                            // Post process args
23265                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
23266                                    pkg.applicationInfo.uid);
23267                        }
23268                    } else {
23269                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
23270                    }
23271                }
23272
23273            } finally {
23274                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
23275                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
23276                }
23277            }
23278        }
23279        // writer
23280        synchronized (mPackages) {
23281            // If the platform SDK has changed since the last time we booted,
23282            // we need to re-grant app permission to catch any new ones that
23283            // appear. This is really a hack, and means that apps can in some
23284            // cases get permissions that the user didn't initially explicitly
23285            // allow... it would be nice to have some better way to handle
23286            // this situation.
23287            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
23288                    : mSettings.getInternalVersion();
23289            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
23290                    : StorageManager.UUID_PRIVATE_INTERNAL;
23291
23292            int updateFlags = UPDATE_PERMISSIONS_ALL;
23293            if (ver.sdkVersion != mSdkVersion) {
23294                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23295                        + mSdkVersion + "; regranting permissions for external");
23296                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23297            }
23298            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23299
23300            // Yay, everything is now upgraded
23301            ver.forceCurrent();
23302
23303            // can downgrade to reader
23304            // Persist settings
23305            mSettings.writeLPr();
23306        }
23307        // Send a broadcast to let everyone know we are done processing
23308        if (pkgList.size() > 0) {
23309            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
23310        }
23311    }
23312
23313   /*
23314     * Utility method to unload a list of specified containers
23315     */
23316    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
23317        // Just unmount all valid containers.
23318        for (AsecInstallArgs arg : cidArgs) {
23319            synchronized (mInstallLock) {
23320                arg.doPostDeleteLI(false);
23321           }
23322       }
23323   }
23324
23325    /*
23326     * Unload packages mounted on external media. This involves deleting package
23327     * data from internal structures, sending broadcasts about disabled packages,
23328     * gc'ing to free up references, unmounting all secure containers
23329     * corresponding to packages on external media, and posting a
23330     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
23331     * that we always have to post this message if status has been requested no
23332     * matter what.
23333     */
23334    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
23335            final boolean reportStatus) {
23336        if (DEBUG_SD_INSTALL)
23337            Log.i(TAG, "unloading media packages");
23338        ArrayList<String> pkgList = new ArrayList<String>();
23339        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
23340        final Set<AsecInstallArgs> keys = processCids.keySet();
23341        for (AsecInstallArgs args : keys) {
23342            String pkgName = args.getPackageName();
23343            if (DEBUG_SD_INSTALL)
23344                Log.i(TAG, "Trying to unload pkg : " + pkgName);
23345            // Delete package internally
23346            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23347            synchronized (mInstallLock) {
23348                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23349                final boolean res;
23350                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
23351                        "unloadMediaPackages")) {
23352                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
23353                            null);
23354                }
23355                if (res) {
23356                    pkgList.add(pkgName);
23357                } else {
23358                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
23359                    failedList.add(args);
23360                }
23361            }
23362        }
23363
23364        // reader
23365        synchronized (mPackages) {
23366            // We didn't update the settings after removing each package;
23367            // write them now for all packages.
23368            mSettings.writeLPr();
23369        }
23370
23371        // We have to absolutely send UPDATED_MEDIA_STATUS only
23372        // after confirming that all the receivers processed the ordered
23373        // broadcast when packages get disabled, force a gc to clean things up.
23374        // and unload all the containers.
23375        if (pkgList.size() > 0) {
23376            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
23377                    new IIntentReceiver.Stub() {
23378                public void performReceive(Intent intent, int resultCode, String data,
23379                        Bundle extras, boolean ordered, boolean sticky,
23380                        int sendingUser) throws RemoteException {
23381                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
23382                            reportStatus ? 1 : 0, 1, keys);
23383                    mHandler.sendMessage(msg);
23384                }
23385            });
23386        } else {
23387            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
23388                    keys);
23389            mHandler.sendMessage(msg);
23390        }
23391    }
23392
23393    private void loadPrivatePackages(final VolumeInfo vol) {
23394        mHandler.post(new Runnable() {
23395            @Override
23396            public void run() {
23397                loadPrivatePackagesInner(vol);
23398            }
23399        });
23400    }
23401
23402    private void loadPrivatePackagesInner(VolumeInfo vol) {
23403        final String volumeUuid = vol.fsUuid;
23404        if (TextUtils.isEmpty(volumeUuid)) {
23405            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
23406            return;
23407        }
23408
23409        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
23410        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
23411        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
23412
23413        final VersionInfo ver;
23414        final List<PackageSetting> packages;
23415        synchronized (mPackages) {
23416            ver = mSettings.findOrCreateVersion(volumeUuid);
23417            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23418        }
23419
23420        for (PackageSetting ps : packages) {
23421            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
23422            synchronized (mInstallLock) {
23423                final PackageParser.Package pkg;
23424                try {
23425                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
23426                    loaded.add(pkg.applicationInfo);
23427
23428                } catch (PackageManagerException e) {
23429                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
23430                }
23431
23432                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
23433                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
23434                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
23435                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
23436                }
23437            }
23438        }
23439
23440        // Reconcile app data for all started/unlocked users
23441        final StorageManager sm = mContext.getSystemService(StorageManager.class);
23442        final UserManager um = mContext.getSystemService(UserManager.class);
23443        UserManagerInternal umInternal = getUserManagerInternal();
23444        for (UserInfo user : um.getUsers()) {
23445            final int flags;
23446            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23447                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23448            } else if (umInternal.isUserRunning(user.id)) {
23449                flags = StorageManager.FLAG_STORAGE_DE;
23450            } else {
23451                continue;
23452            }
23453
23454            try {
23455                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
23456                synchronized (mInstallLock) {
23457                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
23458                }
23459            } catch (IllegalStateException e) {
23460                // Device was probably ejected, and we'll process that event momentarily
23461                Slog.w(TAG, "Failed to prepare storage: " + e);
23462            }
23463        }
23464
23465        synchronized (mPackages) {
23466            int updateFlags = UPDATE_PERMISSIONS_ALL;
23467            if (ver.sdkVersion != mSdkVersion) {
23468                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23469                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
23470                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23471            }
23472            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23473
23474            // Yay, everything is now upgraded
23475            ver.forceCurrent();
23476
23477            mSettings.writeLPr();
23478        }
23479
23480        for (PackageFreezer freezer : freezers) {
23481            freezer.close();
23482        }
23483
23484        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
23485        sendResourcesChangedBroadcast(true, false, loaded, null);
23486        mLoadedVolumes.add(vol.getId());
23487    }
23488
23489    private void unloadPrivatePackages(final VolumeInfo vol) {
23490        mHandler.post(new Runnable() {
23491            @Override
23492            public void run() {
23493                unloadPrivatePackagesInner(vol);
23494            }
23495        });
23496    }
23497
23498    private void unloadPrivatePackagesInner(VolumeInfo vol) {
23499        final String volumeUuid = vol.fsUuid;
23500        if (TextUtils.isEmpty(volumeUuid)) {
23501            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
23502            return;
23503        }
23504
23505        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
23506        synchronized (mInstallLock) {
23507        synchronized (mPackages) {
23508            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
23509            for (PackageSetting ps : packages) {
23510                if (ps.pkg == null) continue;
23511
23512                final ApplicationInfo info = ps.pkg.applicationInfo;
23513                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23514                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23515
23516                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
23517                        "unloadPrivatePackagesInner")) {
23518                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
23519                            false, null)) {
23520                        unloaded.add(info);
23521                    } else {
23522                        Slog.w(TAG, "Failed to unload " + ps.codePath);
23523                    }
23524                }
23525
23526                // Try very hard to release any references to this package
23527                // so we don't risk the system server being killed due to
23528                // open FDs
23529                AttributeCache.instance().removePackage(ps.name);
23530            }
23531
23532            mSettings.writeLPr();
23533        }
23534        }
23535
23536        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
23537        sendResourcesChangedBroadcast(false, false, unloaded, null);
23538        mLoadedVolumes.remove(vol.getId());
23539
23540        // Try very hard to release any references to this path so we don't risk
23541        // the system server being killed due to open FDs
23542        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
23543
23544        for (int i = 0; i < 3; i++) {
23545            System.gc();
23546            System.runFinalization();
23547        }
23548    }
23549
23550    private void assertPackageKnown(String volumeUuid, String packageName)
23551            throws PackageManagerException {
23552        synchronized (mPackages) {
23553            // Normalize package name to handle renamed packages
23554            packageName = normalizePackageNameLPr(packageName);
23555
23556            final PackageSetting ps = mSettings.mPackages.get(packageName);
23557            if (ps == null) {
23558                throw new PackageManagerException("Package " + packageName + " is unknown");
23559            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23560                throw new PackageManagerException(
23561                        "Package " + packageName + " found on unknown volume " + volumeUuid
23562                                + "; expected volume " + ps.volumeUuid);
23563            }
23564        }
23565    }
23566
23567    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23568            throws PackageManagerException {
23569        synchronized (mPackages) {
23570            // Normalize package name to handle renamed packages
23571            packageName = normalizePackageNameLPr(packageName);
23572
23573            final PackageSetting ps = mSettings.mPackages.get(packageName);
23574            if (ps == null) {
23575                throw new PackageManagerException("Package " + packageName + " is unknown");
23576            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23577                throw new PackageManagerException(
23578                        "Package " + packageName + " found on unknown volume " + volumeUuid
23579                                + "; expected volume " + ps.volumeUuid);
23580            } else if (!ps.getInstalled(userId)) {
23581                throw new PackageManagerException(
23582                        "Package " + packageName + " not installed for user " + userId);
23583            }
23584        }
23585    }
23586
23587    private List<String> collectAbsoluteCodePaths() {
23588        synchronized (mPackages) {
23589            List<String> codePaths = new ArrayList<>();
23590            final int packageCount = mSettings.mPackages.size();
23591            for (int i = 0; i < packageCount; i++) {
23592                final PackageSetting ps = mSettings.mPackages.valueAt(i);
23593                codePaths.add(ps.codePath.getAbsolutePath());
23594            }
23595            return codePaths;
23596        }
23597    }
23598
23599    /**
23600     * Examine all apps present on given mounted volume, and destroy apps that
23601     * aren't expected, either due to uninstallation or reinstallation on
23602     * another volume.
23603     */
23604    private void reconcileApps(String volumeUuid) {
23605        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
23606        List<File> filesToDelete = null;
23607
23608        final File[] files = FileUtils.listFilesOrEmpty(
23609                Environment.getDataAppDirectory(volumeUuid));
23610        for (File file : files) {
23611            final boolean isPackage = (isApkFile(file) || file.isDirectory())
23612                    && !PackageInstallerService.isStageName(file.getName());
23613            if (!isPackage) {
23614                // Ignore entries which are not packages
23615                continue;
23616            }
23617
23618            String absolutePath = file.getAbsolutePath();
23619
23620            boolean pathValid = false;
23621            final int absoluteCodePathCount = absoluteCodePaths.size();
23622            for (int i = 0; i < absoluteCodePathCount; i++) {
23623                String absoluteCodePath = absoluteCodePaths.get(i);
23624                if (absolutePath.startsWith(absoluteCodePath)) {
23625                    pathValid = true;
23626                    break;
23627                }
23628            }
23629
23630            if (!pathValid) {
23631                if (filesToDelete == null) {
23632                    filesToDelete = new ArrayList<>();
23633                }
23634                filesToDelete.add(file);
23635            }
23636        }
23637
23638        if (filesToDelete != null) {
23639            final int fileToDeleteCount = filesToDelete.size();
23640            for (int i = 0; i < fileToDeleteCount; i++) {
23641                File fileToDelete = filesToDelete.get(i);
23642                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23643                synchronized (mInstallLock) {
23644                    removeCodePathLI(fileToDelete);
23645                }
23646            }
23647        }
23648    }
23649
23650    /**
23651     * Reconcile all app data for the given user.
23652     * <p>
23653     * Verifies that directories exist and that ownership and labeling is
23654     * correct for all installed apps on all mounted volumes.
23655     */
23656    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
23657        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23658        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
23659            final String volumeUuid = vol.getFsUuid();
23660            synchronized (mInstallLock) {
23661                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
23662            }
23663        }
23664    }
23665
23666    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23667            boolean migrateAppData) {
23668        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
23669    }
23670
23671    /**
23672     * Reconcile all app data on given mounted volume.
23673     * <p>
23674     * Destroys app data that isn't expected, either due to uninstallation or
23675     * reinstallation on another volume.
23676     * <p>
23677     * Verifies that directories exist and that ownership and labeling is
23678     * correct for all installed apps.
23679     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
23680     */
23681    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23682            boolean migrateAppData, boolean onlyCoreApps) {
23683        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
23684                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
23685        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
23686
23687        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
23688        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
23689
23690        // First look for stale data that doesn't belong, and check if things
23691        // have changed since we did our last restorecon
23692        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23693            if (StorageManager.isFileEncryptedNativeOrEmulated()
23694                    && !StorageManager.isUserKeyUnlocked(userId)) {
23695                throw new RuntimeException(
23696                        "Yikes, someone asked us to reconcile CE storage while " + userId
23697                                + " was still locked; this would have caused massive data loss!");
23698            }
23699
23700            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
23701            for (File file : files) {
23702                final String packageName = file.getName();
23703                try {
23704                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23705                } catch (PackageManagerException e) {
23706                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23707                    try {
23708                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23709                                StorageManager.FLAG_STORAGE_CE, 0);
23710                    } catch (InstallerException e2) {
23711                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23712                    }
23713                }
23714            }
23715        }
23716        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
23717            final File[] files = FileUtils.listFilesOrEmpty(deDir);
23718            for (File file : files) {
23719                final String packageName = file.getName();
23720                try {
23721                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23722                } catch (PackageManagerException e) {
23723                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23724                    try {
23725                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23726                                StorageManager.FLAG_STORAGE_DE, 0);
23727                    } catch (InstallerException e2) {
23728                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23729                    }
23730                }
23731            }
23732        }
23733
23734        // Ensure that data directories are ready to roll for all packages
23735        // installed for this volume and user
23736        final List<PackageSetting> packages;
23737        synchronized (mPackages) {
23738            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23739        }
23740        int preparedCount = 0;
23741        for (PackageSetting ps : packages) {
23742            final String packageName = ps.name;
23743            if (ps.pkg == null) {
23744                Slog.w(TAG, "Odd, missing scanned package " + packageName);
23745                // TODO: might be due to legacy ASEC apps; we should circle back
23746                // and reconcile again once they're scanned
23747                continue;
23748            }
23749            // Skip non-core apps if requested
23750            if (onlyCoreApps && !ps.pkg.coreApp) {
23751                result.add(packageName);
23752                continue;
23753            }
23754
23755            if (ps.getInstalled(userId)) {
23756                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
23757                preparedCount++;
23758            }
23759        }
23760
23761        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
23762        return result;
23763    }
23764
23765    /**
23766     * Prepare app data for the given app just after it was installed or
23767     * upgraded. This method carefully only touches users that it's installed
23768     * for, and it forces a restorecon to handle any seinfo changes.
23769     * <p>
23770     * Verifies that directories exist and that ownership and labeling is
23771     * correct for all installed apps. If there is an ownership mismatch, it
23772     * will try recovering system apps by wiping data; third-party app data is
23773     * left intact.
23774     * <p>
23775     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
23776     */
23777    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
23778        final PackageSetting ps;
23779        synchronized (mPackages) {
23780            ps = mSettings.mPackages.get(pkg.packageName);
23781            mSettings.writeKernelMappingLPr(ps);
23782        }
23783
23784        final UserManager um = mContext.getSystemService(UserManager.class);
23785        UserManagerInternal umInternal = getUserManagerInternal();
23786        for (UserInfo user : um.getUsers()) {
23787            final int flags;
23788            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23789                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23790            } else if (umInternal.isUserRunning(user.id)) {
23791                flags = StorageManager.FLAG_STORAGE_DE;
23792            } else {
23793                continue;
23794            }
23795
23796            if (ps.getInstalled(user.id)) {
23797                // TODO: when user data is locked, mark that we're still dirty
23798                prepareAppDataLIF(pkg, user.id, flags);
23799            }
23800        }
23801    }
23802
23803    /**
23804     * Prepare app data for the given app.
23805     * <p>
23806     * Verifies that directories exist and that ownership and labeling is
23807     * correct for all installed apps. If there is an ownership mismatch, this
23808     * will try recovering system apps by wiping data; third-party app data is
23809     * left intact.
23810     */
23811    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
23812        if (pkg == null) {
23813            Slog.wtf(TAG, "Package was null!", new Throwable());
23814            return;
23815        }
23816        prepareAppDataLeafLIF(pkg, userId, flags);
23817        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23818        for (int i = 0; i < childCount; i++) {
23819            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
23820        }
23821    }
23822
23823    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
23824            boolean maybeMigrateAppData) {
23825        prepareAppDataLIF(pkg, userId, flags);
23826
23827        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
23828            // We may have just shuffled around app data directories, so
23829            // prepare them one more time
23830            prepareAppDataLIF(pkg, userId, flags);
23831        }
23832    }
23833
23834    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23835        if (DEBUG_APP_DATA) {
23836            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
23837                    + Integer.toHexString(flags));
23838        }
23839
23840        final String volumeUuid = pkg.volumeUuid;
23841        final String packageName = pkg.packageName;
23842        final ApplicationInfo app = pkg.applicationInfo;
23843        final int appId = UserHandle.getAppId(app.uid);
23844
23845        Preconditions.checkNotNull(app.seInfo);
23846
23847        long ceDataInode = -1;
23848        try {
23849            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23850                    appId, app.seInfo, app.targetSdkVersion);
23851        } catch (InstallerException e) {
23852            if (app.isSystemApp()) {
23853                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
23854                        + ", but trying to recover: " + e);
23855                destroyAppDataLeafLIF(pkg, userId, flags);
23856                try {
23857                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23858                            appId, app.seInfo, app.targetSdkVersion);
23859                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
23860                } catch (InstallerException e2) {
23861                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
23862                }
23863            } else {
23864                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
23865            }
23866        }
23867
23868        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
23869            // TODO: mark this structure as dirty so we persist it!
23870            synchronized (mPackages) {
23871                final PackageSetting ps = mSettings.mPackages.get(packageName);
23872                if (ps != null) {
23873                    ps.setCeDataInode(ceDataInode, userId);
23874                }
23875            }
23876        }
23877
23878        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23879    }
23880
23881    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
23882        if (pkg == null) {
23883            Slog.wtf(TAG, "Package was null!", new Throwable());
23884            return;
23885        }
23886        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23887        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23888        for (int i = 0; i < childCount; i++) {
23889            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
23890        }
23891    }
23892
23893    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23894        final String volumeUuid = pkg.volumeUuid;
23895        final String packageName = pkg.packageName;
23896        final ApplicationInfo app = pkg.applicationInfo;
23897
23898        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23899            // Create a native library symlink only if we have native libraries
23900            // and if the native libraries are 32 bit libraries. We do not provide
23901            // this symlink for 64 bit libraries.
23902            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
23903                final String nativeLibPath = app.nativeLibraryDir;
23904                try {
23905                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
23906                            nativeLibPath, userId);
23907                } catch (InstallerException e) {
23908                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
23909                }
23910            }
23911        }
23912    }
23913
23914    /**
23915     * For system apps on non-FBE devices, this method migrates any existing
23916     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
23917     * requested by the app.
23918     */
23919    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
23920        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
23921                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
23922            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
23923                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
23924            try {
23925                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
23926                        storageTarget);
23927            } catch (InstallerException e) {
23928                logCriticalInfo(Log.WARN,
23929                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
23930            }
23931            return true;
23932        } else {
23933            return false;
23934        }
23935    }
23936
23937    public PackageFreezer freezePackage(String packageName, String killReason) {
23938        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
23939    }
23940
23941    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
23942        return new PackageFreezer(packageName, userId, killReason);
23943    }
23944
23945    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
23946            String killReason) {
23947        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
23948    }
23949
23950    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
23951            String killReason) {
23952        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
23953            return new PackageFreezer();
23954        } else {
23955            return freezePackage(packageName, userId, killReason);
23956        }
23957    }
23958
23959    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
23960            String killReason) {
23961        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
23962    }
23963
23964    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
23965            String killReason) {
23966        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
23967            return new PackageFreezer();
23968        } else {
23969            return freezePackage(packageName, userId, killReason);
23970        }
23971    }
23972
23973    /**
23974     * Class that freezes and kills the given package upon creation, and
23975     * unfreezes it upon closing. This is typically used when doing surgery on
23976     * app code/data to prevent the app from running while you're working.
23977     */
23978    private class PackageFreezer implements AutoCloseable {
23979        private final String mPackageName;
23980        private final PackageFreezer[] mChildren;
23981
23982        private final boolean mWeFroze;
23983
23984        private final AtomicBoolean mClosed = new AtomicBoolean();
23985        private final CloseGuard mCloseGuard = CloseGuard.get();
23986
23987        /**
23988         * Create and return a stub freezer that doesn't actually do anything,
23989         * typically used when someone requested
23990         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
23991         * {@link PackageManager#DELETE_DONT_KILL_APP}.
23992         */
23993        public PackageFreezer() {
23994            mPackageName = null;
23995            mChildren = null;
23996            mWeFroze = false;
23997            mCloseGuard.open("close");
23998        }
23999
24000        public PackageFreezer(String packageName, int userId, String killReason) {
24001            synchronized (mPackages) {
24002                mPackageName = packageName;
24003                mWeFroze = mFrozenPackages.add(mPackageName);
24004
24005                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
24006                if (ps != null) {
24007                    killApplication(ps.name, ps.appId, userId, killReason);
24008                }
24009
24010                final PackageParser.Package p = mPackages.get(packageName);
24011                if (p != null && p.childPackages != null) {
24012                    final int N = p.childPackages.size();
24013                    mChildren = new PackageFreezer[N];
24014                    for (int i = 0; i < N; i++) {
24015                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
24016                                userId, killReason);
24017                    }
24018                } else {
24019                    mChildren = null;
24020                }
24021            }
24022            mCloseGuard.open("close");
24023        }
24024
24025        @Override
24026        protected void finalize() throws Throwable {
24027            try {
24028                if (mCloseGuard != null) {
24029                    mCloseGuard.warnIfOpen();
24030                }
24031
24032                close();
24033            } finally {
24034                super.finalize();
24035            }
24036        }
24037
24038        @Override
24039        public void close() {
24040            mCloseGuard.close();
24041            if (mClosed.compareAndSet(false, true)) {
24042                synchronized (mPackages) {
24043                    if (mWeFroze) {
24044                        mFrozenPackages.remove(mPackageName);
24045                    }
24046
24047                    if (mChildren != null) {
24048                        for (PackageFreezer freezer : mChildren) {
24049                            freezer.close();
24050                        }
24051                    }
24052                }
24053            }
24054        }
24055    }
24056
24057    /**
24058     * Verify that given package is currently frozen.
24059     */
24060    private void checkPackageFrozen(String packageName) {
24061        synchronized (mPackages) {
24062            if (!mFrozenPackages.contains(packageName)) {
24063                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
24064            }
24065        }
24066    }
24067
24068    @Override
24069    public int movePackage(final String packageName, final String volumeUuid) {
24070        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
24071
24072        final int callingUid = Binder.getCallingUid();
24073        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
24074        final int moveId = mNextMoveId.getAndIncrement();
24075        mHandler.post(new Runnable() {
24076            @Override
24077            public void run() {
24078                try {
24079                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
24080                } catch (PackageManagerException e) {
24081                    Slog.w(TAG, "Failed to move " + packageName, e);
24082                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
24083                }
24084            }
24085        });
24086        return moveId;
24087    }
24088
24089    private void movePackageInternal(final String packageName, final String volumeUuid,
24090            final int moveId, final int callingUid, UserHandle user)
24091                    throws PackageManagerException {
24092        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24093        final PackageManager pm = mContext.getPackageManager();
24094
24095        final boolean currentAsec;
24096        final String currentVolumeUuid;
24097        final File codeFile;
24098        final String installerPackageName;
24099        final String packageAbiOverride;
24100        final int appId;
24101        final String seinfo;
24102        final String label;
24103        final int targetSdkVersion;
24104        final PackageFreezer freezer;
24105        final int[] installedUserIds;
24106
24107        // reader
24108        synchronized (mPackages) {
24109            final PackageParser.Package pkg = mPackages.get(packageName);
24110            final PackageSetting ps = mSettings.mPackages.get(packageName);
24111            if (pkg == null
24112                    || ps == null
24113                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
24114                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
24115            }
24116            if (pkg.applicationInfo.isSystemApp()) {
24117                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
24118                        "Cannot move system application");
24119            }
24120
24121            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
24122            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
24123                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
24124            if (isInternalStorage && !allow3rdPartyOnInternal) {
24125                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
24126                        "3rd party apps are not allowed on internal storage");
24127            }
24128
24129            if (pkg.applicationInfo.isExternalAsec()) {
24130                currentAsec = true;
24131                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
24132            } else if (pkg.applicationInfo.isForwardLocked()) {
24133                currentAsec = true;
24134                currentVolumeUuid = "forward_locked";
24135            } else {
24136                currentAsec = false;
24137                currentVolumeUuid = ps.volumeUuid;
24138
24139                final File probe = new File(pkg.codePath);
24140                final File probeOat = new File(probe, "oat");
24141                if (!probe.isDirectory() || !probeOat.isDirectory()) {
24142                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24143                            "Move only supported for modern cluster style installs");
24144                }
24145            }
24146
24147            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
24148                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24149                        "Package already moved to " + volumeUuid);
24150            }
24151            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
24152                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
24153                        "Device admin cannot be moved");
24154            }
24155
24156            if (mFrozenPackages.contains(packageName)) {
24157                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
24158                        "Failed to move already frozen package");
24159            }
24160
24161            codeFile = new File(pkg.codePath);
24162            installerPackageName = ps.installerPackageName;
24163            packageAbiOverride = ps.cpuAbiOverrideString;
24164            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
24165            seinfo = pkg.applicationInfo.seInfo;
24166            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
24167            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
24168            freezer = freezePackage(packageName, "movePackageInternal");
24169            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
24170        }
24171
24172        final Bundle extras = new Bundle();
24173        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
24174        extras.putString(Intent.EXTRA_TITLE, label);
24175        mMoveCallbacks.notifyCreated(moveId, extras);
24176
24177        int installFlags;
24178        final boolean moveCompleteApp;
24179        final File measurePath;
24180
24181        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
24182            installFlags = INSTALL_INTERNAL;
24183            moveCompleteApp = !currentAsec;
24184            measurePath = Environment.getDataAppDirectory(volumeUuid);
24185        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
24186            installFlags = INSTALL_EXTERNAL;
24187            moveCompleteApp = false;
24188            measurePath = storage.getPrimaryPhysicalVolume().getPath();
24189        } else {
24190            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
24191            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
24192                    || !volume.isMountedWritable()) {
24193                freezer.close();
24194                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24195                        "Move location not mounted private volume");
24196            }
24197
24198            Preconditions.checkState(!currentAsec);
24199
24200            installFlags = INSTALL_INTERNAL;
24201            moveCompleteApp = true;
24202            measurePath = Environment.getDataAppDirectory(volumeUuid);
24203        }
24204
24205        // If we're moving app data around, we need all the users unlocked
24206        if (moveCompleteApp) {
24207            for (int userId : installedUserIds) {
24208                if (StorageManager.isFileEncryptedNativeOrEmulated()
24209                        && !StorageManager.isUserKeyUnlocked(userId)) {
24210                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
24211                            "User " + userId + " must be unlocked");
24212                }
24213            }
24214        }
24215
24216        final PackageStats stats = new PackageStats(null, -1);
24217        synchronized (mInstaller) {
24218            for (int userId : installedUserIds) {
24219                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
24220                    freezer.close();
24221                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24222                            "Failed to measure package size");
24223                }
24224            }
24225        }
24226
24227        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
24228                + stats.dataSize);
24229
24230        final long startFreeBytes = measurePath.getUsableSpace();
24231        final long sizeBytes;
24232        if (moveCompleteApp) {
24233            sizeBytes = stats.codeSize + stats.dataSize;
24234        } else {
24235            sizeBytes = stats.codeSize;
24236        }
24237
24238        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
24239            freezer.close();
24240            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24241                    "Not enough free space to move");
24242        }
24243
24244        mMoveCallbacks.notifyStatusChanged(moveId, 10);
24245
24246        final CountDownLatch installedLatch = new CountDownLatch(1);
24247        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
24248            @Override
24249            public void onUserActionRequired(Intent intent) throws RemoteException {
24250                throw new IllegalStateException();
24251            }
24252
24253            @Override
24254            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
24255                    Bundle extras) throws RemoteException {
24256                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
24257                        + PackageManager.installStatusToString(returnCode, msg));
24258
24259                installedLatch.countDown();
24260                freezer.close();
24261
24262                final int status = PackageManager.installStatusToPublicStatus(returnCode);
24263                switch (status) {
24264                    case PackageInstaller.STATUS_SUCCESS:
24265                        mMoveCallbacks.notifyStatusChanged(moveId,
24266                                PackageManager.MOVE_SUCCEEDED);
24267                        break;
24268                    case PackageInstaller.STATUS_FAILURE_STORAGE:
24269                        mMoveCallbacks.notifyStatusChanged(moveId,
24270                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
24271                        break;
24272                    default:
24273                        mMoveCallbacks.notifyStatusChanged(moveId,
24274                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
24275                        break;
24276                }
24277            }
24278        };
24279
24280        final MoveInfo move;
24281        if (moveCompleteApp) {
24282            // Kick off a thread to report progress estimates
24283            new Thread() {
24284                @Override
24285                public void run() {
24286                    while (true) {
24287                        try {
24288                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
24289                                break;
24290                            }
24291                        } catch (InterruptedException ignored) {
24292                        }
24293
24294                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
24295                        final int progress = 10 + (int) MathUtils.constrain(
24296                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
24297                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
24298                    }
24299                }
24300            }.start();
24301
24302            final String dataAppName = codeFile.getName();
24303            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
24304                    dataAppName, appId, seinfo, targetSdkVersion);
24305        } else {
24306            move = null;
24307        }
24308
24309        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
24310
24311        final Message msg = mHandler.obtainMessage(INIT_COPY);
24312        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
24313        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
24314                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
24315                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
24316                PackageManager.INSTALL_REASON_UNKNOWN);
24317        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
24318        msg.obj = params;
24319
24320        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
24321                System.identityHashCode(msg.obj));
24322        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
24323                System.identityHashCode(msg.obj));
24324
24325        mHandler.sendMessage(msg);
24326    }
24327
24328    @Override
24329    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
24330        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
24331
24332        final int realMoveId = mNextMoveId.getAndIncrement();
24333        final Bundle extras = new Bundle();
24334        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
24335        mMoveCallbacks.notifyCreated(realMoveId, extras);
24336
24337        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
24338            @Override
24339            public void onCreated(int moveId, Bundle extras) {
24340                // Ignored
24341            }
24342
24343            @Override
24344            public void onStatusChanged(int moveId, int status, long estMillis) {
24345                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
24346            }
24347        };
24348
24349        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24350        storage.setPrimaryStorageUuid(volumeUuid, callback);
24351        return realMoveId;
24352    }
24353
24354    @Override
24355    public int getMoveStatus(int moveId) {
24356        mContext.enforceCallingOrSelfPermission(
24357                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24358        return mMoveCallbacks.mLastStatus.get(moveId);
24359    }
24360
24361    @Override
24362    public void registerMoveCallback(IPackageMoveObserver callback) {
24363        mContext.enforceCallingOrSelfPermission(
24364                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24365        mMoveCallbacks.register(callback);
24366    }
24367
24368    @Override
24369    public void unregisterMoveCallback(IPackageMoveObserver callback) {
24370        mContext.enforceCallingOrSelfPermission(
24371                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24372        mMoveCallbacks.unregister(callback);
24373    }
24374
24375    @Override
24376    public boolean setInstallLocation(int loc) {
24377        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
24378                null);
24379        if (getInstallLocation() == loc) {
24380            return true;
24381        }
24382        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
24383                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
24384            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
24385                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
24386            return true;
24387        }
24388        return false;
24389   }
24390
24391    @Override
24392    public int getInstallLocation() {
24393        // allow instant app access
24394        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
24395                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
24396                PackageHelper.APP_INSTALL_AUTO);
24397    }
24398
24399    /** Called by UserManagerService */
24400    void cleanUpUser(UserManagerService userManager, int userHandle) {
24401        synchronized (mPackages) {
24402            mDirtyUsers.remove(userHandle);
24403            mUserNeedsBadging.delete(userHandle);
24404            mSettings.removeUserLPw(userHandle);
24405            mPendingBroadcasts.remove(userHandle);
24406            mInstantAppRegistry.onUserRemovedLPw(userHandle);
24407            removeUnusedPackagesLPw(userManager, userHandle);
24408        }
24409    }
24410
24411    /**
24412     * We're removing userHandle and would like to remove any downloaded packages
24413     * that are no longer in use by any other user.
24414     * @param userHandle the user being removed
24415     */
24416    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
24417        final boolean DEBUG_CLEAN_APKS = false;
24418        int [] users = userManager.getUserIds();
24419        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
24420        while (psit.hasNext()) {
24421            PackageSetting ps = psit.next();
24422            if (ps.pkg == null) {
24423                continue;
24424            }
24425            final String packageName = ps.pkg.packageName;
24426            // Skip over if system app
24427            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
24428                continue;
24429            }
24430            if (DEBUG_CLEAN_APKS) {
24431                Slog.i(TAG, "Checking package " + packageName);
24432            }
24433            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
24434            if (keep) {
24435                if (DEBUG_CLEAN_APKS) {
24436                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
24437                }
24438            } else {
24439                for (int i = 0; i < users.length; i++) {
24440                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
24441                        keep = true;
24442                        if (DEBUG_CLEAN_APKS) {
24443                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
24444                                    + users[i]);
24445                        }
24446                        break;
24447                    }
24448                }
24449            }
24450            if (!keep) {
24451                if (DEBUG_CLEAN_APKS) {
24452                    Slog.i(TAG, "  Removing package " + packageName);
24453                }
24454                mHandler.post(new Runnable() {
24455                    public void run() {
24456                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24457                                userHandle, 0);
24458                    } //end run
24459                });
24460            }
24461        }
24462    }
24463
24464    /** Called by UserManagerService */
24465    void createNewUser(int userId, String[] disallowedPackages) {
24466        synchronized (mInstallLock) {
24467            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
24468        }
24469        synchronized (mPackages) {
24470            scheduleWritePackageRestrictionsLocked(userId);
24471            scheduleWritePackageListLocked(userId);
24472            applyFactoryDefaultBrowserLPw(userId);
24473            primeDomainVerificationsLPw(userId);
24474        }
24475    }
24476
24477    void onNewUserCreated(final int userId) {
24478        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
24479        // If permission review for legacy apps is required, we represent
24480        // dagerous permissions for such apps as always granted runtime
24481        // permissions to keep per user flag state whether review is needed.
24482        // Hence, if a new user is added we have to propagate dangerous
24483        // permission grants for these legacy apps.
24484        if (mPermissionReviewRequired) {
24485            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
24486                    | UPDATE_PERMISSIONS_REPLACE_ALL);
24487        }
24488    }
24489
24490    @Override
24491    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
24492        mContext.enforceCallingOrSelfPermission(
24493                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
24494                "Only package verification agents can read the verifier device identity");
24495
24496        synchronized (mPackages) {
24497            return mSettings.getVerifierDeviceIdentityLPw();
24498        }
24499    }
24500
24501    @Override
24502    public void setPermissionEnforced(String permission, boolean enforced) {
24503        // TODO: Now that we no longer change GID for storage, this should to away.
24504        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
24505                "setPermissionEnforced");
24506        if (READ_EXTERNAL_STORAGE.equals(permission)) {
24507            synchronized (mPackages) {
24508                if (mSettings.mReadExternalStorageEnforced == null
24509                        || mSettings.mReadExternalStorageEnforced != enforced) {
24510                    mSettings.mReadExternalStorageEnforced = enforced;
24511                    mSettings.writeLPr();
24512                }
24513            }
24514            // kill any non-foreground processes so we restart them and
24515            // grant/revoke the GID.
24516            final IActivityManager am = ActivityManager.getService();
24517            if (am != null) {
24518                final long token = Binder.clearCallingIdentity();
24519                try {
24520                    am.killProcessesBelowForeground("setPermissionEnforcement");
24521                } catch (RemoteException e) {
24522                } finally {
24523                    Binder.restoreCallingIdentity(token);
24524                }
24525            }
24526        } else {
24527            throw new IllegalArgumentException("No selective enforcement for " + permission);
24528        }
24529    }
24530
24531    @Override
24532    @Deprecated
24533    public boolean isPermissionEnforced(String permission) {
24534        // allow instant applications
24535        return true;
24536    }
24537
24538    @Override
24539    public boolean isStorageLow() {
24540        // allow instant applications
24541        final long token = Binder.clearCallingIdentity();
24542        try {
24543            final DeviceStorageMonitorInternal
24544                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
24545            if (dsm != null) {
24546                return dsm.isMemoryLow();
24547            } else {
24548                return false;
24549            }
24550        } finally {
24551            Binder.restoreCallingIdentity(token);
24552        }
24553    }
24554
24555    @Override
24556    public IPackageInstaller getPackageInstaller() {
24557        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24558            return null;
24559        }
24560        return mInstallerService;
24561    }
24562
24563    private boolean userNeedsBadging(int userId) {
24564        int index = mUserNeedsBadging.indexOfKey(userId);
24565        if (index < 0) {
24566            final UserInfo userInfo;
24567            final long token = Binder.clearCallingIdentity();
24568            try {
24569                userInfo = sUserManager.getUserInfo(userId);
24570            } finally {
24571                Binder.restoreCallingIdentity(token);
24572            }
24573            final boolean b;
24574            if (userInfo != null && userInfo.isManagedProfile()) {
24575                b = true;
24576            } else {
24577                b = false;
24578            }
24579            mUserNeedsBadging.put(userId, b);
24580            return b;
24581        }
24582        return mUserNeedsBadging.valueAt(index);
24583    }
24584
24585    @Override
24586    public KeySet getKeySetByAlias(String packageName, String alias) {
24587        if (packageName == null || alias == null) {
24588            return null;
24589        }
24590        synchronized(mPackages) {
24591            final PackageParser.Package pkg = mPackages.get(packageName);
24592            if (pkg == null) {
24593                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24594                throw new IllegalArgumentException("Unknown package: " + packageName);
24595            }
24596            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24597            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24598                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24599                throw new IllegalArgumentException("Unknown package: " + packageName);
24600            }
24601            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24602            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24603        }
24604    }
24605
24606    @Override
24607    public KeySet getSigningKeySet(String packageName) {
24608        if (packageName == null) {
24609            return null;
24610        }
24611        synchronized(mPackages) {
24612            final int callingUid = Binder.getCallingUid();
24613            final int callingUserId = UserHandle.getUserId(callingUid);
24614            final PackageParser.Package pkg = mPackages.get(packageName);
24615            if (pkg == null) {
24616                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24617                throw new IllegalArgumentException("Unknown package: " + packageName);
24618            }
24619            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24620            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24621                // filter and pretend the package doesn't exist
24622                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24623                        + ", uid:" + callingUid);
24624                throw new IllegalArgumentException("Unknown package: " + packageName);
24625            }
24626            if (pkg.applicationInfo.uid != callingUid
24627                    && Process.SYSTEM_UID != callingUid) {
24628                throw new SecurityException("May not access signing KeySet of other apps.");
24629            }
24630            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24631            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24632        }
24633    }
24634
24635    @Override
24636    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
24637        final int callingUid = Binder.getCallingUid();
24638        if (getInstantAppPackageName(callingUid) != null) {
24639            return false;
24640        }
24641        if (packageName == null || ks == null) {
24642            return false;
24643        }
24644        synchronized(mPackages) {
24645            final PackageParser.Package pkg = mPackages.get(packageName);
24646            if (pkg == null
24647                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24648                            UserHandle.getUserId(callingUid))) {
24649                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24650                throw new IllegalArgumentException("Unknown package: " + packageName);
24651            }
24652            IBinder ksh = ks.getToken();
24653            if (ksh instanceof KeySetHandle) {
24654                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24655                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
24656            }
24657            return false;
24658        }
24659    }
24660
24661    @Override
24662    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
24663        final int callingUid = Binder.getCallingUid();
24664        if (getInstantAppPackageName(callingUid) != null) {
24665            return false;
24666        }
24667        if (packageName == null || ks == null) {
24668            return false;
24669        }
24670        synchronized(mPackages) {
24671            final PackageParser.Package pkg = mPackages.get(packageName);
24672            if (pkg == null
24673                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24674                            UserHandle.getUserId(callingUid))) {
24675                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24676                throw new IllegalArgumentException("Unknown package: " + packageName);
24677            }
24678            IBinder ksh = ks.getToken();
24679            if (ksh instanceof KeySetHandle) {
24680                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24681                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
24682            }
24683            return false;
24684        }
24685    }
24686
24687    private void deletePackageIfUnusedLPr(final String packageName) {
24688        PackageSetting ps = mSettings.mPackages.get(packageName);
24689        if (ps == null) {
24690            return;
24691        }
24692        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
24693            // TODO Implement atomic delete if package is unused
24694            // It is currently possible that the package will be deleted even if it is installed
24695            // after this method returns.
24696            mHandler.post(new Runnable() {
24697                public void run() {
24698                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24699                            0, PackageManager.DELETE_ALL_USERS);
24700                }
24701            });
24702        }
24703    }
24704
24705    /**
24706     * Check and throw if the given before/after packages would be considered a
24707     * downgrade.
24708     */
24709    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
24710            throws PackageManagerException {
24711        if (after.versionCode < before.mVersionCode) {
24712            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24713                    "Update version code " + after.versionCode + " is older than current "
24714                    + before.mVersionCode);
24715        } else if (after.versionCode == before.mVersionCode) {
24716            if (after.baseRevisionCode < before.baseRevisionCode) {
24717                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24718                        "Update base revision code " + after.baseRevisionCode
24719                        + " is older than current " + before.baseRevisionCode);
24720            }
24721
24722            if (!ArrayUtils.isEmpty(after.splitNames)) {
24723                for (int i = 0; i < after.splitNames.length; i++) {
24724                    final String splitName = after.splitNames[i];
24725                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
24726                    if (j != -1) {
24727                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
24728                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24729                                    "Update split " + splitName + " revision code "
24730                                    + after.splitRevisionCodes[i] + " is older than current "
24731                                    + before.splitRevisionCodes[j]);
24732                        }
24733                    }
24734                }
24735            }
24736        }
24737    }
24738
24739    private static class MoveCallbacks extends Handler {
24740        private static final int MSG_CREATED = 1;
24741        private static final int MSG_STATUS_CHANGED = 2;
24742
24743        private final RemoteCallbackList<IPackageMoveObserver>
24744                mCallbacks = new RemoteCallbackList<>();
24745
24746        private final SparseIntArray mLastStatus = new SparseIntArray();
24747
24748        public MoveCallbacks(Looper looper) {
24749            super(looper);
24750        }
24751
24752        public void register(IPackageMoveObserver callback) {
24753            mCallbacks.register(callback);
24754        }
24755
24756        public void unregister(IPackageMoveObserver callback) {
24757            mCallbacks.unregister(callback);
24758        }
24759
24760        @Override
24761        public void handleMessage(Message msg) {
24762            final SomeArgs args = (SomeArgs) msg.obj;
24763            final int n = mCallbacks.beginBroadcast();
24764            for (int i = 0; i < n; i++) {
24765                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
24766                try {
24767                    invokeCallback(callback, msg.what, args);
24768                } catch (RemoteException ignored) {
24769                }
24770            }
24771            mCallbacks.finishBroadcast();
24772            args.recycle();
24773        }
24774
24775        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
24776                throws RemoteException {
24777            switch (what) {
24778                case MSG_CREATED: {
24779                    callback.onCreated(args.argi1, (Bundle) args.arg2);
24780                    break;
24781                }
24782                case MSG_STATUS_CHANGED: {
24783                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
24784                    break;
24785                }
24786            }
24787        }
24788
24789        private void notifyCreated(int moveId, Bundle extras) {
24790            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
24791
24792            final SomeArgs args = SomeArgs.obtain();
24793            args.argi1 = moveId;
24794            args.arg2 = extras;
24795            obtainMessage(MSG_CREATED, args).sendToTarget();
24796        }
24797
24798        private void notifyStatusChanged(int moveId, int status) {
24799            notifyStatusChanged(moveId, status, -1);
24800        }
24801
24802        private void notifyStatusChanged(int moveId, int status, long estMillis) {
24803            Slog.v(TAG, "Move " + moveId + " status " + status);
24804
24805            final SomeArgs args = SomeArgs.obtain();
24806            args.argi1 = moveId;
24807            args.argi2 = status;
24808            args.arg3 = estMillis;
24809            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
24810
24811            synchronized (mLastStatus) {
24812                mLastStatus.put(moveId, status);
24813            }
24814        }
24815    }
24816
24817    private final static class OnPermissionChangeListeners extends Handler {
24818        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
24819
24820        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
24821                new RemoteCallbackList<>();
24822
24823        public OnPermissionChangeListeners(Looper looper) {
24824            super(looper);
24825        }
24826
24827        @Override
24828        public void handleMessage(Message msg) {
24829            switch (msg.what) {
24830                case MSG_ON_PERMISSIONS_CHANGED: {
24831                    final int uid = msg.arg1;
24832                    handleOnPermissionsChanged(uid);
24833                } break;
24834            }
24835        }
24836
24837        public void addListenerLocked(IOnPermissionsChangeListener listener) {
24838            mPermissionListeners.register(listener);
24839
24840        }
24841
24842        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
24843            mPermissionListeners.unregister(listener);
24844        }
24845
24846        public void onPermissionsChanged(int uid) {
24847            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
24848                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
24849            }
24850        }
24851
24852        private void handleOnPermissionsChanged(int uid) {
24853            final int count = mPermissionListeners.beginBroadcast();
24854            try {
24855                for (int i = 0; i < count; i++) {
24856                    IOnPermissionsChangeListener callback = mPermissionListeners
24857                            .getBroadcastItem(i);
24858                    try {
24859                        callback.onPermissionsChanged(uid);
24860                    } catch (RemoteException e) {
24861                        Log.e(TAG, "Permission listener is dead", e);
24862                    }
24863                }
24864            } finally {
24865                mPermissionListeners.finishBroadcast();
24866            }
24867        }
24868    }
24869
24870    private class PackageManagerNative extends IPackageManagerNative.Stub {
24871        @Override
24872        public String[] getNamesForUids(int[] uids) throws RemoteException {
24873            final String[] results = PackageManagerService.this.getNamesForUids(uids);
24874            // massage results so they can be parsed by the native binder
24875            for (int i = results.length - 1; i >= 0; --i) {
24876                if (results[i] == null) {
24877                    results[i] = "";
24878                }
24879            }
24880            return results;
24881        }
24882    }
24883
24884    private class PackageManagerInternalImpl extends PackageManagerInternal {
24885        @Override
24886        public void setLocationPackagesProvider(PackagesProvider provider) {
24887            synchronized (mPackages) {
24888                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
24889            }
24890        }
24891
24892        @Override
24893        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
24894            synchronized (mPackages) {
24895                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
24896            }
24897        }
24898
24899        @Override
24900        public void setSmsAppPackagesProvider(PackagesProvider provider) {
24901            synchronized (mPackages) {
24902                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
24903            }
24904        }
24905
24906        @Override
24907        public void setDialerAppPackagesProvider(PackagesProvider provider) {
24908            synchronized (mPackages) {
24909                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
24910            }
24911        }
24912
24913        @Override
24914        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
24915            synchronized (mPackages) {
24916                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
24917            }
24918        }
24919
24920        @Override
24921        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
24922            synchronized (mPackages) {
24923                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
24924            }
24925        }
24926
24927        @Override
24928        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
24929            synchronized (mPackages) {
24930                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
24931                        packageName, userId);
24932            }
24933        }
24934
24935        @Override
24936        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
24937            synchronized (mPackages) {
24938                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
24939                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
24940                        packageName, userId);
24941            }
24942        }
24943
24944        @Override
24945        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
24946            synchronized (mPackages) {
24947                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
24948                        packageName, userId);
24949            }
24950        }
24951
24952        @Override
24953        public void setKeepUninstalledPackages(final List<String> packageList) {
24954            Preconditions.checkNotNull(packageList);
24955            List<String> removedFromList = null;
24956            synchronized (mPackages) {
24957                if (mKeepUninstalledPackages != null) {
24958                    final int packagesCount = mKeepUninstalledPackages.size();
24959                    for (int i = 0; i < packagesCount; i++) {
24960                        String oldPackage = mKeepUninstalledPackages.get(i);
24961                        if (packageList != null && packageList.contains(oldPackage)) {
24962                            continue;
24963                        }
24964                        if (removedFromList == null) {
24965                            removedFromList = new ArrayList<>();
24966                        }
24967                        removedFromList.add(oldPackage);
24968                    }
24969                }
24970                mKeepUninstalledPackages = new ArrayList<>(packageList);
24971                if (removedFromList != null) {
24972                    final int removedCount = removedFromList.size();
24973                    for (int i = 0; i < removedCount; i++) {
24974                        deletePackageIfUnusedLPr(removedFromList.get(i));
24975                    }
24976                }
24977            }
24978        }
24979
24980        @Override
24981        public boolean isPermissionsReviewRequired(String packageName, int userId) {
24982            synchronized (mPackages) {
24983                // If we do not support permission review, done.
24984                if (!mPermissionReviewRequired) {
24985                    return false;
24986                }
24987
24988                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
24989                if (packageSetting == null) {
24990                    return false;
24991                }
24992
24993                // Permission review applies only to apps not supporting the new permission model.
24994                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
24995                    return false;
24996                }
24997
24998                // Legacy apps have the permission and get user consent on launch.
24999                PermissionsState permissionsState = packageSetting.getPermissionsState();
25000                return permissionsState.isPermissionReviewRequired(userId);
25001            }
25002        }
25003
25004        @Override
25005        public PackageInfo getPackageInfo(
25006                String packageName, int flags, int filterCallingUid, int userId) {
25007            return PackageManagerService.this
25008                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
25009                            flags, filterCallingUid, userId);
25010        }
25011
25012        @Override
25013        public ApplicationInfo getApplicationInfo(
25014                String packageName, int flags, int filterCallingUid, int userId) {
25015            return PackageManagerService.this
25016                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
25017        }
25018
25019        @Override
25020        public ActivityInfo getActivityInfo(
25021                ComponentName component, int flags, int filterCallingUid, int userId) {
25022            return PackageManagerService.this
25023                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
25024        }
25025
25026        @Override
25027        public List<ResolveInfo> queryIntentActivities(
25028                Intent intent, int flags, int filterCallingUid, int userId) {
25029            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
25030            return PackageManagerService.this
25031                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
25032                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
25033        }
25034
25035        @Override
25036        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
25037                int userId) {
25038            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
25039        }
25040
25041        @Override
25042        public void setDeviceAndProfileOwnerPackages(
25043                int deviceOwnerUserId, String deviceOwnerPackage,
25044                SparseArray<String> profileOwnerPackages) {
25045            mProtectedPackages.setDeviceAndProfileOwnerPackages(
25046                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
25047        }
25048
25049        @Override
25050        public boolean isPackageDataProtected(int userId, String packageName) {
25051            return mProtectedPackages.isPackageDataProtected(userId, packageName);
25052        }
25053
25054        @Override
25055        public boolean isPackageEphemeral(int userId, String packageName) {
25056            synchronized (mPackages) {
25057                final PackageSetting ps = mSettings.mPackages.get(packageName);
25058                return ps != null ? ps.getInstantApp(userId) : false;
25059            }
25060        }
25061
25062        @Override
25063        public boolean wasPackageEverLaunched(String packageName, int userId) {
25064            synchronized (mPackages) {
25065                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
25066            }
25067        }
25068
25069        @Override
25070        public void grantRuntimePermission(String packageName, String name, int userId,
25071                boolean overridePolicy) {
25072            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
25073                    overridePolicy);
25074        }
25075
25076        @Override
25077        public void revokeRuntimePermission(String packageName, String name, int userId,
25078                boolean overridePolicy) {
25079            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
25080                    overridePolicy);
25081        }
25082
25083        @Override
25084        public String getNameForUid(int uid) {
25085            return PackageManagerService.this.getNameForUid(uid);
25086        }
25087
25088        @Override
25089        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
25090                Intent origIntent, String resolvedType, String callingPackage,
25091                Bundle verificationBundle, int userId) {
25092            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
25093                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
25094                    userId);
25095        }
25096
25097        @Override
25098        public void grantEphemeralAccess(int userId, Intent intent,
25099                int targetAppId, int ephemeralAppId) {
25100            synchronized (mPackages) {
25101                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
25102                        targetAppId, ephemeralAppId);
25103            }
25104        }
25105
25106        @Override
25107        public boolean isInstantAppInstallerComponent(ComponentName component) {
25108            synchronized (mPackages) {
25109                return mInstantAppInstallerActivity != null
25110                        && mInstantAppInstallerActivity.getComponentName().equals(component);
25111            }
25112        }
25113
25114        @Override
25115        public void pruneInstantApps() {
25116            mInstantAppRegistry.pruneInstantApps();
25117        }
25118
25119        @Override
25120        public String getSetupWizardPackageName() {
25121            return mSetupWizardPackage;
25122        }
25123
25124        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
25125            if (policy != null) {
25126                mExternalSourcesPolicy = policy;
25127            }
25128        }
25129
25130        @Override
25131        public boolean isPackagePersistent(String packageName) {
25132            synchronized (mPackages) {
25133                PackageParser.Package pkg = mPackages.get(packageName);
25134                return pkg != null
25135                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
25136                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
25137                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
25138                        : false;
25139            }
25140        }
25141
25142        @Override
25143        public List<PackageInfo> getOverlayPackages(int userId) {
25144            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
25145            synchronized (mPackages) {
25146                for (PackageParser.Package p : mPackages.values()) {
25147                    if (p.mOverlayTarget != null) {
25148                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
25149                        if (pkg != null) {
25150                            overlayPackages.add(pkg);
25151                        }
25152                    }
25153                }
25154            }
25155            return overlayPackages;
25156        }
25157
25158        @Override
25159        public List<String> getTargetPackageNames(int userId) {
25160            List<String> targetPackages = new ArrayList<>();
25161            synchronized (mPackages) {
25162                for (PackageParser.Package p : mPackages.values()) {
25163                    if (p.mOverlayTarget == null) {
25164                        targetPackages.add(p.packageName);
25165                    }
25166                }
25167            }
25168            return targetPackages;
25169        }
25170
25171        @Override
25172        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
25173                @Nullable List<String> overlayPackageNames) {
25174            synchronized (mPackages) {
25175                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
25176                    Slog.e(TAG, "failed to find package " + targetPackageName);
25177                    return false;
25178                }
25179                ArrayList<String> overlayPaths = null;
25180                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
25181                    final int N = overlayPackageNames.size();
25182                    overlayPaths = new ArrayList<>(N);
25183                    for (int i = 0; i < N; i++) {
25184                        final String packageName = overlayPackageNames.get(i);
25185                        final PackageParser.Package pkg = mPackages.get(packageName);
25186                        if (pkg == null) {
25187                            Slog.e(TAG, "failed to find package " + packageName);
25188                            return false;
25189                        }
25190                        overlayPaths.add(pkg.baseCodePath);
25191                    }
25192                }
25193
25194                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
25195                ps.setOverlayPaths(overlayPaths, userId);
25196                return true;
25197            }
25198        }
25199
25200        @Override
25201        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
25202                int flags, int userId) {
25203            return resolveIntentInternal(
25204                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
25205        }
25206
25207        @Override
25208        public ResolveInfo resolveService(Intent intent, String resolvedType,
25209                int flags, int userId, int callingUid) {
25210            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
25211        }
25212
25213        @Override
25214        public void addIsolatedUid(int isolatedUid, int ownerUid) {
25215            synchronized (mPackages) {
25216                mIsolatedOwners.put(isolatedUid, ownerUid);
25217            }
25218        }
25219
25220        @Override
25221        public void removeIsolatedUid(int isolatedUid) {
25222            synchronized (mPackages) {
25223                mIsolatedOwners.delete(isolatedUid);
25224            }
25225        }
25226
25227        @Override
25228        public int getUidTargetSdkVersion(int uid) {
25229            synchronized (mPackages) {
25230                return getUidTargetSdkVersionLockedLPr(uid);
25231            }
25232        }
25233
25234        @Override
25235        public boolean canAccessInstantApps(int callingUid, int userId) {
25236            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
25237        }
25238    }
25239
25240    @Override
25241    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
25242        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
25243        synchronized (mPackages) {
25244            final long identity = Binder.clearCallingIdentity();
25245            try {
25246                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
25247                        packageNames, userId);
25248            } finally {
25249                Binder.restoreCallingIdentity(identity);
25250            }
25251        }
25252    }
25253
25254    @Override
25255    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
25256        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
25257        synchronized (mPackages) {
25258            final long identity = Binder.clearCallingIdentity();
25259            try {
25260                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
25261                        packageNames, userId);
25262            } finally {
25263                Binder.restoreCallingIdentity(identity);
25264            }
25265        }
25266    }
25267
25268    private static void enforceSystemOrPhoneCaller(String tag) {
25269        int callingUid = Binder.getCallingUid();
25270        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
25271            throw new SecurityException(
25272                    "Cannot call " + tag + " from UID " + callingUid);
25273        }
25274    }
25275
25276    boolean isHistoricalPackageUsageAvailable() {
25277        return mPackageUsage.isHistoricalPackageUsageAvailable();
25278    }
25279
25280    /**
25281     * Return a <b>copy</b> of the collection of packages known to the package manager.
25282     * @return A copy of the values of mPackages.
25283     */
25284    Collection<PackageParser.Package> getPackages() {
25285        synchronized (mPackages) {
25286            return new ArrayList<>(mPackages.values());
25287        }
25288    }
25289
25290    /**
25291     * Logs process start information (including base APK hash) to the security log.
25292     * @hide
25293     */
25294    @Override
25295    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
25296            String apkFile, int pid) {
25297        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25298            return;
25299        }
25300        if (!SecurityLog.isLoggingEnabled()) {
25301            return;
25302        }
25303        Bundle data = new Bundle();
25304        data.putLong("startTimestamp", System.currentTimeMillis());
25305        data.putString("processName", processName);
25306        data.putInt("uid", uid);
25307        data.putString("seinfo", seinfo);
25308        data.putString("apkFile", apkFile);
25309        data.putInt("pid", pid);
25310        Message msg = mProcessLoggingHandler.obtainMessage(
25311                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
25312        msg.setData(data);
25313        mProcessLoggingHandler.sendMessage(msg);
25314    }
25315
25316    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
25317        return mCompilerStats.getPackageStats(pkgName);
25318    }
25319
25320    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
25321        return getOrCreateCompilerPackageStats(pkg.packageName);
25322    }
25323
25324    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
25325        return mCompilerStats.getOrCreatePackageStats(pkgName);
25326    }
25327
25328    public void deleteCompilerPackageStats(String pkgName) {
25329        mCompilerStats.deletePackageStats(pkgName);
25330    }
25331
25332    @Override
25333    public int getInstallReason(String packageName, int userId) {
25334        final int callingUid = Binder.getCallingUid();
25335        enforceCrossUserPermission(callingUid, userId,
25336                true /* requireFullPermission */, false /* checkShell */,
25337                "get install reason");
25338        synchronized (mPackages) {
25339            final PackageSetting ps = mSettings.mPackages.get(packageName);
25340            if (filterAppAccessLPr(ps, callingUid, userId)) {
25341                return PackageManager.INSTALL_REASON_UNKNOWN;
25342            }
25343            if (ps != null) {
25344                return ps.getInstallReason(userId);
25345            }
25346        }
25347        return PackageManager.INSTALL_REASON_UNKNOWN;
25348    }
25349
25350    @Override
25351    public boolean canRequestPackageInstalls(String packageName, int userId) {
25352        return canRequestPackageInstallsInternal(packageName, 0, userId,
25353                true /* throwIfPermNotDeclared*/);
25354    }
25355
25356    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
25357            boolean throwIfPermNotDeclared) {
25358        int callingUid = Binder.getCallingUid();
25359        int uid = getPackageUid(packageName, 0, userId);
25360        if (callingUid != uid && callingUid != Process.ROOT_UID
25361                && callingUid != Process.SYSTEM_UID) {
25362            throw new SecurityException(
25363                    "Caller uid " + callingUid + " does not own package " + packageName);
25364        }
25365        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
25366        if (info == null) {
25367            return false;
25368        }
25369        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
25370            return false;
25371        }
25372        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
25373        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
25374        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
25375            if (throwIfPermNotDeclared) {
25376                throw new SecurityException("Need to declare " + appOpPermission
25377                        + " to call this api");
25378            } else {
25379                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
25380                return false;
25381            }
25382        }
25383        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
25384            return false;
25385        }
25386        if (mExternalSourcesPolicy != null) {
25387            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
25388            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
25389                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
25390            }
25391        }
25392        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
25393    }
25394
25395    @Override
25396    public ComponentName getInstantAppResolverSettingsComponent() {
25397        return mInstantAppResolverSettingsComponent;
25398    }
25399
25400    @Override
25401    public ComponentName getInstantAppInstallerComponent() {
25402        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25403            return null;
25404        }
25405        return mInstantAppInstallerActivity == null
25406                ? null : mInstantAppInstallerActivity.getComponentName();
25407    }
25408
25409    @Override
25410    public String getInstantAppAndroidId(String packageName, int userId) {
25411        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
25412                "getInstantAppAndroidId");
25413        enforceCrossUserPermission(Binder.getCallingUid(), userId,
25414                true /* requireFullPermission */, false /* checkShell */,
25415                "getInstantAppAndroidId");
25416        // Make sure the target is an Instant App.
25417        if (!isInstantApp(packageName, userId)) {
25418            return null;
25419        }
25420        synchronized (mPackages) {
25421            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
25422        }
25423    }
25424
25425    boolean canHaveOatDir(String packageName) {
25426        synchronized (mPackages) {
25427            PackageParser.Package p = mPackages.get(packageName);
25428            if (p == null) {
25429                return false;
25430            }
25431            return p.canHaveOatDir();
25432        }
25433    }
25434
25435    private String getOatDir(PackageParser.Package pkg) {
25436        if (!pkg.canHaveOatDir()) {
25437            return null;
25438        }
25439        File codePath = new File(pkg.codePath);
25440        if (codePath.isDirectory()) {
25441            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
25442        }
25443        return null;
25444    }
25445
25446    void deleteOatArtifactsOfPackage(String packageName) {
25447        final String[] instructionSets;
25448        final List<String> codePaths;
25449        final String oatDir;
25450        final PackageParser.Package pkg;
25451        synchronized (mPackages) {
25452            pkg = mPackages.get(packageName);
25453        }
25454        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
25455        codePaths = pkg.getAllCodePaths();
25456        oatDir = getOatDir(pkg);
25457
25458        for (String codePath : codePaths) {
25459            for (String isa : instructionSets) {
25460                try {
25461                    mInstaller.deleteOdex(codePath, isa, oatDir);
25462                } catch (InstallerException e) {
25463                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
25464                }
25465            }
25466        }
25467    }
25468
25469    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
25470        Set<String> unusedPackages = new HashSet<>();
25471        long currentTimeInMillis = System.currentTimeMillis();
25472        synchronized (mPackages) {
25473            for (PackageParser.Package pkg : mPackages.values()) {
25474                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
25475                if (ps == null) {
25476                    continue;
25477                }
25478                PackageDexUsage.PackageUseInfo packageUseInfo =
25479                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
25480                if (PackageManagerServiceUtils
25481                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
25482                                downgradeTimeThresholdMillis, packageUseInfo,
25483                                pkg.getLatestPackageUseTimeInMills(),
25484                                pkg.getLatestForegroundPackageUseTimeInMills())) {
25485                    unusedPackages.add(pkg.packageName);
25486                }
25487            }
25488        }
25489        return unusedPackages;
25490    }
25491}
25492
25493interface PackageSender {
25494    void sendPackageBroadcast(final String action, final String pkg,
25495        final Bundle extras, final int flags, final String targetPkg,
25496        final IIntentReceiver finishedReceiver, final int[] userIds);
25497    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
25498        boolean includeStopped, int appId, int... userIds);
25499}
25500