PackageManagerService.java revision 695c8ac7f030d1ad8fd6a4622aa064ff9ac8b46e
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_OEM;
86import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
87import static android.content.pm.PackageParser.isApkFile;
88import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
89import static android.os.storage.StorageManager.FLAG_STORAGE_CE;
90import static android.os.storage.StorageManager.FLAG_STORAGE_DE;
91import static android.system.OsConstants.O_CREAT;
92import static android.system.OsConstants.O_RDWR;
93
94import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
95import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
96import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
97import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
98import static com.android.internal.util.ArrayUtils.appendInt;
99import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
100import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
101import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
102import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
103import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
104import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
105import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
106import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
107import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
108import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
109
110import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
111
112import android.Manifest;
113import android.annotation.IntDef;
114import android.annotation.NonNull;
115import android.annotation.Nullable;
116import android.app.ActivityManager;
117import android.app.AppOpsManager;
118import android.app.IActivityManager;
119import android.app.ResourcesManager;
120import android.app.admin.IDevicePolicyManager;
121import android.app.admin.SecurityLog;
122import android.app.backup.IBackupManager;
123import android.content.BroadcastReceiver;
124import android.content.ComponentName;
125import android.content.ContentResolver;
126import android.content.Context;
127import android.content.IIntentReceiver;
128import android.content.Intent;
129import android.content.IntentFilter;
130import android.content.IntentSender;
131import android.content.IntentSender.SendIntentException;
132import android.content.ServiceConnection;
133import android.content.pm.ActivityInfo;
134import android.content.pm.ApplicationInfo;
135import android.content.pm.AppsQueryHelper;
136import android.content.pm.AuxiliaryResolveInfo;
137import android.content.pm.ChangedPackages;
138import android.content.pm.ComponentInfo;
139import android.content.pm.FallbackCategoryProvider;
140import android.content.pm.FeatureInfo;
141import android.content.pm.IDexModuleRegisterCallback;
142import android.content.pm.IOnPermissionsChangeListener;
143import android.content.pm.IPackageDataObserver;
144import android.content.pm.IPackageDeleteObserver;
145import android.content.pm.IPackageDeleteObserver2;
146import android.content.pm.IPackageInstallObserver2;
147import android.content.pm.IPackageInstaller;
148import android.content.pm.IPackageManager;
149import android.content.pm.IPackageManagerNative;
150import android.content.pm.IPackageMoveObserver;
151import android.content.pm.IPackageStatsObserver;
152import android.content.pm.InstantAppInfo;
153import android.content.pm.InstantAppRequest;
154import android.content.pm.InstantAppResolveInfo;
155import android.content.pm.InstrumentationInfo;
156import android.content.pm.IntentFilterVerificationInfo;
157import android.content.pm.KeySet;
158import android.content.pm.PackageCleanItem;
159import android.content.pm.PackageInfo;
160import android.content.pm.PackageInfoLite;
161import android.content.pm.PackageInstaller;
162import android.content.pm.PackageManager;
163import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
164import android.content.pm.PackageManagerInternal;
165import android.content.pm.PackageParser;
166import android.content.pm.PackageParser.ActivityIntentInfo;
167import android.content.pm.PackageParser.PackageLite;
168import android.content.pm.PackageParser.PackageParserException;
169import android.content.pm.PackageStats;
170import android.content.pm.PackageUserState;
171import android.content.pm.ParceledListSlice;
172import android.content.pm.PermissionGroupInfo;
173import android.content.pm.PermissionInfo;
174import android.content.pm.ProviderInfo;
175import android.content.pm.ResolveInfo;
176import android.content.pm.ServiceInfo;
177import android.content.pm.SharedLibraryInfo;
178import android.content.pm.Signature;
179import android.content.pm.UserInfo;
180import android.content.pm.VerifierDeviceIdentity;
181import android.content.pm.VerifierInfo;
182import android.content.pm.VersionedPackage;
183import android.content.res.Resources;
184import android.database.ContentObserver;
185import android.graphics.Bitmap;
186import android.hardware.display.DisplayManager;
187import android.net.Uri;
188import android.os.Binder;
189import android.os.Build;
190import android.os.Bundle;
191import android.os.Debug;
192import android.os.Environment;
193import android.os.Environment.UserEnvironment;
194import android.os.FileUtils;
195import android.os.Handler;
196import android.os.IBinder;
197import android.os.Looper;
198import android.os.Message;
199import android.os.Parcel;
200import android.os.ParcelFileDescriptor;
201import android.os.PatternMatcher;
202import android.os.Process;
203import android.os.RemoteCallbackList;
204import android.os.RemoteException;
205import android.os.ResultReceiver;
206import android.os.SELinux;
207import android.os.ServiceManager;
208import android.os.ShellCallback;
209import android.os.SystemClock;
210import android.os.SystemProperties;
211import android.os.Trace;
212import android.os.UserHandle;
213import android.os.UserManager;
214import android.os.UserManagerInternal;
215import android.os.storage.IStorageManager;
216import android.os.storage.StorageEventListener;
217import android.os.storage.StorageManager;
218import android.os.storage.StorageManagerInternal;
219import android.os.storage.VolumeInfo;
220import android.os.storage.VolumeRecord;
221import android.provider.Settings.Global;
222import android.provider.Settings.Secure;
223import android.security.KeyStore;
224import android.security.SystemKeyStore;
225import android.service.pm.PackageServiceDumpProto;
226import android.system.ErrnoException;
227import android.system.Os;
228import android.text.TextUtils;
229import android.text.format.DateUtils;
230import android.util.ArrayMap;
231import android.util.ArraySet;
232import android.util.Base64;
233import android.util.TimingsTraceLog;
234import android.util.DisplayMetrics;
235import android.util.EventLog;
236import android.util.ExceptionUtils;
237import android.util.Log;
238import android.util.LogPrinter;
239import android.util.MathUtils;
240import android.util.PackageUtils;
241import android.util.Pair;
242import android.util.PrintStreamPrinter;
243import android.util.Slog;
244import android.util.SparseArray;
245import android.util.SparseBooleanArray;
246import android.util.SparseIntArray;
247import android.util.Xml;
248import android.util.jar.StrictJarFile;
249import android.util.proto.ProtoOutputStream;
250import android.view.Display;
251
252import com.android.internal.R;
253import com.android.internal.annotations.GuardedBy;
254import com.android.internal.app.IMediaContainerService;
255import com.android.internal.app.ResolverActivity;
256import com.android.internal.content.NativeLibraryHelper;
257import com.android.internal.content.PackageHelper;
258import com.android.internal.logging.MetricsLogger;
259import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
260import com.android.internal.os.IParcelFileDescriptorFactory;
261import com.android.internal.os.RoSystemProperties;
262import com.android.internal.os.SomeArgs;
263import com.android.internal.os.Zygote;
264import com.android.internal.telephony.CarrierAppUtils;
265import com.android.internal.util.ArrayUtils;
266import com.android.internal.util.ConcurrentUtils;
267import com.android.internal.util.DumpUtils;
268import com.android.internal.util.FastPrintWriter;
269import com.android.internal.util.FastXmlSerializer;
270import com.android.internal.util.IndentingPrintWriter;
271import com.android.internal.util.Preconditions;
272import com.android.internal.util.XmlUtils;
273import com.android.server.AttributeCache;
274import com.android.server.DeviceIdleController;
275import com.android.server.EventLogTags;
276import com.android.server.FgThread;
277import com.android.server.IntentResolver;
278import com.android.server.LocalServices;
279import com.android.server.LockGuard;
280import com.android.server.ServiceThread;
281import com.android.server.SystemConfig;
282import com.android.server.SystemServerInitThreadPool;
283import com.android.server.Watchdog;
284import com.android.server.net.NetworkPolicyManagerInternal;
285import com.android.server.pm.Installer.InstallerException;
286import com.android.server.pm.PermissionsState.PermissionState;
287import com.android.server.pm.Settings.DatabaseVersion;
288import com.android.server.pm.Settings.VersionInfo;
289import com.android.server.pm.dex.DexManager;
290import com.android.server.pm.dex.DexoptOptions;
291import com.android.server.pm.dex.PackageDexUsage;
292import com.android.server.storage.DeviceStorageMonitorInternal;
293
294import dalvik.system.CloseGuard;
295import dalvik.system.DexFile;
296import dalvik.system.VMRuntime;
297
298import libcore.io.IoUtils;
299import libcore.io.Streams;
300import libcore.util.EmptyArray;
301
302import org.xmlpull.v1.XmlPullParser;
303import org.xmlpull.v1.XmlPullParserException;
304import org.xmlpull.v1.XmlSerializer;
305
306import java.io.BufferedOutputStream;
307import java.io.BufferedReader;
308import java.io.ByteArrayInputStream;
309import java.io.ByteArrayOutputStream;
310import java.io.File;
311import java.io.FileDescriptor;
312import java.io.FileInputStream;
313import java.io.FileOutputStream;
314import java.io.FileReader;
315import java.io.FilenameFilter;
316import java.io.IOException;
317import java.io.InputStream;
318import java.io.OutputStream;
319import java.io.PrintWriter;
320import java.lang.annotation.Retention;
321import java.lang.annotation.RetentionPolicy;
322import java.nio.charset.StandardCharsets;
323import java.security.DigestInputStream;
324import java.security.MessageDigest;
325import java.security.NoSuchAlgorithmException;
326import java.security.PublicKey;
327import java.security.SecureRandom;
328import java.security.cert.Certificate;
329import java.security.cert.CertificateEncodingException;
330import java.security.cert.CertificateException;
331import java.text.SimpleDateFormat;
332import java.util.ArrayList;
333import java.util.Arrays;
334import java.util.Collection;
335import java.util.Collections;
336import java.util.Comparator;
337import java.util.Date;
338import java.util.HashMap;
339import java.util.HashSet;
340import java.util.Iterator;
341import java.util.List;
342import java.util.Map;
343import java.util.Objects;
344import java.util.Set;
345import java.util.concurrent.CountDownLatch;
346import java.util.concurrent.Future;
347import java.util.concurrent.TimeUnit;
348import java.util.concurrent.atomic.AtomicBoolean;
349import java.util.concurrent.atomic.AtomicInteger;
350import java.util.zip.GZIPInputStream;
351
352/**
353 * Keep track of all those APKs everywhere.
354 * <p>
355 * Internally there are two important locks:
356 * <ul>
357 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
358 * and other related state. It is a fine-grained lock that should only be held
359 * momentarily, as it's one of the most contended locks in the system.
360 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
361 * operations typically involve heavy lifting of application data on disk. Since
362 * {@code installd} is single-threaded, and it's operations can often be slow,
363 * this lock should never be acquired while already holding {@link #mPackages}.
364 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
365 * holding {@link #mInstallLock}.
366 * </ul>
367 * Many internal methods rely on the caller to hold the appropriate locks, and
368 * this contract is expressed through method name suffixes:
369 * <ul>
370 * <li>fooLI(): the caller must hold {@link #mInstallLock}
371 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
372 * being modified must be frozen
373 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
374 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
375 * </ul>
376 * <p>
377 * Because this class is very central to the platform's security; please run all
378 * CTS and unit tests whenever making modifications:
379 *
380 * <pre>
381 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
382 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
383 * </pre>
384 */
385public class PackageManagerService extends IPackageManager.Stub
386        implements PackageSender {
387    static final String TAG = "PackageManager";
388    static final boolean DEBUG_SETTINGS = false;
389    static final boolean DEBUG_PREFERRED = false;
390    static final boolean DEBUG_UPGRADE = false;
391    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
392    private static final boolean DEBUG_BACKUP = false;
393    private static final boolean DEBUG_INSTALL = false;
394    private static final boolean DEBUG_REMOVE = false;
395    private static final boolean DEBUG_BROADCASTS = false;
396    private static final boolean DEBUG_SHOW_INFO = false;
397    private static final boolean DEBUG_PACKAGE_INFO = false;
398    private static final boolean DEBUG_INTENT_MATCHING = false;
399    private static final boolean DEBUG_PACKAGE_SCANNING = false;
400    private static final boolean DEBUG_VERIFY = false;
401    private static final boolean DEBUG_FILTERS = false;
402    private static final boolean DEBUG_PERMISSIONS = false;
403    private static final boolean DEBUG_SHARED_LIBRARIES = false;
404    private static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
405
406    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
407    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
408    // user, but by default initialize to this.
409    public static final boolean DEBUG_DEXOPT = false;
410
411    private static final boolean DEBUG_ABI_SELECTION = false;
412    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
413    private static final boolean DEBUG_TRIAGED_MISSING = false;
414    private static final boolean DEBUG_APP_DATA = false;
415
416    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
417    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
418
419    private static final boolean HIDE_EPHEMERAL_APIS = false;
420
421    private static final boolean ENABLE_FREE_CACHE_V2 =
422            SystemProperties.getBoolean("fw.free_cache_v2", true);
423
424    private static final int RADIO_UID = Process.PHONE_UID;
425    private static final int LOG_UID = Process.LOG_UID;
426    private static final int NFC_UID = Process.NFC_UID;
427    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
428    private static final int SHELL_UID = Process.SHELL_UID;
429
430    // Cap the size of permission trees that 3rd party apps can define
431    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
432
433    // Suffix used during package installation when copying/moving
434    // package apks to install directory.
435    private static final String INSTALL_PACKAGE_SUFFIX = "-";
436
437    static final int SCAN_NO_DEX = 1<<1;
438    static final int SCAN_FORCE_DEX = 1<<2;
439    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
440    static final int SCAN_NEW_INSTALL = 1<<4;
441    static final int SCAN_UPDATE_TIME = 1<<5;
442    static final int SCAN_BOOTING = 1<<6;
443    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
444    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
445    static final int SCAN_REPLACING = 1<<9;
446    static final int SCAN_REQUIRE_KNOWN = 1<<10;
447    static final int SCAN_MOVE = 1<<11;
448    static final int SCAN_INITIAL = 1<<12;
449    static final int SCAN_CHECK_ONLY = 1<<13;
450    static final int SCAN_DONT_KILL_APP = 1<<14;
451    static final int SCAN_IGNORE_FROZEN = 1<<15;
452    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
453    static final int SCAN_AS_INSTANT_APP = 1<<17;
454    static final int SCAN_AS_FULL_APP = 1<<18;
455    static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<19;
456    /** Should not be with the scan flags */
457    static final int FLAGS_REMOVE_CHATTY = 1<<31;
458
459    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
460    /** Extension of the compressed packages */
461    private final static String COMPRESSED_EXTENSION = ".gz";
462    /** Suffix of stub packages on the system partition */
463    private final static String STUB_SUFFIX = "-Stub";
464
465    private static final int[] EMPTY_INT_ARRAY = new int[0];
466
467    private static final int TYPE_UNKNOWN = 0;
468    private static final int TYPE_ACTIVITY = 1;
469    private static final int TYPE_RECEIVER = 2;
470    private static final int TYPE_SERVICE = 3;
471    private static final int TYPE_PROVIDER = 4;
472    @IntDef(prefix = { "TYPE_" }, value = {
473            TYPE_UNKNOWN,
474            TYPE_ACTIVITY,
475            TYPE_RECEIVER,
476            TYPE_SERVICE,
477            TYPE_PROVIDER,
478    })
479    @Retention(RetentionPolicy.SOURCE)
480    public @interface ComponentType {}
481
482    /**
483     * Timeout (in milliseconds) after which the watchdog should declare that
484     * our handler thread is wedged.  The usual default for such things is one
485     * minute but we sometimes do very lengthy I/O operations on this thread,
486     * such as installing multi-gigabyte applications, so ours needs to be longer.
487     */
488    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
489
490    /**
491     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
492     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
493     * settings entry if available, otherwise we use the hardcoded default.  If it's been
494     * more than this long since the last fstrim, we force one during the boot sequence.
495     *
496     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
497     * one gets run at the next available charging+idle time.  This final mandatory
498     * no-fstrim check kicks in only of the other scheduling criteria is never met.
499     */
500    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
501
502    /**
503     * Whether verification is enabled by default.
504     */
505    private static final boolean DEFAULT_VERIFY_ENABLE = true;
506
507    /**
508     * The default maximum time to wait for the verification agent to return in
509     * milliseconds.
510     */
511    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
512
513    /**
514     * The default response for package verification timeout.
515     *
516     * This can be either PackageManager.VERIFICATION_ALLOW or
517     * PackageManager.VERIFICATION_REJECT.
518     */
519    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
520
521    static final String PLATFORM_PACKAGE_NAME = "android";
522
523    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
524
525    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
526            DEFAULT_CONTAINER_PACKAGE,
527            "com.android.defcontainer.DefaultContainerService");
528
529    private static final String KILL_APP_REASON_GIDS_CHANGED =
530            "permission grant or revoke changed gids";
531
532    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
533            "permissions revoked";
534
535    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
536
537    private static final String PACKAGE_SCHEME = "package";
538
539    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
540
541    /** Permission grant: not grant the permission. */
542    private static final int GRANT_DENIED = 1;
543
544    /** Permission grant: grant the permission as an install permission. */
545    private static final int GRANT_INSTALL = 2;
546
547    /** Permission grant: grant the permission as a runtime one. */
548    private static final int GRANT_RUNTIME = 3;
549
550    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
551    private static final int GRANT_UPGRADE = 4;
552
553    /** Canonical intent used to identify what counts as a "web browser" app */
554    private static final Intent sBrowserIntent;
555    static {
556        sBrowserIntent = new Intent();
557        sBrowserIntent.setAction(Intent.ACTION_VIEW);
558        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
559        sBrowserIntent.setData(Uri.parse("http:"));
560    }
561
562    /**
563     * The set of all protected actions [i.e. those actions for which a high priority
564     * intent filter is disallowed].
565     */
566    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
567    static {
568        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
569        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
570        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
571        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
572    }
573
574    // Compilation reasons.
575    public static final int REASON_FIRST_BOOT = 0;
576    public static final int REASON_BOOT = 1;
577    public static final int REASON_INSTALL = 2;
578    public static final int REASON_BACKGROUND_DEXOPT = 3;
579    public static final int REASON_AB_OTA = 4;
580    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
581    public static final int REASON_SHARED = 6;
582
583    public static final int REASON_LAST = REASON_SHARED;
584
585    /** All dangerous permission names in the same order as the events in MetricsEvent */
586    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
587            Manifest.permission.READ_CALENDAR,
588            Manifest.permission.WRITE_CALENDAR,
589            Manifest.permission.CAMERA,
590            Manifest.permission.READ_CONTACTS,
591            Manifest.permission.WRITE_CONTACTS,
592            Manifest.permission.GET_ACCOUNTS,
593            Manifest.permission.ACCESS_FINE_LOCATION,
594            Manifest.permission.ACCESS_COARSE_LOCATION,
595            Manifest.permission.RECORD_AUDIO,
596            Manifest.permission.READ_PHONE_STATE,
597            Manifest.permission.CALL_PHONE,
598            Manifest.permission.READ_CALL_LOG,
599            Manifest.permission.WRITE_CALL_LOG,
600            Manifest.permission.ADD_VOICEMAIL,
601            Manifest.permission.USE_SIP,
602            Manifest.permission.PROCESS_OUTGOING_CALLS,
603            Manifest.permission.READ_CELL_BROADCASTS,
604            Manifest.permission.BODY_SENSORS,
605            Manifest.permission.SEND_SMS,
606            Manifest.permission.RECEIVE_SMS,
607            Manifest.permission.READ_SMS,
608            Manifest.permission.RECEIVE_WAP_PUSH,
609            Manifest.permission.RECEIVE_MMS,
610            Manifest.permission.READ_EXTERNAL_STORAGE,
611            Manifest.permission.WRITE_EXTERNAL_STORAGE,
612            Manifest.permission.READ_PHONE_NUMBERS,
613            Manifest.permission.ANSWER_PHONE_CALLS);
614
615
616    /**
617     * Version number for the package parser cache. Increment this whenever the format or
618     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
619     */
620    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
621
622    /**
623     * Whether the package parser cache is enabled.
624     */
625    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
626
627    final ServiceThread mHandlerThread;
628
629    final PackageHandler mHandler;
630
631    private final ProcessLoggingHandler mProcessLoggingHandler;
632
633    /**
634     * Messages for {@link #mHandler} that need to wait for system ready before
635     * being dispatched.
636     */
637    private ArrayList<Message> mPostSystemReadyMessages;
638
639    final int mSdkVersion = Build.VERSION.SDK_INT;
640
641    final Context mContext;
642    final boolean mFactoryTest;
643    final boolean mOnlyCore;
644    final DisplayMetrics mMetrics;
645    final int mDefParseFlags;
646    final String[] mSeparateProcesses;
647    final boolean mIsUpgrade;
648    final boolean mIsPreNUpgrade;
649    final boolean mIsPreNMR1Upgrade;
650
651    // Have we told the Activity Manager to whitelist the default container service by uid yet?
652    @GuardedBy("mPackages")
653    boolean mDefaultContainerWhitelisted = false;
654
655    @GuardedBy("mPackages")
656    private boolean mDexOptDialogShown;
657
658    /** The location for ASEC container files on internal storage. */
659    final String mAsecInternalPath;
660
661    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
662    // LOCK HELD.  Can be called with mInstallLock held.
663    @GuardedBy("mInstallLock")
664    final Installer mInstaller;
665
666    /** Directory where installed third-party apps stored */
667    final File mAppInstallDir;
668
669    /**
670     * Directory to which applications installed internally have their
671     * 32 bit native libraries copied.
672     */
673    private File mAppLib32InstallDir;
674
675    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
676    // apps.
677    final File mDrmAppPrivateInstallDir;
678
679    // ----------------------------------------------------------------
680
681    // Lock for state used when installing and doing other long running
682    // operations.  Methods that must be called with this lock held have
683    // the suffix "LI".
684    final Object mInstallLock = new Object();
685
686    // ----------------------------------------------------------------
687
688    // Keys are String (package name), values are Package.  This also serves
689    // as the lock for the global state.  Methods that must be called with
690    // this lock held have the prefix "LP".
691    @GuardedBy("mPackages")
692    final ArrayMap<String, PackageParser.Package> mPackages =
693            new ArrayMap<String, PackageParser.Package>();
694
695    final ArrayMap<String, Set<String>> mKnownCodebase =
696            new ArrayMap<String, Set<String>>();
697
698    // Keys are isolated uids and values are the uid of the application
699    // that created the isolated proccess.
700    @GuardedBy("mPackages")
701    final SparseIntArray mIsolatedOwners = new SparseIntArray();
702
703    /**
704     * Tracks new system packages [received in an OTA] that we expect to
705     * find updated user-installed versions. Keys are package name, values
706     * are package location.
707     */
708    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
709    /**
710     * Tracks high priority intent filters for protected actions. During boot, certain
711     * filter actions are protected and should never be allowed to have a high priority
712     * intent filter for them. However, there is one, and only one exception -- the
713     * setup wizard. It must be able to define a high priority intent filter for these
714     * actions to ensure there are no escapes from the wizard. We need to delay processing
715     * of these during boot as we need to look at all of the system packages in order
716     * to know which component is the setup wizard.
717     */
718    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
719    /**
720     * Whether or not processing protected filters should be deferred.
721     */
722    private boolean mDeferProtectedFilters = true;
723
724    /**
725     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
726     */
727    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
728    /**
729     * Whether or not system app permissions should be promoted from install to runtime.
730     */
731    boolean mPromoteSystemApps;
732
733    @GuardedBy("mPackages")
734    final Settings mSettings;
735
736    /**
737     * Set of package names that are currently "frozen", which means active
738     * surgery is being done on the code/data for that package. The platform
739     * will refuse to launch frozen packages to avoid race conditions.
740     *
741     * @see PackageFreezer
742     */
743    @GuardedBy("mPackages")
744    final ArraySet<String> mFrozenPackages = new ArraySet<>();
745
746    final ProtectedPackages mProtectedPackages;
747
748    @GuardedBy("mLoadedVolumes")
749    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
750
751    boolean mFirstBoot;
752
753    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
754
755    // System configuration read by SystemConfig.
756    final int[] mGlobalGids;
757    final SparseArray<ArraySet<String>> mSystemPermissions;
758    @GuardedBy("mAvailableFeatures")
759    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
760
761    // If mac_permissions.xml was found for seinfo labeling.
762    boolean mFoundPolicyFile;
763
764    private final InstantAppRegistry mInstantAppRegistry;
765
766    @GuardedBy("mPackages")
767    int mChangedPackagesSequenceNumber;
768    /**
769     * List of changed [installed, removed or updated] packages.
770     * mapping from user id -> sequence number -> package name
771     */
772    @GuardedBy("mPackages")
773    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
774    /**
775     * The sequence number of the last change to a package.
776     * mapping from user id -> package name -> sequence number
777     */
778    @GuardedBy("mPackages")
779    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
780
781    class PackageParserCallback implements PackageParser.Callback {
782        @Override public final boolean hasFeature(String feature) {
783            return PackageManagerService.this.hasSystemFeature(feature, 0);
784        }
785
786        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
787                Collection<PackageParser.Package> allPackages, String targetPackageName) {
788            List<PackageParser.Package> overlayPackages = null;
789            for (PackageParser.Package p : allPackages) {
790                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
791                    if (overlayPackages == null) {
792                        overlayPackages = new ArrayList<PackageParser.Package>();
793                    }
794                    overlayPackages.add(p);
795                }
796            }
797            if (overlayPackages != null) {
798                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
799                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
800                        return p1.mOverlayPriority - p2.mOverlayPriority;
801                    }
802                };
803                Collections.sort(overlayPackages, cmp);
804            }
805            return overlayPackages;
806        }
807
808        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
809                String targetPackageName, String targetPath) {
810            if ("android".equals(targetPackageName)) {
811                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
812                // native AssetManager.
813                return null;
814            }
815            List<PackageParser.Package> overlayPackages =
816                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
817            if (overlayPackages == null || overlayPackages.isEmpty()) {
818                return null;
819            }
820            List<String> overlayPathList = null;
821            for (PackageParser.Package overlayPackage : overlayPackages) {
822                if (targetPath == null) {
823                    if (overlayPathList == null) {
824                        overlayPathList = new ArrayList<String>();
825                    }
826                    overlayPathList.add(overlayPackage.baseCodePath);
827                    continue;
828                }
829
830                try {
831                    // Creates idmaps for system to parse correctly the Android manifest of the
832                    // target package.
833                    //
834                    // OverlayManagerService will update each of them with a correct gid from its
835                    // target package app id.
836                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
837                            UserHandle.getSharedAppGid(
838                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
839                    if (overlayPathList == null) {
840                        overlayPathList = new ArrayList<String>();
841                    }
842                    overlayPathList.add(overlayPackage.baseCodePath);
843                } catch (InstallerException e) {
844                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
845                            overlayPackage.baseCodePath);
846                }
847            }
848            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
849        }
850
851        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
852            synchronized (mPackages) {
853                return getStaticOverlayPathsLocked(
854                        mPackages.values(), targetPackageName, targetPath);
855            }
856        }
857
858        @Override public final String[] getOverlayApks(String targetPackageName) {
859            return getStaticOverlayPaths(targetPackageName, null);
860        }
861
862        @Override public final String[] getOverlayPaths(String targetPackageName,
863                String targetPath) {
864            return getStaticOverlayPaths(targetPackageName, targetPath);
865        }
866    };
867
868    class ParallelPackageParserCallback extends PackageParserCallback {
869        List<PackageParser.Package> mOverlayPackages = null;
870
871        void findStaticOverlayPackages() {
872            synchronized (mPackages) {
873                for (PackageParser.Package p : mPackages.values()) {
874                    if (p.mIsStaticOverlay) {
875                        if (mOverlayPackages == null) {
876                            mOverlayPackages = new ArrayList<PackageParser.Package>();
877                        }
878                        mOverlayPackages.add(p);
879                    }
880                }
881            }
882        }
883
884        @Override
885        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
886            // We can trust mOverlayPackages without holding mPackages because package uninstall
887            // can't happen while running parallel parsing.
888            // Moreover holding mPackages on each parsing thread causes dead-lock.
889            return mOverlayPackages == null ? null :
890                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
891        }
892    }
893
894    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
895    final ParallelPackageParserCallback mParallelPackageParserCallback =
896            new ParallelPackageParserCallback();
897
898    public static final class SharedLibraryEntry {
899        public final @Nullable String path;
900        public final @Nullable String apk;
901        public final @NonNull SharedLibraryInfo info;
902
903        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
904                String declaringPackageName, int declaringPackageVersionCode) {
905            path = _path;
906            apk = _apk;
907            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
908                    declaringPackageName, declaringPackageVersionCode), null);
909        }
910    }
911
912    // Currently known shared libraries.
913    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
914    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
915            new ArrayMap<>();
916
917    // All available activities, for your resolving pleasure.
918    final ActivityIntentResolver mActivities =
919            new ActivityIntentResolver();
920
921    // All available receivers, for your resolving pleasure.
922    final ActivityIntentResolver mReceivers =
923            new ActivityIntentResolver();
924
925    // All available services, for your resolving pleasure.
926    final ServiceIntentResolver mServices = new ServiceIntentResolver();
927
928    // All available providers, for your resolving pleasure.
929    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
930
931    // Mapping from provider base names (first directory in content URI codePath)
932    // to the provider information.
933    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
934            new ArrayMap<String, PackageParser.Provider>();
935
936    // Mapping from instrumentation class names to info about them.
937    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
938            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
939
940    // Mapping from permission names to info about them.
941    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
942            new ArrayMap<String, PackageParser.PermissionGroup>();
943
944    // Packages whose data we have transfered into another package, thus
945    // should no longer exist.
946    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
947
948    // Broadcast actions that are only available to the system.
949    @GuardedBy("mProtectedBroadcasts")
950    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
951
952    /** List of packages waiting for verification. */
953    final SparseArray<PackageVerificationState> mPendingVerification
954            = new SparseArray<PackageVerificationState>();
955
956    /** Set of packages associated with each app op permission. */
957    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
958
959    final PackageInstallerService mInstallerService;
960
961    private final PackageDexOptimizer mPackageDexOptimizer;
962    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
963    // is used by other apps).
964    private final DexManager mDexManager;
965
966    private AtomicInteger mNextMoveId = new AtomicInteger();
967    private final MoveCallbacks mMoveCallbacks;
968
969    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
970
971    // Cache of users who need badging.
972    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
973
974    /** Token for keys in mPendingVerification. */
975    private int mPendingVerificationToken = 0;
976
977    volatile boolean mSystemReady;
978    volatile boolean mSafeMode;
979    volatile boolean mHasSystemUidErrors;
980    private volatile boolean mEphemeralAppsDisabled;
981
982    ApplicationInfo mAndroidApplication;
983    final ActivityInfo mResolveActivity = new ActivityInfo();
984    final ResolveInfo mResolveInfo = new ResolveInfo();
985    ComponentName mResolveComponentName;
986    PackageParser.Package mPlatformPackage;
987    ComponentName mCustomResolverComponentName;
988
989    boolean mResolverReplaced = false;
990
991    private final @Nullable ComponentName mIntentFilterVerifierComponent;
992    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
993
994    private int mIntentFilterVerificationToken = 0;
995
996    /** The service connection to the ephemeral resolver */
997    final EphemeralResolverConnection mInstantAppResolverConnection;
998    /** Component used to show resolver settings for Instant Apps */
999    final ComponentName mInstantAppResolverSettingsComponent;
1000
1001    /** Activity used to install instant applications */
1002    ActivityInfo mInstantAppInstallerActivity;
1003    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
1004
1005    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
1006            = new SparseArray<IntentFilterVerificationState>();
1007
1008    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
1009
1010    // List of packages names to keep cached, even if they are uninstalled for all users
1011    private List<String> mKeepUninstalledPackages;
1012
1013    private UserManagerInternal mUserManagerInternal;
1014
1015    private DeviceIdleController.LocalService mDeviceIdleController;
1016
1017    private File mCacheDir;
1018
1019    private ArraySet<String> mPrivappPermissionsViolations;
1020
1021    private Future<?> mPrepareAppDataFuture;
1022
1023    private static class IFVerificationParams {
1024        PackageParser.Package pkg;
1025        boolean replacing;
1026        int userId;
1027        int verifierUid;
1028
1029        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1030                int _userId, int _verifierUid) {
1031            pkg = _pkg;
1032            replacing = _replacing;
1033            userId = _userId;
1034            replacing = _replacing;
1035            verifierUid = _verifierUid;
1036        }
1037    }
1038
1039    private interface IntentFilterVerifier<T extends IntentFilter> {
1040        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1041                                               T filter, String packageName);
1042        void startVerifications(int userId);
1043        void receiveVerificationResponse(int verificationId);
1044    }
1045
1046    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1047        private Context mContext;
1048        private ComponentName mIntentFilterVerifierComponent;
1049        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1050
1051        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1052            mContext = context;
1053            mIntentFilterVerifierComponent = verifierComponent;
1054        }
1055
1056        private String getDefaultScheme() {
1057            return IntentFilter.SCHEME_HTTPS;
1058        }
1059
1060        @Override
1061        public void startVerifications(int userId) {
1062            // Launch verifications requests
1063            int count = mCurrentIntentFilterVerifications.size();
1064            for (int n=0; n<count; n++) {
1065                int verificationId = mCurrentIntentFilterVerifications.get(n);
1066                final IntentFilterVerificationState ivs =
1067                        mIntentFilterVerificationStates.get(verificationId);
1068
1069                String packageName = ivs.getPackageName();
1070
1071                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1072                final int filterCount = filters.size();
1073                ArraySet<String> domainsSet = new ArraySet<>();
1074                for (int m=0; m<filterCount; m++) {
1075                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1076                    domainsSet.addAll(filter.getHostsList());
1077                }
1078                synchronized (mPackages) {
1079                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1080                            packageName, domainsSet) != null) {
1081                        scheduleWriteSettingsLocked();
1082                    }
1083                }
1084                sendVerificationRequest(verificationId, ivs);
1085            }
1086            mCurrentIntentFilterVerifications.clear();
1087        }
1088
1089        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1090            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1091            verificationIntent.putExtra(
1092                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1093                    verificationId);
1094            verificationIntent.putExtra(
1095                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1096                    getDefaultScheme());
1097            verificationIntent.putExtra(
1098                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1099                    ivs.getHostsString());
1100            verificationIntent.putExtra(
1101                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1102                    ivs.getPackageName());
1103            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1104            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1105
1106            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1107            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1108                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1109                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1110
1111            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1112            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1113                    "Sending IntentFilter verification broadcast");
1114        }
1115
1116        public void receiveVerificationResponse(int verificationId) {
1117            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1118
1119            final boolean verified = ivs.isVerified();
1120
1121            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1122            final int count = filters.size();
1123            if (DEBUG_DOMAIN_VERIFICATION) {
1124                Slog.i(TAG, "Received verification response " + verificationId
1125                        + " for " + count + " filters, verified=" + verified);
1126            }
1127            for (int n=0; n<count; n++) {
1128                PackageParser.ActivityIntentInfo filter = filters.get(n);
1129                filter.setVerified(verified);
1130
1131                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1132                        + " verified with result:" + verified + " and hosts:"
1133                        + ivs.getHostsString());
1134            }
1135
1136            mIntentFilterVerificationStates.remove(verificationId);
1137
1138            final String packageName = ivs.getPackageName();
1139            IntentFilterVerificationInfo ivi = null;
1140
1141            synchronized (mPackages) {
1142                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1143            }
1144            if (ivi == null) {
1145                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1146                        + verificationId + " packageName:" + packageName);
1147                return;
1148            }
1149            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1150                    "Updating IntentFilterVerificationInfo for package " + packageName
1151                            +" verificationId:" + verificationId);
1152
1153            synchronized (mPackages) {
1154                if (verified) {
1155                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1156                } else {
1157                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1158                }
1159                scheduleWriteSettingsLocked();
1160
1161                final int userId = ivs.getUserId();
1162                if (userId != UserHandle.USER_ALL) {
1163                    final int userStatus =
1164                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1165
1166                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1167                    boolean needUpdate = false;
1168
1169                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1170                    // already been set by the User thru the Disambiguation dialog
1171                    switch (userStatus) {
1172                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1173                            if (verified) {
1174                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1175                            } else {
1176                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1177                            }
1178                            needUpdate = true;
1179                            break;
1180
1181                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1182                            if (verified) {
1183                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1184                                needUpdate = true;
1185                            }
1186                            break;
1187
1188                        default:
1189                            // Nothing to do
1190                    }
1191
1192                    if (needUpdate) {
1193                        mSettings.updateIntentFilterVerificationStatusLPw(
1194                                packageName, updatedStatus, userId);
1195                        scheduleWritePackageRestrictionsLocked(userId);
1196                    }
1197                }
1198            }
1199        }
1200
1201        @Override
1202        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1203                    ActivityIntentInfo filter, String packageName) {
1204            if (!hasValidDomains(filter)) {
1205                return false;
1206            }
1207            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1208            if (ivs == null) {
1209                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1210                        packageName);
1211            }
1212            if (DEBUG_DOMAIN_VERIFICATION) {
1213                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1214            }
1215            ivs.addFilter(filter);
1216            return true;
1217        }
1218
1219        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1220                int userId, int verificationId, String packageName) {
1221            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1222                    verifierUid, userId, packageName);
1223            ivs.setPendingState();
1224            synchronized (mPackages) {
1225                mIntentFilterVerificationStates.append(verificationId, ivs);
1226                mCurrentIntentFilterVerifications.add(verificationId);
1227            }
1228            return ivs;
1229        }
1230    }
1231
1232    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1233        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1234                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1235                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1236    }
1237
1238    // Set of pending broadcasts for aggregating enable/disable of components.
1239    static class PendingPackageBroadcasts {
1240        // for each user id, a map of <package name -> components within that package>
1241        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1242
1243        public PendingPackageBroadcasts() {
1244            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1245        }
1246
1247        public ArrayList<String> get(int userId, String packageName) {
1248            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1249            return packages.get(packageName);
1250        }
1251
1252        public void put(int userId, String packageName, ArrayList<String> components) {
1253            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1254            packages.put(packageName, components);
1255        }
1256
1257        public void remove(int userId, String packageName) {
1258            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1259            if (packages != null) {
1260                packages.remove(packageName);
1261            }
1262        }
1263
1264        public void remove(int userId) {
1265            mUidMap.remove(userId);
1266        }
1267
1268        public int userIdCount() {
1269            return mUidMap.size();
1270        }
1271
1272        public int userIdAt(int n) {
1273            return mUidMap.keyAt(n);
1274        }
1275
1276        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1277            return mUidMap.get(userId);
1278        }
1279
1280        public int size() {
1281            // total number of pending broadcast entries across all userIds
1282            int num = 0;
1283            for (int i = 0; i< mUidMap.size(); i++) {
1284                num += mUidMap.valueAt(i).size();
1285            }
1286            return num;
1287        }
1288
1289        public void clear() {
1290            mUidMap.clear();
1291        }
1292
1293        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1294            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1295            if (map == null) {
1296                map = new ArrayMap<String, ArrayList<String>>();
1297                mUidMap.put(userId, map);
1298            }
1299            return map;
1300        }
1301    }
1302    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1303
1304    // Service Connection to remote media container service to copy
1305    // package uri's from external media onto secure containers
1306    // or internal storage.
1307    private IMediaContainerService mContainerService = null;
1308
1309    static final int SEND_PENDING_BROADCAST = 1;
1310    static final int MCS_BOUND = 3;
1311    static final int END_COPY = 4;
1312    static final int INIT_COPY = 5;
1313    static final int MCS_UNBIND = 6;
1314    static final int START_CLEANING_PACKAGE = 7;
1315    static final int FIND_INSTALL_LOC = 8;
1316    static final int POST_INSTALL = 9;
1317    static final int MCS_RECONNECT = 10;
1318    static final int MCS_GIVE_UP = 11;
1319    static final int UPDATED_MEDIA_STATUS = 12;
1320    static final int WRITE_SETTINGS = 13;
1321    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1322    static final int PACKAGE_VERIFIED = 15;
1323    static final int CHECK_PENDING_VERIFICATION = 16;
1324    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1325    static final int INTENT_FILTER_VERIFIED = 18;
1326    static final int WRITE_PACKAGE_LIST = 19;
1327    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1328
1329    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1330
1331    // Delay time in millisecs
1332    static final int BROADCAST_DELAY = 10 * 1000;
1333
1334    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1335            2 * 60 * 60 * 1000L; /* two hours */
1336
1337    static UserManagerService sUserManager;
1338
1339    // Stores a list of users whose package restrictions file needs to be updated
1340    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1341
1342    final private DefaultContainerConnection mDefContainerConn =
1343            new DefaultContainerConnection();
1344    class DefaultContainerConnection implements ServiceConnection {
1345        public void onServiceConnected(ComponentName name, IBinder service) {
1346            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1347            final IMediaContainerService imcs = IMediaContainerService.Stub
1348                    .asInterface(Binder.allowBlocking(service));
1349            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1350        }
1351
1352        public void onServiceDisconnected(ComponentName name) {
1353            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1354        }
1355    }
1356
1357    // Recordkeeping of restore-after-install operations that are currently in flight
1358    // between the Package Manager and the Backup Manager
1359    static class PostInstallData {
1360        public InstallArgs args;
1361        public PackageInstalledInfo res;
1362
1363        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1364            args = _a;
1365            res = _r;
1366        }
1367    }
1368
1369    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1370    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1371
1372    // XML tags for backup/restore of various bits of state
1373    private static final String TAG_PREFERRED_BACKUP = "pa";
1374    private static final String TAG_DEFAULT_APPS = "da";
1375    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1376
1377    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1378    private static final String TAG_ALL_GRANTS = "rt-grants";
1379    private static final String TAG_GRANT = "grant";
1380    private static final String ATTR_PACKAGE_NAME = "pkg";
1381
1382    private static final String TAG_PERMISSION = "perm";
1383    private static final String ATTR_PERMISSION_NAME = "name";
1384    private static final String ATTR_IS_GRANTED = "g";
1385    private static final String ATTR_USER_SET = "set";
1386    private static final String ATTR_USER_FIXED = "fixed";
1387    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1388
1389    // System/policy permission grants are not backed up
1390    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1391            FLAG_PERMISSION_POLICY_FIXED
1392            | FLAG_PERMISSION_SYSTEM_FIXED
1393            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1394
1395    // And we back up these user-adjusted states
1396    private static final int USER_RUNTIME_GRANT_MASK =
1397            FLAG_PERMISSION_USER_SET
1398            | FLAG_PERMISSION_USER_FIXED
1399            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1400
1401    final @Nullable String mRequiredVerifierPackage;
1402    final @NonNull String mRequiredInstallerPackage;
1403    final @NonNull String mRequiredUninstallerPackage;
1404    final @Nullable String mSetupWizardPackage;
1405    final @Nullable String mStorageManagerPackage;
1406    final @NonNull String mServicesSystemSharedLibraryPackageName;
1407    final @NonNull String mSharedSystemSharedLibraryPackageName;
1408
1409    final boolean mPermissionReviewRequired;
1410
1411    private final PackageUsage mPackageUsage = new PackageUsage();
1412    private final CompilerStats mCompilerStats = new CompilerStats();
1413
1414    class PackageHandler extends Handler {
1415        private boolean mBound = false;
1416        final ArrayList<HandlerParams> mPendingInstalls =
1417            new ArrayList<HandlerParams>();
1418
1419        private boolean connectToService() {
1420            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1421                    " DefaultContainerService");
1422            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1423            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1424            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1425                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1426                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1427                mBound = true;
1428                return true;
1429            }
1430            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1431            return false;
1432        }
1433
1434        private void disconnectService() {
1435            mContainerService = null;
1436            mBound = false;
1437            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1438            mContext.unbindService(mDefContainerConn);
1439            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1440        }
1441
1442        PackageHandler(Looper looper) {
1443            super(looper);
1444        }
1445
1446        public void handleMessage(Message msg) {
1447            try {
1448                doHandleMessage(msg);
1449            } finally {
1450                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1451            }
1452        }
1453
1454        void doHandleMessage(Message msg) {
1455            switch (msg.what) {
1456                case INIT_COPY: {
1457                    HandlerParams params = (HandlerParams) msg.obj;
1458                    int idx = mPendingInstalls.size();
1459                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1460                    // If a bind was already initiated we dont really
1461                    // need to do anything. The pending install
1462                    // will be processed later on.
1463                    if (!mBound) {
1464                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1465                                System.identityHashCode(mHandler));
1466                        // If this is the only one pending we might
1467                        // have to bind to the service again.
1468                        if (!connectToService()) {
1469                            Slog.e(TAG, "Failed to bind to media container service");
1470                            params.serviceError();
1471                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1472                                    System.identityHashCode(mHandler));
1473                            if (params.traceMethod != null) {
1474                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1475                                        params.traceCookie);
1476                            }
1477                            return;
1478                        } else {
1479                            // Once we bind to the service, the first
1480                            // pending request will be processed.
1481                            mPendingInstalls.add(idx, params);
1482                        }
1483                    } else {
1484                        mPendingInstalls.add(idx, params);
1485                        // Already bound to the service. Just make
1486                        // sure we trigger off processing the first request.
1487                        if (idx == 0) {
1488                            mHandler.sendEmptyMessage(MCS_BOUND);
1489                        }
1490                    }
1491                    break;
1492                }
1493                case MCS_BOUND: {
1494                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1495                    if (msg.obj != null) {
1496                        mContainerService = (IMediaContainerService) msg.obj;
1497                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1498                                System.identityHashCode(mHandler));
1499                    }
1500                    if (mContainerService == null) {
1501                        if (!mBound) {
1502                            // Something seriously wrong since we are not bound and we are not
1503                            // waiting for connection. Bail out.
1504                            Slog.e(TAG, "Cannot bind to media container service");
1505                            for (HandlerParams params : mPendingInstalls) {
1506                                // Indicate service bind error
1507                                params.serviceError();
1508                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1509                                        System.identityHashCode(params));
1510                                if (params.traceMethod != null) {
1511                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1512                                            params.traceMethod, params.traceCookie);
1513                                }
1514                                return;
1515                            }
1516                            mPendingInstalls.clear();
1517                        } else {
1518                            Slog.w(TAG, "Waiting to connect to media container service");
1519                        }
1520                    } else if (mPendingInstalls.size() > 0) {
1521                        HandlerParams params = mPendingInstalls.get(0);
1522                        if (params != null) {
1523                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1524                                    System.identityHashCode(params));
1525                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1526                            if (params.startCopy()) {
1527                                // We are done...  look for more work or to
1528                                // go idle.
1529                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1530                                        "Checking for more work or unbind...");
1531                                // Delete pending install
1532                                if (mPendingInstalls.size() > 0) {
1533                                    mPendingInstalls.remove(0);
1534                                }
1535                                if (mPendingInstalls.size() == 0) {
1536                                    if (mBound) {
1537                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1538                                                "Posting delayed MCS_UNBIND");
1539                                        removeMessages(MCS_UNBIND);
1540                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1541                                        // Unbind after a little delay, to avoid
1542                                        // continual thrashing.
1543                                        sendMessageDelayed(ubmsg, 10000);
1544                                    }
1545                                } else {
1546                                    // There are more pending requests in queue.
1547                                    // Just post MCS_BOUND message to trigger processing
1548                                    // of next pending install.
1549                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1550                                            "Posting MCS_BOUND for next work");
1551                                    mHandler.sendEmptyMessage(MCS_BOUND);
1552                                }
1553                            }
1554                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1555                        }
1556                    } else {
1557                        // Should never happen ideally.
1558                        Slog.w(TAG, "Empty queue");
1559                    }
1560                    break;
1561                }
1562                case MCS_RECONNECT: {
1563                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1564                    if (mPendingInstalls.size() > 0) {
1565                        if (mBound) {
1566                            disconnectService();
1567                        }
1568                        if (!connectToService()) {
1569                            Slog.e(TAG, "Failed to bind to media container service");
1570                            for (HandlerParams params : mPendingInstalls) {
1571                                // Indicate service bind error
1572                                params.serviceError();
1573                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1574                                        System.identityHashCode(params));
1575                            }
1576                            mPendingInstalls.clear();
1577                        }
1578                    }
1579                    break;
1580                }
1581                case MCS_UNBIND: {
1582                    // If there is no actual work left, then time to unbind.
1583                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1584
1585                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1586                        if (mBound) {
1587                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1588
1589                            disconnectService();
1590                        }
1591                    } else if (mPendingInstalls.size() > 0) {
1592                        // There are more pending requests in queue.
1593                        // Just post MCS_BOUND message to trigger processing
1594                        // of next pending install.
1595                        mHandler.sendEmptyMessage(MCS_BOUND);
1596                    }
1597
1598                    break;
1599                }
1600                case MCS_GIVE_UP: {
1601                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1602                    HandlerParams params = mPendingInstalls.remove(0);
1603                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1604                            System.identityHashCode(params));
1605                    break;
1606                }
1607                case SEND_PENDING_BROADCAST: {
1608                    String packages[];
1609                    ArrayList<String> components[];
1610                    int size = 0;
1611                    int uids[];
1612                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1613                    synchronized (mPackages) {
1614                        if (mPendingBroadcasts == null) {
1615                            return;
1616                        }
1617                        size = mPendingBroadcasts.size();
1618                        if (size <= 0) {
1619                            // Nothing to be done. Just return
1620                            return;
1621                        }
1622                        packages = new String[size];
1623                        components = new ArrayList[size];
1624                        uids = new int[size];
1625                        int i = 0;  // filling out the above arrays
1626
1627                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1628                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1629                            Iterator<Map.Entry<String, ArrayList<String>>> it
1630                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1631                                            .entrySet().iterator();
1632                            while (it.hasNext() && i < size) {
1633                                Map.Entry<String, ArrayList<String>> ent = it.next();
1634                                packages[i] = ent.getKey();
1635                                components[i] = ent.getValue();
1636                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1637                                uids[i] = (ps != null)
1638                                        ? UserHandle.getUid(packageUserId, ps.appId)
1639                                        : -1;
1640                                i++;
1641                            }
1642                        }
1643                        size = i;
1644                        mPendingBroadcasts.clear();
1645                    }
1646                    // Send broadcasts
1647                    for (int i = 0; i < size; i++) {
1648                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1649                    }
1650                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1651                    break;
1652                }
1653                case START_CLEANING_PACKAGE: {
1654                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1655                    final String packageName = (String)msg.obj;
1656                    final int userId = msg.arg1;
1657                    final boolean andCode = msg.arg2 != 0;
1658                    synchronized (mPackages) {
1659                        if (userId == UserHandle.USER_ALL) {
1660                            int[] users = sUserManager.getUserIds();
1661                            for (int user : users) {
1662                                mSettings.addPackageToCleanLPw(
1663                                        new PackageCleanItem(user, packageName, andCode));
1664                            }
1665                        } else {
1666                            mSettings.addPackageToCleanLPw(
1667                                    new PackageCleanItem(userId, packageName, andCode));
1668                        }
1669                    }
1670                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1671                    startCleaningPackages();
1672                } break;
1673                case POST_INSTALL: {
1674                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1675
1676                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1677                    final boolean didRestore = (msg.arg2 != 0);
1678                    mRunningInstalls.delete(msg.arg1);
1679
1680                    if (data != null) {
1681                        InstallArgs args = data.args;
1682                        PackageInstalledInfo parentRes = data.res;
1683
1684                        final boolean grantPermissions = (args.installFlags
1685                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1686                        final boolean killApp = (args.installFlags
1687                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1688                        final boolean virtualPreload = ((args.installFlags
1689                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1690                        final String[] grantedPermissions = args.installGrantPermissions;
1691
1692                        // Handle the parent package
1693                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1694                                virtualPreload, grantedPermissions, didRestore,
1695                                args.installerPackageName, args.observer);
1696
1697                        // Handle the child packages
1698                        final int childCount = (parentRes.addedChildPackages != null)
1699                                ? parentRes.addedChildPackages.size() : 0;
1700                        for (int i = 0; i < childCount; i++) {
1701                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1702                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1703                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1704                                    args.installerPackageName, args.observer);
1705                        }
1706
1707                        // Log tracing if needed
1708                        if (args.traceMethod != null) {
1709                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1710                                    args.traceCookie);
1711                        }
1712                    } else {
1713                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1714                    }
1715
1716                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1717                } break;
1718                case UPDATED_MEDIA_STATUS: {
1719                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1720                    boolean reportStatus = msg.arg1 == 1;
1721                    boolean doGc = msg.arg2 == 1;
1722                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1723                    if (doGc) {
1724                        // Force a gc to clear up stale containers.
1725                        Runtime.getRuntime().gc();
1726                    }
1727                    if (msg.obj != null) {
1728                        @SuppressWarnings("unchecked")
1729                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1730                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1731                        // Unload containers
1732                        unloadAllContainers(args);
1733                    }
1734                    if (reportStatus) {
1735                        try {
1736                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1737                                    "Invoking StorageManagerService call back");
1738                            PackageHelper.getStorageManager().finishMediaUpdate();
1739                        } catch (RemoteException e) {
1740                            Log.e(TAG, "StorageManagerService not running?");
1741                        }
1742                    }
1743                } break;
1744                case WRITE_SETTINGS: {
1745                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1746                    synchronized (mPackages) {
1747                        removeMessages(WRITE_SETTINGS);
1748                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1749                        mSettings.writeLPr();
1750                        mDirtyUsers.clear();
1751                    }
1752                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1753                } break;
1754                case WRITE_PACKAGE_RESTRICTIONS: {
1755                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1756                    synchronized (mPackages) {
1757                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1758                        for (int userId : mDirtyUsers) {
1759                            mSettings.writePackageRestrictionsLPr(userId);
1760                        }
1761                        mDirtyUsers.clear();
1762                    }
1763                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1764                } break;
1765                case WRITE_PACKAGE_LIST: {
1766                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1767                    synchronized (mPackages) {
1768                        removeMessages(WRITE_PACKAGE_LIST);
1769                        mSettings.writePackageListLPr(msg.arg1);
1770                    }
1771                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1772                } break;
1773                case CHECK_PENDING_VERIFICATION: {
1774                    final int verificationId = msg.arg1;
1775                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1776
1777                    if ((state != null) && !state.timeoutExtended()) {
1778                        final InstallArgs args = state.getInstallArgs();
1779                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1780
1781                        Slog.i(TAG, "Verification timed out for " + originUri);
1782                        mPendingVerification.remove(verificationId);
1783
1784                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1785
1786                        final UserHandle user = args.getUser();
1787                        if (getDefaultVerificationResponse(user)
1788                                == PackageManager.VERIFICATION_ALLOW) {
1789                            Slog.i(TAG, "Continuing with installation of " + originUri);
1790                            state.setVerifierResponse(Binder.getCallingUid(),
1791                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1792                            broadcastPackageVerified(verificationId, originUri,
1793                                    PackageManager.VERIFICATION_ALLOW, user);
1794                            try {
1795                                ret = args.copyApk(mContainerService, true);
1796                            } catch (RemoteException e) {
1797                                Slog.e(TAG, "Could not contact the ContainerService");
1798                            }
1799                        } else {
1800                            broadcastPackageVerified(verificationId, originUri,
1801                                    PackageManager.VERIFICATION_REJECT, user);
1802                        }
1803
1804                        Trace.asyncTraceEnd(
1805                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1806
1807                        processPendingInstall(args, ret);
1808                        mHandler.sendEmptyMessage(MCS_UNBIND);
1809                    }
1810                    break;
1811                }
1812                case PACKAGE_VERIFIED: {
1813                    final int verificationId = msg.arg1;
1814
1815                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1816                    if (state == null) {
1817                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1818                        break;
1819                    }
1820
1821                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1822
1823                    state.setVerifierResponse(response.callerUid, response.code);
1824
1825                    if (state.isVerificationComplete()) {
1826                        mPendingVerification.remove(verificationId);
1827
1828                        final InstallArgs args = state.getInstallArgs();
1829                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1830
1831                        int ret;
1832                        if (state.isInstallAllowed()) {
1833                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1834                            broadcastPackageVerified(verificationId, originUri,
1835                                    response.code, state.getInstallArgs().getUser());
1836                            try {
1837                                ret = args.copyApk(mContainerService, true);
1838                            } catch (RemoteException e) {
1839                                Slog.e(TAG, "Could not contact the ContainerService");
1840                            }
1841                        } else {
1842                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1843                        }
1844
1845                        Trace.asyncTraceEnd(
1846                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1847
1848                        processPendingInstall(args, ret);
1849                        mHandler.sendEmptyMessage(MCS_UNBIND);
1850                    }
1851
1852                    break;
1853                }
1854                case START_INTENT_FILTER_VERIFICATIONS: {
1855                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1856                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1857                            params.replacing, params.pkg);
1858                    break;
1859                }
1860                case INTENT_FILTER_VERIFIED: {
1861                    final int verificationId = msg.arg1;
1862
1863                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1864                            verificationId);
1865                    if (state == null) {
1866                        Slog.w(TAG, "Invalid IntentFilter verification token "
1867                                + verificationId + " received");
1868                        break;
1869                    }
1870
1871                    final int userId = state.getUserId();
1872
1873                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1874                            "Processing IntentFilter verification with token:"
1875                            + verificationId + " and userId:" + userId);
1876
1877                    final IntentFilterVerificationResponse response =
1878                            (IntentFilterVerificationResponse) msg.obj;
1879
1880                    state.setVerifierResponse(response.callerUid, response.code);
1881
1882                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1883                            "IntentFilter verification with token:" + verificationId
1884                            + " and userId:" + userId
1885                            + " is settings verifier response with response code:"
1886                            + response.code);
1887
1888                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1889                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1890                                + response.getFailedDomainsString());
1891                    }
1892
1893                    if (state.isVerificationComplete()) {
1894                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1895                    } else {
1896                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1897                                "IntentFilter verification with token:" + verificationId
1898                                + " was not said to be complete");
1899                    }
1900
1901                    break;
1902                }
1903                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1904                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1905                            mInstantAppResolverConnection,
1906                            (InstantAppRequest) msg.obj,
1907                            mInstantAppInstallerActivity,
1908                            mHandler);
1909                }
1910            }
1911        }
1912    }
1913
1914    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1915            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1916            boolean launchedForRestore, String installerPackage,
1917            IPackageInstallObserver2 installObserver) {
1918        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1919            // Send the removed broadcasts
1920            if (res.removedInfo != null) {
1921                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1922            }
1923
1924            // Now that we successfully installed the package, grant runtime
1925            // permissions if requested before broadcasting the install. Also
1926            // for legacy apps in permission review mode we clear the permission
1927            // review flag which is used to emulate runtime permissions for
1928            // legacy apps.
1929            if (grantPermissions) {
1930                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1931            }
1932
1933            final boolean update = res.removedInfo != null
1934                    && res.removedInfo.removedPackage != null;
1935            final String installerPackageName =
1936                    res.installerPackageName != null
1937                            ? res.installerPackageName
1938                            : res.removedInfo != null
1939                                    ? res.removedInfo.installerPackageName
1940                                    : null;
1941
1942            // If this is the first time we have child packages for a disabled privileged
1943            // app that had no children, we grant requested runtime permissions to the new
1944            // children if the parent on the system image had them already granted.
1945            if (res.pkg.parentPackage != null) {
1946                synchronized (mPackages) {
1947                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1948                }
1949            }
1950
1951            synchronized (mPackages) {
1952                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1953            }
1954
1955            final String packageName = res.pkg.applicationInfo.packageName;
1956
1957            // Determine the set of users who are adding this package for
1958            // the first time vs. those who are seeing an update.
1959            int[] firstUsers = EMPTY_INT_ARRAY;
1960            int[] updateUsers = EMPTY_INT_ARRAY;
1961            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1962            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1963            for (int newUser : res.newUsers) {
1964                if (ps.getInstantApp(newUser)) {
1965                    continue;
1966                }
1967                if (allNewUsers) {
1968                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1969                    continue;
1970                }
1971                boolean isNew = true;
1972                for (int origUser : res.origUsers) {
1973                    if (origUser == newUser) {
1974                        isNew = false;
1975                        break;
1976                    }
1977                }
1978                if (isNew) {
1979                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1980                } else {
1981                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1982                }
1983            }
1984
1985            // Send installed broadcasts if the package is not a static shared lib.
1986            if (res.pkg.staticSharedLibName == null) {
1987                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1988
1989                // Send added for users that see the package for the first time
1990                // sendPackageAddedForNewUsers also deals with system apps
1991                int appId = UserHandle.getAppId(res.uid);
1992                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1993                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
1994                        virtualPreload /*startReceiver*/, appId, firstUsers);
1995
1996                // Send added for users that don't see the package for the first time
1997                Bundle extras = new Bundle(1);
1998                extras.putInt(Intent.EXTRA_UID, res.uid);
1999                if (update) {
2000                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
2001                }
2002                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2003                        extras, 0 /*flags*/,
2004                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
2005                if (installerPackageName != null) {
2006                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2007                            extras, 0 /*flags*/,
2008                            installerPackageName, null /*finishedReceiver*/, updateUsers);
2009                }
2010
2011                // Send replaced for users that don't see the package for the first time
2012                if (update) {
2013                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2014                            packageName, extras, 0 /*flags*/,
2015                            null /*targetPackage*/, null /*finishedReceiver*/,
2016                            updateUsers);
2017                    if (installerPackageName != null) {
2018                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2019                                extras, 0 /*flags*/,
2020                                installerPackageName, null /*finishedReceiver*/, updateUsers);
2021                    }
2022                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2023                            null /*package*/, null /*extras*/, 0 /*flags*/,
2024                            packageName /*targetPackage*/,
2025                            null /*finishedReceiver*/, updateUsers);
2026                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2027                    // First-install and we did a restore, so we're responsible for the
2028                    // first-launch broadcast.
2029                    if (DEBUG_BACKUP) {
2030                        Slog.i(TAG, "Post-restore of " + packageName
2031                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2032                    }
2033                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2034                }
2035
2036                // Send broadcast package appeared if forward locked/external for all users
2037                // treat asec-hosted packages like removable media on upgrade
2038                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2039                    if (DEBUG_INSTALL) {
2040                        Slog.i(TAG, "upgrading pkg " + res.pkg
2041                                + " is ASEC-hosted -> AVAILABLE");
2042                    }
2043                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2044                    ArrayList<String> pkgList = new ArrayList<>(1);
2045                    pkgList.add(packageName);
2046                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2047                }
2048            }
2049
2050            // Work that needs to happen on first install within each user
2051            if (firstUsers != null && firstUsers.length > 0) {
2052                synchronized (mPackages) {
2053                    for (int userId : firstUsers) {
2054                        // If this app is a browser and it's newly-installed for some
2055                        // users, clear any default-browser state in those users. The
2056                        // app's nature doesn't depend on the user, so we can just check
2057                        // its browser nature in any user and generalize.
2058                        if (packageIsBrowser(packageName, userId)) {
2059                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2060                        }
2061
2062                        // We may also need to apply pending (restored) runtime
2063                        // permission grants within these users.
2064                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2065                    }
2066                }
2067            }
2068
2069            // Log current value of "unknown sources" setting
2070            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2071                    getUnknownSourcesSettings());
2072
2073            // Remove the replaced package's older resources safely now
2074            // We delete after a gc for applications  on sdcard.
2075            if (res.removedInfo != null && res.removedInfo.args != null) {
2076                Runtime.getRuntime().gc();
2077                synchronized (mInstallLock) {
2078                    res.removedInfo.args.doPostDeleteLI(true);
2079                }
2080            } else {
2081                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2082                // and not block here.
2083                VMRuntime.getRuntime().requestConcurrentGC();
2084            }
2085
2086            // Notify DexManager that the package was installed for new users.
2087            // The updated users should already be indexed and the package code paths
2088            // should not change.
2089            // Don't notify the manager for ephemeral apps as they are not expected to
2090            // survive long enough to benefit of background optimizations.
2091            for (int userId : firstUsers) {
2092                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2093                // There's a race currently where some install events may interleave with an uninstall.
2094                // This can lead to package info being null (b/36642664).
2095                if (info != null) {
2096                    mDexManager.notifyPackageInstalled(info, userId);
2097                }
2098            }
2099        }
2100
2101        // If someone is watching installs - notify them
2102        if (installObserver != null) {
2103            try {
2104                Bundle extras = extrasForInstallResult(res);
2105                installObserver.onPackageInstalled(res.name, res.returnCode,
2106                        res.returnMsg, extras);
2107            } catch (RemoteException e) {
2108                Slog.i(TAG, "Observer no longer exists.");
2109            }
2110        }
2111    }
2112
2113    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2114            PackageParser.Package pkg) {
2115        if (pkg.parentPackage == null) {
2116            return;
2117        }
2118        if (pkg.requestedPermissions == null) {
2119            return;
2120        }
2121        final PackageSetting disabledSysParentPs = mSettings
2122                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2123        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2124                || !disabledSysParentPs.isPrivileged()
2125                || (disabledSysParentPs.childPackageNames != null
2126                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2127            return;
2128        }
2129        final int[] allUserIds = sUserManager.getUserIds();
2130        final int permCount = pkg.requestedPermissions.size();
2131        for (int i = 0; i < permCount; i++) {
2132            String permission = pkg.requestedPermissions.get(i);
2133            BasePermission bp = mSettings.mPermissions.get(permission);
2134            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2135                continue;
2136            }
2137            for (int userId : allUserIds) {
2138                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2139                        permission, userId)) {
2140                    grantRuntimePermission(pkg.packageName, permission, userId);
2141                }
2142            }
2143        }
2144    }
2145
2146    private StorageEventListener mStorageListener = new StorageEventListener() {
2147        @Override
2148        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2149            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2150                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2151                    final String volumeUuid = vol.getFsUuid();
2152
2153                    // Clean up any users or apps that were removed or recreated
2154                    // while this volume was missing
2155                    sUserManager.reconcileUsers(volumeUuid);
2156                    reconcileApps(volumeUuid);
2157
2158                    // Clean up any install sessions that expired or were
2159                    // cancelled while this volume was missing
2160                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2161
2162                    loadPrivatePackages(vol);
2163
2164                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2165                    unloadPrivatePackages(vol);
2166                }
2167            }
2168
2169            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2170                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2171                    updateExternalMediaStatus(true, false);
2172                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2173                    updateExternalMediaStatus(false, false);
2174                }
2175            }
2176        }
2177
2178        @Override
2179        public void onVolumeForgotten(String fsUuid) {
2180            if (TextUtils.isEmpty(fsUuid)) {
2181                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2182                return;
2183            }
2184
2185            // Remove any apps installed on the forgotten volume
2186            synchronized (mPackages) {
2187                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2188                for (PackageSetting ps : packages) {
2189                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2190                    deletePackageVersioned(new VersionedPackage(ps.name,
2191                            PackageManager.VERSION_CODE_HIGHEST),
2192                            new LegacyPackageDeleteObserver(null).getBinder(),
2193                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2194                    // Try very hard to release any references to this package
2195                    // so we don't risk the system server being killed due to
2196                    // open FDs
2197                    AttributeCache.instance().removePackage(ps.name);
2198                }
2199
2200                mSettings.onVolumeForgotten(fsUuid);
2201                mSettings.writeLPr();
2202            }
2203        }
2204    };
2205
2206    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2207            String[] grantedPermissions) {
2208        for (int userId : userIds) {
2209            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2210        }
2211    }
2212
2213    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2214            String[] grantedPermissions) {
2215        PackageSetting ps = (PackageSetting) pkg.mExtras;
2216        if (ps == null) {
2217            return;
2218        }
2219
2220        PermissionsState permissionsState = ps.getPermissionsState();
2221
2222        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2223                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2224
2225        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2226                >= Build.VERSION_CODES.M;
2227
2228        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2229
2230        for (String permission : pkg.requestedPermissions) {
2231            final BasePermission bp;
2232            synchronized (mPackages) {
2233                bp = mSettings.mPermissions.get(permission);
2234            }
2235            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2236                    && (!instantApp || bp.isInstant())
2237                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2238                    && (grantedPermissions == null
2239                           || ArrayUtils.contains(grantedPermissions, permission))) {
2240                final int flags = permissionsState.getPermissionFlags(permission, userId);
2241                if (supportsRuntimePermissions) {
2242                    // Installer cannot change immutable permissions.
2243                    if ((flags & immutableFlags) == 0) {
2244                        grantRuntimePermission(pkg.packageName, permission, userId);
2245                    }
2246                } else if (mPermissionReviewRequired) {
2247                    // In permission review mode we clear the review flag when we
2248                    // are asked to install the app with all permissions granted.
2249                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2250                        updatePermissionFlags(permission, pkg.packageName,
2251                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2252                    }
2253                }
2254            }
2255        }
2256    }
2257
2258    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2259        Bundle extras = null;
2260        switch (res.returnCode) {
2261            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2262                extras = new Bundle();
2263                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2264                        res.origPermission);
2265                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2266                        res.origPackage);
2267                break;
2268            }
2269            case PackageManager.INSTALL_SUCCEEDED: {
2270                extras = new Bundle();
2271                extras.putBoolean(Intent.EXTRA_REPLACING,
2272                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2273                break;
2274            }
2275        }
2276        return extras;
2277    }
2278
2279    void scheduleWriteSettingsLocked() {
2280        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2281            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2282        }
2283    }
2284
2285    void scheduleWritePackageListLocked(int userId) {
2286        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2287            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2288            msg.arg1 = userId;
2289            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2290        }
2291    }
2292
2293    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2294        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2295        scheduleWritePackageRestrictionsLocked(userId);
2296    }
2297
2298    void scheduleWritePackageRestrictionsLocked(int userId) {
2299        final int[] userIds = (userId == UserHandle.USER_ALL)
2300                ? sUserManager.getUserIds() : new int[]{userId};
2301        for (int nextUserId : userIds) {
2302            if (!sUserManager.exists(nextUserId)) return;
2303            mDirtyUsers.add(nextUserId);
2304            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2305                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2306            }
2307        }
2308    }
2309
2310    public static PackageManagerService main(Context context, Installer installer,
2311            boolean factoryTest, boolean onlyCore) {
2312        // Self-check for initial settings.
2313        PackageManagerServiceCompilerMapping.checkProperties();
2314
2315        PackageManagerService m = new PackageManagerService(context, installer,
2316                factoryTest, onlyCore);
2317        m.enableSystemUserPackages();
2318        ServiceManager.addService("package", m);
2319        final PackageManagerNative pmn = m.new PackageManagerNative();
2320        ServiceManager.addService("package_native", pmn);
2321        return m;
2322    }
2323
2324    private void enableSystemUserPackages() {
2325        if (!UserManager.isSplitSystemUser()) {
2326            return;
2327        }
2328        // For system user, enable apps based on the following conditions:
2329        // - app is whitelisted or belong to one of these groups:
2330        //   -- system app which has no launcher icons
2331        //   -- system app which has INTERACT_ACROSS_USERS permission
2332        //   -- system IME app
2333        // - app is not in the blacklist
2334        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2335        Set<String> enableApps = new ArraySet<>();
2336        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2337                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2338                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2339        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2340        enableApps.addAll(wlApps);
2341        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2342                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2343        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2344        enableApps.removeAll(blApps);
2345        Log.i(TAG, "Applications installed for system user: " + enableApps);
2346        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2347                UserHandle.SYSTEM);
2348        final int allAppsSize = allAps.size();
2349        synchronized (mPackages) {
2350            for (int i = 0; i < allAppsSize; i++) {
2351                String pName = allAps.get(i);
2352                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2353                // Should not happen, but we shouldn't be failing if it does
2354                if (pkgSetting == null) {
2355                    continue;
2356                }
2357                boolean install = enableApps.contains(pName);
2358                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2359                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2360                            + " for system user");
2361                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2362                }
2363            }
2364            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2365        }
2366    }
2367
2368    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2369        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2370                Context.DISPLAY_SERVICE);
2371        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2372    }
2373
2374    /**
2375     * Requests that files preopted on a secondary system partition be copied to the data partition
2376     * if possible.  Note that the actual copying of the files is accomplished by init for security
2377     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2378     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2379     */
2380    private static void requestCopyPreoptedFiles() {
2381        final int WAIT_TIME_MS = 100;
2382        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2383        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2384            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2385            // We will wait for up to 100 seconds.
2386            final long timeStart = SystemClock.uptimeMillis();
2387            final long timeEnd = timeStart + 100 * 1000;
2388            long timeNow = timeStart;
2389            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2390                try {
2391                    Thread.sleep(WAIT_TIME_MS);
2392                } catch (InterruptedException e) {
2393                    // Do nothing
2394                }
2395                timeNow = SystemClock.uptimeMillis();
2396                if (timeNow > timeEnd) {
2397                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2398                    Slog.wtf(TAG, "cppreopt did not finish!");
2399                    break;
2400                }
2401            }
2402
2403            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2404        }
2405    }
2406
2407    public PackageManagerService(Context context, Installer installer,
2408            boolean factoryTest, boolean onlyCore) {
2409        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2410        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2411        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2412                SystemClock.uptimeMillis());
2413
2414        if (mSdkVersion <= 0) {
2415            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2416        }
2417
2418        mContext = context;
2419
2420        mPermissionReviewRequired = context.getResources().getBoolean(
2421                R.bool.config_permissionReviewRequired);
2422
2423        mFactoryTest = factoryTest;
2424        mOnlyCore = onlyCore;
2425        mMetrics = new DisplayMetrics();
2426        mSettings = new Settings(mPackages);
2427        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2428                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2429        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2430                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2431        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2432                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2433        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2434                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2435        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2436                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2437        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2438                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2439
2440        String separateProcesses = SystemProperties.get("debug.separate_processes");
2441        if (separateProcesses != null && separateProcesses.length() > 0) {
2442            if ("*".equals(separateProcesses)) {
2443                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2444                mSeparateProcesses = null;
2445                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2446            } else {
2447                mDefParseFlags = 0;
2448                mSeparateProcesses = separateProcesses.split(",");
2449                Slog.w(TAG, "Running with debug.separate_processes: "
2450                        + separateProcesses);
2451            }
2452        } else {
2453            mDefParseFlags = 0;
2454            mSeparateProcesses = null;
2455        }
2456
2457        mInstaller = installer;
2458        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2459                "*dexopt*");
2460        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2461        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2462
2463        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2464                FgThread.get().getLooper());
2465
2466        getDefaultDisplayMetrics(context, mMetrics);
2467
2468        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2469        SystemConfig systemConfig = SystemConfig.getInstance();
2470        mGlobalGids = systemConfig.getGlobalGids();
2471        mSystemPermissions = systemConfig.getSystemPermissions();
2472        mAvailableFeatures = systemConfig.getAvailableFeatures();
2473        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2474
2475        mProtectedPackages = new ProtectedPackages(mContext);
2476
2477        synchronized (mInstallLock) {
2478        // writer
2479        synchronized (mPackages) {
2480            mHandlerThread = new ServiceThread(TAG,
2481                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2482            mHandlerThread.start();
2483            mHandler = new PackageHandler(mHandlerThread.getLooper());
2484            mProcessLoggingHandler = new ProcessLoggingHandler();
2485            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2486
2487            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2488            mInstantAppRegistry = new InstantAppRegistry(this);
2489
2490            File dataDir = Environment.getDataDirectory();
2491            mAppInstallDir = new File(dataDir, "app");
2492            mAppLib32InstallDir = new File(dataDir, "app-lib");
2493            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2494            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2495            sUserManager = new UserManagerService(context, this,
2496                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2497
2498            // Propagate permission configuration in to package manager.
2499            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2500                    = systemConfig.getPermissions();
2501            for (int i=0; i<permConfig.size(); i++) {
2502                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2503                BasePermission bp = mSettings.mPermissions.get(perm.name);
2504                if (bp == null) {
2505                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2506                    mSettings.mPermissions.put(perm.name, bp);
2507                }
2508                if (perm.gids != null) {
2509                    bp.setGids(perm.gids, perm.perUser);
2510                }
2511            }
2512
2513            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2514            final int builtInLibCount = libConfig.size();
2515            for (int i = 0; i < builtInLibCount; i++) {
2516                String name = libConfig.keyAt(i);
2517                String path = libConfig.valueAt(i);
2518                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2519                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2520            }
2521
2522            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2523
2524            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2525            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2526            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2527
2528            // Clean up orphaned packages for which the code path doesn't exist
2529            // and they are an update to a system app - caused by bug/32321269
2530            final int packageSettingCount = mSettings.mPackages.size();
2531            for (int i = packageSettingCount - 1; i >= 0; i--) {
2532                PackageSetting ps = mSettings.mPackages.valueAt(i);
2533                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2534                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2535                    mSettings.mPackages.removeAt(i);
2536                    mSettings.enableSystemPackageLPw(ps.name);
2537                }
2538            }
2539
2540            if (mFirstBoot) {
2541                requestCopyPreoptedFiles();
2542            }
2543
2544            String customResolverActivity = Resources.getSystem().getString(
2545                    R.string.config_customResolverActivity);
2546            if (TextUtils.isEmpty(customResolverActivity)) {
2547                customResolverActivity = null;
2548            } else {
2549                mCustomResolverComponentName = ComponentName.unflattenFromString(
2550                        customResolverActivity);
2551            }
2552
2553            long startTime = SystemClock.uptimeMillis();
2554
2555            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2556                    startTime);
2557
2558            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2559            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2560
2561            if (bootClassPath == null) {
2562                Slog.w(TAG, "No BOOTCLASSPATH found!");
2563            }
2564
2565            if (systemServerClassPath == null) {
2566                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2567            }
2568
2569            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2570
2571            final VersionInfo ver = mSettings.getInternalVersion();
2572            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2573            if (mIsUpgrade) {
2574                logCriticalInfo(Log.INFO,
2575                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2576            }
2577
2578            // when upgrading from pre-M, promote system app permissions from install to runtime
2579            mPromoteSystemApps =
2580                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2581
2582            // When upgrading from pre-N, we need to handle package extraction like first boot,
2583            // as there is no profiling data available.
2584            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2585
2586            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2587
2588            // save off the names of pre-existing system packages prior to scanning; we don't
2589            // want to automatically grant runtime permissions for new system apps
2590            if (mPromoteSystemApps) {
2591                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2592                while (pkgSettingIter.hasNext()) {
2593                    PackageSetting ps = pkgSettingIter.next();
2594                    if (isSystemApp(ps)) {
2595                        mExistingSystemPackages.add(ps.name);
2596                    }
2597                }
2598            }
2599
2600            mCacheDir = preparePackageParserCache(mIsUpgrade);
2601
2602            // Set flag to monitor and not change apk file paths when
2603            // scanning install directories.
2604            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2605
2606            if (mIsUpgrade || mFirstBoot) {
2607                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2608            }
2609
2610            // Collect vendor overlay packages. (Do this before scanning any apps.)
2611            // For security and version matching reason, only consider
2612            // overlay packages if they reside in the right directory.
2613            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2614                    | PackageParser.PARSE_IS_SYSTEM
2615                    | PackageParser.PARSE_IS_SYSTEM_DIR
2616                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2617
2618            mParallelPackageParserCallback.findStaticOverlayPackages();
2619
2620            // Find base frameworks (resource packages without code).
2621            scanDirTracedLI(frameworkDir, mDefParseFlags
2622                    | PackageParser.PARSE_IS_SYSTEM
2623                    | PackageParser.PARSE_IS_SYSTEM_DIR
2624                    | PackageParser.PARSE_IS_PRIVILEGED,
2625                    scanFlags | SCAN_NO_DEX, 0);
2626
2627            // Collected privileged system packages.
2628            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2629            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2630                    | PackageParser.PARSE_IS_SYSTEM
2631                    | PackageParser.PARSE_IS_SYSTEM_DIR
2632                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2633
2634            // Collect ordinary system packages.
2635            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2636            scanDirTracedLI(systemAppDir, mDefParseFlags
2637                    | PackageParser.PARSE_IS_SYSTEM
2638                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2639
2640            // Collect all vendor packages.
2641            File vendorAppDir = new File("/vendor/app");
2642            try {
2643                vendorAppDir = vendorAppDir.getCanonicalFile();
2644            } catch (IOException e) {
2645                // failed to look up canonical path, continue with original one
2646            }
2647            scanDirTracedLI(vendorAppDir, mDefParseFlags
2648                    | PackageParser.PARSE_IS_SYSTEM
2649                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2650
2651            // Collect all OEM packages.
2652            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2653            scanDirTracedLI(oemAppDir, mDefParseFlags
2654                    | PackageParser.PARSE_IS_SYSTEM
2655                    | PackageParser.PARSE_IS_SYSTEM_DIR
2656                    | PackageParser.PARSE_IS_OEM, scanFlags, 0);
2657
2658            // Prune any system packages that no longer exist.
2659            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2660            // Stub packages must either be replaced with full versions in the /data
2661            // partition or be disabled.
2662            final List<String> stubSystemApps = new ArrayList<>();
2663            if (!mOnlyCore) {
2664                // do this first before mucking with mPackages for the "expecting better" case
2665                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2666                while (pkgIterator.hasNext()) {
2667                    final PackageParser.Package pkg = pkgIterator.next();
2668                    if (pkg.isStub) {
2669                        stubSystemApps.add(pkg.packageName);
2670                    }
2671                }
2672
2673                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2674                while (psit.hasNext()) {
2675                    PackageSetting ps = psit.next();
2676
2677                    /*
2678                     * If this is not a system app, it can't be a
2679                     * disable system app.
2680                     */
2681                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2682                        continue;
2683                    }
2684
2685                    /*
2686                     * If the package is scanned, it's not erased.
2687                     */
2688                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2689                    if (scannedPkg != null) {
2690                        /*
2691                         * If the system app is both scanned and in the
2692                         * disabled packages list, then it must have been
2693                         * added via OTA. Remove it from the currently
2694                         * scanned package so the previously user-installed
2695                         * application can be scanned.
2696                         */
2697                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2698                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2699                                    + ps.name + "; removing system app.  Last known codePath="
2700                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2701                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2702                                    + scannedPkg.mVersionCode);
2703                            removePackageLI(scannedPkg, true);
2704                            mExpectingBetter.put(ps.name, ps.codePath);
2705                        }
2706
2707                        continue;
2708                    }
2709
2710                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2711                        psit.remove();
2712                        logCriticalInfo(Log.WARN, "System package " + ps.name
2713                                + " no longer exists; it's data will be wiped");
2714                        // Actual deletion of code and data will be handled by later
2715                        // reconciliation step
2716                    } else {
2717                        // we still have a disabled system package, but, it still might have
2718                        // been removed. check the code path still exists and check there's
2719                        // still a package. the latter can happen if an OTA keeps the same
2720                        // code path, but, changes the package name.
2721                        final PackageSetting disabledPs =
2722                                mSettings.getDisabledSystemPkgLPr(ps.name);
2723                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2724                                || disabledPs.pkg == null) {
2725                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2726                        }
2727                    }
2728                }
2729            }
2730
2731            //look for any incomplete package installations
2732            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2733            for (int i = 0; i < deletePkgsList.size(); i++) {
2734                // Actual deletion of code and data will be handled by later
2735                // reconciliation step
2736                final String packageName = deletePkgsList.get(i).name;
2737                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2738                synchronized (mPackages) {
2739                    mSettings.removePackageLPw(packageName);
2740                }
2741            }
2742
2743            //delete tmp files
2744            deleteTempPackageFiles();
2745
2746            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2747
2748            // Remove any shared userIDs that have no associated packages
2749            mSettings.pruneSharedUsersLPw();
2750            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2751            final int systemPackagesCount = mPackages.size();
2752            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2753                    + " ms, packageCount: " + systemPackagesCount
2754                    + " , timePerPackage: "
2755                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2756                    + " , cached: " + cachedSystemApps);
2757            if (mIsUpgrade && systemPackagesCount > 0) {
2758                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2759                        ((int) systemScanTime) / systemPackagesCount);
2760            }
2761            if (!mOnlyCore) {
2762                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2763                        SystemClock.uptimeMillis());
2764                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2765
2766                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2767                        | PackageParser.PARSE_FORWARD_LOCK,
2768                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2769
2770                // Remove disable package settings for updated system apps that were
2771                // removed via an OTA. If the update is no longer present, remove the
2772                // app completely. Otherwise, revoke their system privileges.
2773                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2774                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2775                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2776
2777                    final String msg;
2778                    if (deletedPkg == null) {
2779                        // should have found an update, but, we didn't; remove everything
2780                        msg = "Updated system package " + deletedAppName
2781                                + " no longer exists; removing its data";
2782                        // Actual deletion of code and data will be handled by later
2783                        // reconciliation step
2784                    } else {
2785                        // found an update; revoke system privileges
2786                        msg = "Updated system package + " + deletedAppName
2787                                + " no longer exists; revoking system privileges";
2788
2789                        // Don't do anything if a stub is removed from the system image. If
2790                        // we were to remove the uncompressed version from the /data partition,
2791                        // this is where it'd be done.
2792
2793                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2794                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2795                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2796                    }
2797                    logCriticalInfo(Log.WARN, msg);
2798                }
2799
2800                /*
2801                 * Make sure all system apps that we expected to appear on
2802                 * the userdata partition actually showed up. If they never
2803                 * appeared, crawl back and revive the system version.
2804                 */
2805                for (int i = 0; i < mExpectingBetter.size(); i++) {
2806                    final String packageName = mExpectingBetter.keyAt(i);
2807                    if (!mPackages.containsKey(packageName)) {
2808                        final File scanFile = mExpectingBetter.valueAt(i);
2809
2810                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2811                                + " but never showed up; reverting to system");
2812
2813                        int reparseFlags = mDefParseFlags;
2814                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2815                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2816                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2817                                    | PackageParser.PARSE_IS_PRIVILEGED;
2818                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2819                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2820                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2821                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2822                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2823                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2824                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2825                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2826                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2827                                    | PackageParser.PARSE_IS_OEM;
2828                        } else {
2829                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2830                            continue;
2831                        }
2832
2833                        mSettings.enableSystemPackageLPw(packageName);
2834
2835                        try {
2836                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2837                        } catch (PackageManagerException e) {
2838                            Slog.e(TAG, "Failed to parse original system package: "
2839                                    + e.getMessage());
2840                        }
2841                    }
2842                }
2843
2844                // Uncompress and install any stubbed system applications.
2845                // This must be done last to ensure all stubs are replaced or disabled.
2846                decompressSystemApplications(stubSystemApps, scanFlags);
2847
2848                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2849                                - cachedSystemApps;
2850
2851                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2852                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2853                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2854                        + " ms, packageCount: " + dataPackagesCount
2855                        + " , timePerPackage: "
2856                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2857                        + " , cached: " + cachedNonSystemApps);
2858                if (mIsUpgrade && dataPackagesCount > 0) {
2859                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2860                            ((int) dataScanTime) / dataPackagesCount);
2861                }
2862            }
2863            mExpectingBetter.clear();
2864
2865            // Resolve the storage manager.
2866            mStorageManagerPackage = getStorageManagerPackageName();
2867
2868            // Resolve protected action filters. Only the setup wizard is allowed to
2869            // have a high priority filter for these actions.
2870            mSetupWizardPackage = getSetupWizardPackageName();
2871            if (mProtectedFilters.size() > 0) {
2872                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2873                    Slog.i(TAG, "No setup wizard;"
2874                        + " All protected intents capped to priority 0");
2875                }
2876                for (ActivityIntentInfo filter : mProtectedFilters) {
2877                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2878                        if (DEBUG_FILTERS) {
2879                            Slog.i(TAG, "Found setup wizard;"
2880                                + " allow priority " + filter.getPriority() + ";"
2881                                + " package: " + filter.activity.info.packageName
2882                                + " activity: " + filter.activity.className
2883                                + " priority: " + filter.getPriority());
2884                        }
2885                        // skip setup wizard; allow it to keep the high priority filter
2886                        continue;
2887                    }
2888                    if (DEBUG_FILTERS) {
2889                        Slog.i(TAG, "Protected action; cap priority to 0;"
2890                                + " package: " + filter.activity.info.packageName
2891                                + " activity: " + filter.activity.className
2892                                + " origPrio: " + filter.getPriority());
2893                    }
2894                    filter.setPriority(0);
2895                }
2896            }
2897            mDeferProtectedFilters = false;
2898            mProtectedFilters.clear();
2899
2900            // Now that we know all of the shared libraries, update all clients to have
2901            // the correct library paths.
2902            updateAllSharedLibrariesLPw(null);
2903
2904            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2905                // NOTE: We ignore potential failures here during a system scan (like
2906                // the rest of the commands above) because there's precious little we
2907                // can do about it. A settings error is reported, though.
2908                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2909            }
2910
2911            // Now that we know all the packages we are keeping,
2912            // read and update their last usage times.
2913            mPackageUsage.read(mPackages);
2914            mCompilerStats.read();
2915
2916            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2917                    SystemClock.uptimeMillis());
2918            Slog.i(TAG, "Time to scan packages: "
2919                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2920                    + " seconds");
2921
2922            // If the platform SDK has changed since the last time we booted,
2923            // we need to re-grant app permission to catch any new ones that
2924            // appear.  This is really a hack, and means that apps can in some
2925            // cases get permissions that the user didn't initially explicitly
2926            // allow...  it would be nice to have some better way to handle
2927            // this situation.
2928            int updateFlags = UPDATE_PERMISSIONS_ALL;
2929            if (ver.sdkVersion != mSdkVersion) {
2930                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2931                        + mSdkVersion + "; regranting permissions for internal storage");
2932                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2933            }
2934            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2935            ver.sdkVersion = mSdkVersion;
2936
2937            // If this is the first boot or an update from pre-M, and it is a normal
2938            // boot, then we need to initialize the default preferred apps across
2939            // all defined users.
2940            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2941                for (UserInfo user : sUserManager.getUsers(true)) {
2942                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2943                    applyFactoryDefaultBrowserLPw(user.id);
2944                    primeDomainVerificationsLPw(user.id);
2945                }
2946            }
2947
2948            // Prepare storage for system user really early during boot,
2949            // since core system apps like SettingsProvider and SystemUI
2950            // can't wait for user to start
2951            final int storageFlags;
2952            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2953                storageFlags = StorageManager.FLAG_STORAGE_DE;
2954            } else {
2955                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2956            }
2957            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2958                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2959                    true /* onlyCoreApps */);
2960            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2961                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
2962                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2963                traceLog.traceBegin("AppDataFixup");
2964                try {
2965                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2966                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2967                } catch (InstallerException e) {
2968                    Slog.w(TAG, "Trouble fixing GIDs", e);
2969                }
2970                traceLog.traceEnd();
2971
2972                traceLog.traceBegin("AppDataPrepare");
2973                if (deferPackages == null || deferPackages.isEmpty()) {
2974                    return;
2975                }
2976                int count = 0;
2977                for (String pkgName : deferPackages) {
2978                    PackageParser.Package pkg = null;
2979                    synchronized (mPackages) {
2980                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2981                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2982                            pkg = ps.pkg;
2983                        }
2984                    }
2985                    if (pkg != null) {
2986                        synchronized (mInstallLock) {
2987                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2988                                    true /* maybeMigrateAppData */);
2989                        }
2990                        count++;
2991                    }
2992                }
2993                traceLog.traceEnd();
2994                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2995            }, "prepareAppData");
2996
2997            // If this is first boot after an OTA, and a normal boot, then
2998            // we need to clear code cache directories.
2999            // Note that we do *not* clear the application profiles. These remain valid
3000            // across OTAs and are used to drive profile verification (post OTA) and
3001            // profile compilation (without waiting to collect a fresh set of profiles).
3002            if (mIsUpgrade && !onlyCore) {
3003                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
3004                for (int i = 0; i < mSettings.mPackages.size(); i++) {
3005                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
3006                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
3007                        // No apps are running this early, so no need to freeze
3008                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
3009                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
3010                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
3011                    }
3012                }
3013                ver.fingerprint = Build.FINGERPRINT;
3014            }
3015
3016            checkDefaultBrowser();
3017
3018            // clear only after permissions and other defaults have been updated
3019            mExistingSystemPackages.clear();
3020            mPromoteSystemApps = false;
3021
3022            // All the changes are done during package scanning.
3023            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3024
3025            // can downgrade to reader
3026            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3027            mSettings.writeLPr();
3028            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3029            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3030                    SystemClock.uptimeMillis());
3031
3032            if (!mOnlyCore) {
3033                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3034                mRequiredInstallerPackage = getRequiredInstallerLPr();
3035                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3036                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3037                if (mIntentFilterVerifierComponent != null) {
3038                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3039                            mIntentFilterVerifierComponent);
3040                } else {
3041                    mIntentFilterVerifier = null;
3042                }
3043                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3044                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3045                        SharedLibraryInfo.VERSION_UNDEFINED);
3046                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3047                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3048                        SharedLibraryInfo.VERSION_UNDEFINED);
3049            } else {
3050                mRequiredVerifierPackage = null;
3051                mRequiredInstallerPackage = null;
3052                mRequiredUninstallerPackage = null;
3053                mIntentFilterVerifierComponent = null;
3054                mIntentFilterVerifier = null;
3055                mServicesSystemSharedLibraryPackageName = null;
3056                mSharedSystemSharedLibraryPackageName = null;
3057            }
3058
3059            mInstallerService = new PackageInstallerService(context, this);
3060            final Pair<ComponentName, String> instantAppResolverComponent =
3061                    getInstantAppResolverLPr();
3062            if (instantAppResolverComponent != null) {
3063                if (DEBUG_EPHEMERAL) {
3064                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3065                }
3066                mInstantAppResolverConnection = new EphemeralResolverConnection(
3067                        mContext, instantAppResolverComponent.first,
3068                        instantAppResolverComponent.second);
3069                mInstantAppResolverSettingsComponent =
3070                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3071            } else {
3072                mInstantAppResolverConnection = null;
3073                mInstantAppResolverSettingsComponent = null;
3074            }
3075            updateInstantAppInstallerLocked(null);
3076
3077            // Read and update the usage of dex files.
3078            // Do this at the end of PM init so that all the packages have their
3079            // data directory reconciled.
3080            // At this point we know the code paths of the packages, so we can validate
3081            // the disk file and build the internal cache.
3082            // The usage file is expected to be small so loading and verifying it
3083            // should take a fairly small time compare to the other activities (e.g. package
3084            // scanning).
3085            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3086            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3087            for (int userId : currentUserIds) {
3088                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3089            }
3090            mDexManager.load(userPackages);
3091            if (mIsUpgrade) {
3092                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3093                        (int) (SystemClock.uptimeMillis() - startTime));
3094            }
3095        } // synchronized (mPackages)
3096        } // synchronized (mInstallLock)
3097
3098        // Now after opening every single application zip, make sure they
3099        // are all flushed.  Not really needed, but keeps things nice and
3100        // tidy.
3101        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3102        Runtime.getRuntime().gc();
3103        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3104
3105        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3106        FallbackCategoryProvider.loadFallbacks();
3107        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3108
3109        // The initial scanning above does many calls into installd while
3110        // holding the mPackages lock, but we're mostly interested in yelling
3111        // once we have a booted system.
3112        mInstaller.setWarnIfHeld(mPackages);
3113
3114        // Expose private service for system components to use.
3115        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3116        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3117    }
3118
3119    /**
3120     * Uncompress and install stub applications.
3121     * <p>In order to save space on the system partition, some applications are shipped in a
3122     * compressed form. In addition the compressed bits for the full application, the
3123     * system image contains a tiny stub comprised of only the Android manifest.
3124     * <p>During the first boot, attempt to uncompress and install the full application. If
3125     * the application can't be installed for any reason, disable the stub and prevent
3126     * uncompressing the full application during future boots.
3127     * <p>In order to forcefully attempt an installation of a full application, go to app
3128     * settings and enable the application.
3129     */
3130    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3131        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3132            final String pkgName = stubSystemApps.get(i);
3133            // skip if the system package is already disabled
3134            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3135                stubSystemApps.remove(i);
3136                continue;
3137            }
3138            // skip if the package isn't installed (?!); this should never happen
3139            final PackageParser.Package pkg = mPackages.get(pkgName);
3140            if (pkg == null) {
3141                stubSystemApps.remove(i);
3142                continue;
3143            }
3144            // skip if the package has been disabled by the user
3145            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3146            if (ps != null) {
3147                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3148                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3149                    stubSystemApps.remove(i);
3150                    continue;
3151                }
3152            }
3153
3154            if (DEBUG_COMPRESSION) {
3155                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3156            }
3157
3158            // uncompress the binary to its eventual destination on /data
3159            final File scanFile = decompressPackage(pkg);
3160            if (scanFile == null) {
3161                continue;
3162            }
3163
3164            // install the package to replace the stub on /system
3165            try {
3166                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3167                removePackageLI(pkg, true /*chatty*/);
3168                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3169                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3170                        UserHandle.USER_SYSTEM, "android");
3171                stubSystemApps.remove(i);
3172                continue;
3173            } catch (PackageManagerException e) {
3174                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3175            }
3176
3177            // any failed attempt to install the package will be cleaned up later
3178        }
3179
3180        // disable any stub still left; these failed to install the full application
3181        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3182            final String pkgName = stubSystemApps.get(i);
3183            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3184            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3185                    UserHandle.USER_SYSTEM, "android");
3186            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3187        }
3188    }
3189
3190    private int decompressFile(File srcFile, File dstFile) throws ErrnoException {
3191        if (DEBUG_COMPRESSION) {
3192            Slog.i(TAG, "Decompress file"
3193                    + "; src: " + srcFile.getAbsolutePath()
3194                    + ", dst: " + dstFile.getAbsolutePath());
3195        }
3196        try (
3197                InputStream fileIn = new GZIPInputStream(new FileInputStream(srcFile));
3198                OutputStream fileOut = new FileOutputStream(dstFile, false /*append*/);
3199        ) {
3200            Streams.copy(fileIn, fileOut);
3201            Os.chmod(dstFile.getAbsolutePath(), 0644);
3202            return PackageManager.INSTALL_SUCCEEDED;
3203        } catch (IOException e) {
3204            logCriticalInfo(Log.ERROR, "Failed to decompress file"
3205                    + "; src: " + srcFile.getAbsolutePath()
3206                    + ", dst: " + dstFile.getAbsolutePath());
3207        }
3208        return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3209    }
3210
3211    private File[] getCompressedFiles(String codePath) {
3212        final File stubCodePath = new File(codePath);
3213        final String stubName = stubCodePath.getName();
3214
3215        // The layout of a compressed package on a given partition is as follows :
3216        //
3217        // Compressed artifacts:
3218        //
3219        // /partition/ModuleName/foo.gz
3220        // /partation/ModuleName/bar.gz
3221        //
3222        // Stub artifact:
3223        //
3224        // /partition/ModuleName-Stub/ModuleName-Stub.apk
3225        //
3226        // In other words, stub is on the same partition as the compressed artifacts
3227        // and in a directory that's suffixed with "-Stub".
3228        int idx = stubName.lastIndexOf(STUB_SUFFIX);
3229        if (idx < 0 || (stubName.length() != (idx + STUB_SUFFIX.length()))) {
3230            return null;
3231        }
3232
3233        final File stubParentDir = stubCodePath.getParentFile();
3234        if (stubParentDir == null) {
3235            Slog.e(TAG, "Unable to determine stub parent dir for codePath: " + codePath);
3236            return null;
3237        }
3238
3239        final File compressedPath = new File(stubParentDir, stubName.substring(0, idx));
3240        final File[] files = compressedPath.listFiles(new FilenameFilter() {
3241            @Override
3242            public boolean accept(File dir, String name) {
3243                return name.toLowerCase().endsWith(COMPRESSED_EXTENSION);
3244            }
3245        });
3246
3247        if (DEBUG_COMPRESSION && files != null && files.length > 0) {
3248            Slog.i(TAG, "getCompressedFiles[" + codePath + "]: " + Arrays.toString(files));
3249        }
3250
3251        return files;
3252    }
3253
3254    private boolean compressedFileExists(String codePath) {
3255        final File[] compressedFiles = getCompressedFiles(codePath);
3256        return compressedFiles != null && compressedFiles.length > 0;
3257    }
3258
3259    /**
3260     * Decompresses the given package on the system image onto
3261     * the /data partition.
3262     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3263     */
3264    private File decompressPackage(PackageParser.Package pkg) {
3265        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3266        if (compressedFiles == null || compressedFiles.length == 0) {
3267            if (DEBUG_COMPRESSION) {
3268                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3269            }
3270            return null;
3271        }
3272        final File dstCodePath =
3273                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3274        int ret = PackageManager.INSTALL_SUCCEEDED;
3275        try {
3276            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3277            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3278            for (File srcFile : compressedFiles) {
3279                final String srcFileName = srcFile.getName();
3280                final String dstFileName = srcFileName.substring(
3281                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3282                final File dstFile = new File(dstCodePath, dstFileName);
3283                ret = decompressFile(srcFile, dstFile);
3284                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3285                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3286                            + "; pkg: " + pkg.packageName
3287                            + ", file: " + dstFileName);
3288                    break;
3289                }
3290            }
3291        } catch (ErrnoException e) {
3292            logCriticalInfo(Log.ERROR, "Failed to decompress"
3293                    + "; pkg: " + pkg.packageName
3294                    + ", err: " + e.errno);
3295        }
3296        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3297            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3298            NativeLibraryHelper.Handle handle = null;
3299            try {
3300                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3301                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3302                        null /*abiOverride*/);
3303            } catch (IOException e) {
3304                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3305                        + "; pkg: " + pkg.packageName);
3306                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3307            } finally {
3308                IoUtils.closeQuietly(handle);
3309            }
3310        }
3311        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3312            if (dstCodePath == null || !dstCodePath.exists()) {
3313                return null;
3314            }
3315            removeCodePathLI(dstCodePath);
3316            return null;
3317        }
3318
3319        // If we have a profile for a compressed APK, copy it to the reference location.
3320        // Since the package is the stub one, remove the stub suffix to get the normal package and
3321        // APK name.
3322        File profileFile = new File(getPrebuildProfilePath(pkg).replace(STUB_SUFFIX, ""));
3323        if (profileFile.exists()) {
3324            try {
3325                // We could also do this lazily before calling dexopt in
3326                // PackageDexOptimizer to prevent this happening on first boot. The issue
3327                // is that we don't have a good way to say "do this only once".
3328                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
3329                        pkg.applicationInfo.uid, pkg.packageName)) {
3330                    Log.e(TAG, "decompressPackage failed to copy system profile!");
3331                }
3332            } catch (Exception e) {
3333                Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ", e);
3334            }
3335        }
3336        return dstCodePath;
3337    }
3338
3339    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3340        // we're only interested in updating the installer appliction when 1) it's not
3341        // already set or 2) the modified package is the installer
3342        if (mInstantAppInstallerActivity != null
3343                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3344                        .equals(modifiedPackage)) {
3345            return;
3346        }
3347        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3348    }
3349
3350    private static File preparePackageParserCache(boolean isUpgrade) {
3351        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3352            return null;
3353        }
3354
3355        // Disable package parsing on eng builds to allow for faster incremental development.
3356        if (Build.IS_ENG) {
3357            return null;
3358        }
3359
3360        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3361            Slog.i(TAG, "Disabling package parser cache due to system property.");
3362            return null;
3363        }
3364
3365        // The base directory for the package parser cache lives under /data/system/.
3366        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3367                "package_cache");
3368        if (cacheBaseDir == null) {
3369            return null;
3370        }
3371
3372        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3373        // This also serves to "GC" unused entries when the package cache version changes (which
3374        // can only happen during upgrades).
3375        if (isUpgrade) {
3376            FileUtils.deleteContents(cacheBaseDir);
3377        }
3378
3379
3380        // Return the versioned package cache directory. This is something like
3381        // "/data/system/package_cache/1"
3382        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3383
3384        // The following is a workaround to aid development on non-numbered userdebug
3385        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3386        // the system partition is newer.
3387        //
3388        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3389        // that starts with "eng." to signify that this is an engineering build and not
3390        // destined for release.
3391        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3392            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3393
3394            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3395            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3396            // in general and should not be used for production changes. In this specific case,
3397            // we know that they will work.
3398            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3399            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3400                FileUtils.deleteContents(cacheBaseDir);
3401                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3402            }
3403        }
3404
3405        return cacheDir;
3406    }
3407
3408    @Override
3409    public boolean isFirstBoot() {
3410        // allow instant applications
3411        return mFirstBoot;
3412    }
3413
3414    @Override
3415    public boolean isOnlyCoreApps() {
3416        // allow instant applications
3417        return mOnlyCore;
3418    }
3419
3420    @Override
3421    public boolean isUpgrade() {
3422        // allow instant applications
3423        return mIsUpgrade;
3424    }
3425
3426    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3427        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3428
3429        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3430                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3431                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3432        if (matches.size() == 1) {
3433            return matches.get(0).getComponentInfo().packageName;
3434        } else if (matches.size() == 0) {
3435            Log.e(TAG, "There should probably be a verifier, but, none were found");
3436            return null;
3437        }
3438        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3439    }
3440
3441    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3442        synchronized (mPackages) {
3443            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3444            if (libraryEntry == null) {
3445                throw new IllegalStateException("Missing required shared library:" + name);
3446            }
3447            return libraryEntry.apk;
3448        }
3449    }
3450
3451    private @NonNull String getRequiredInstallerLPr() {
3452        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3453        intent.addCategory(Intent.CATEGORY_DEFAULT);
3454        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3455
3456        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3457                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3458                UserHandle.USER_SYSTEM);
3459        if (matches.size() == 1) {
3460            ResolveInfo resolveInfo = matches.get(0);
3461            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3462                throw new RuntimeException("The installer must be a privileged app");
3463            }
3464            return matches.get(0).getComponentInfo().packageName;
3465        } else {
3466            throw new RuntimeException("There must be exactly one installer; found " + matches);
3467        }
3468    }
3469
3470    private @NonNull String getRequiredUninstallerLPr() {
3471        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3472        intent.addCategory(Intent.CATEGORY_DEFAULT);
3473        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3474
3475        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3476                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3477                UserHandle.USER_SYSTEM);
3478        if (resolveInfo == null ||
3479                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3480            throw new RuntimeException("There must be exactly one uninstaller; found "
3481                    + resolveInfo);
3482        }
3483        return resolveInfo.getComponentInfo().packageName;
3484    }
3485
3486    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3487        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3488
3489        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3490                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3491                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3492        ResolveInfo best = null;
3493        final int N = matches.size();
3494        for (int i = 0; i < N; i++) {
3495            final ResolveInfo cur = matches.get(i);
3496            final String packageName = cur.getComponentInfo().packageName;
3497            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3498                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3499                continue;
3500            }
3501
3502            if (best == null || cur.priority > best.priority) {
3503                best = cur;
3504            }
3505        }
3506
3507        if (best != null) {
3508            return best.getComponentInfo().getComponentName();
3509        }
3510        Slog.w(TAG, "Intent filter verifier not found");
3511        return null;
3512    }
3513
3514    @Override
3515    public @Nullable ComponentName getInstantAppResolverComponent() {
3516        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3517            return null;
3518        }
3519        synchronized (mPackages) {
3520            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3521            if (instantAppResolver == null) {
3522                return null;
3523            }
3524            return instantAppResolver.first;
3525        }
3526    }
3527
3528    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3529        final String[] packageArray =
3530                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3531        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3532            if (DEBUG_EPHEMERAL) {
3533                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3534            }
3535            return null;
3536        }
3537
3538        final int callingUid = Binder.getCallingUid();
3539        final int resolveFlags =
3540                MATCH_DIRECT_BOOT_AWARE
3541                | MATCH_DIRECT_BOOT_UNAWARE
3542                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3543        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3544        final Intent resolverIntent = new Intent(actionName);
3545        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3546                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3547        // temporarily look for the old action
3548        if (resolvers.size() == 0) {
3549            if (DEBUG_EPHEMERAL) {
3550                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3551            }
3552            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3553            resolverIntent.setAction(actionName);
3554            resolvers = queryIntentServicesInternal(resolverIntent, null,
3555                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3556        }
3557        final int N = resolvers.size();
3558        if (N == 0) {
3559            if (DEBUG_EPHEMERAL) {
3560                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3561            }
3562            return null;
3563        }
3564
3565        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3566        for (int i = 0; i < N; i++) {
3567            final ResolveInfo info = resolvers.get(i);
3568
3569            if (info.serviceInfo == null) {
3570                continue;
3571            }
3572
3573            final String packageName = info.serviceInfo.packageName;
3574            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3575                if (DEBUG_EPHEMERAL) {
3576                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3577                            + " pkg: " + packageName + ", info:" + info);
3578                }
3579                continue;
3580            }
3581
3582            if (DEBUG_EPHEMERAL) {
3583                Slog.v(TAG, "Ephemeral resolver found;"
3584                        + " pkg: " + packageName + ", info:" + info);
3585            }
3586            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3587        }
3588        if (DEBUG_EPHEMERAL) {
3589            Slog.v(TAG, "Ephemeral resolver NOT found");
3590        }
3591        return null;
3592    }
3593
3594    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3595        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3596        intent.addCategory(Intent.CATEGORY_DEFAULT);
3597        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3598
3599        final int resolveFlags =
3600                MATCH_DIRECT_BOOT_AWARE
3601                | MATCH_DIRECT_BOOT_UNAWARE
3602                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3603        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3604                resolveFlags, UserHandle.USER_SYSTEM);
3605        // temporarily look for the old action
3606        if (matches.isEmpty()) {
3607            if (DEBUG_EPHEMERAL) {
3608                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3609            }
3610            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3611            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3612                    resolveFlags, UserHandle.USER_SYSTEM);
3613        }
3614        Iterator<ResolveInfo> iter = matches.iterator();
3615        while (iter.hasNext()) {
3616            final ResolveInfo rInfo = iter.next();
3617            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3618            if (ps != null) {
3619                final PermissionsState permissionsState = ps.getPermissionsState();
3620                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3621                    continue;
3622                }
3623            }
3624            iter.remove();
3625        }
3626        if (matches.size() == 0) {
3627            return null;
3628        } else if (matches.size() == 1) {
3629            return (ActivityInfo) matches.get(0).getComponentInfo();
3630        } else {
3631            throw new RuntimeException(
3632                    "There must be at most one ephemeral installer; found " + matches);
3633        }
3634    }
3635
3636    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3637            @NonNull ComponentName resolver) {
3638        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3639                .addCategory(Intent.CATEGORY_DEFAULT)
3640                .setPackage(resolver.getPackageName());
3641        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3642        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3643                UserHandle.USER_SYSTEM);
3644        // temporarily look for the old action
3645        if (matches.isEmpty()) {
3646            if (DEBUG_EPHEMERAL) {
3647                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3648            }
3649            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3650            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3651                    UserHandle.USER_SYSTEM);
3652        }
3653        if (matches.isEmpty()) {
3654            return null;
3655        }
3656        return matches.get(0).getComponentInfo().getComponentName();
3657    }
3658
3659    private void primeDomainVerificationsLPw(int userId) {
3660        if (DEBUG_DOMAIN_VERIFICATION) {
3661            Slog.d(TAG, "Priming domain verifications in user " + userId);
3662        }
3663
3664        SystemConfig systemConfig = SystemConfig.getInstance();
3665        ArraySet<String> packages = systemConfig.getLinkedApps();
3666
3667        for (String packageName : packages) {
3668            PackageParser.Package pkg = mPackages.get(packageName);
3669            if (pkg != null) {
3670                if (!pkg.isSystemApp()) {
3671                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3672                    continue;
3673                }
3674
3675                ArraySet<String> domains = null;
3676                for (PackageParser.Activity a : pkg.activities) {
3677                    for (ActivityIntentInfo filter : a.intents) {
3678                        if (hasValidDomains(filter)) {
3679                            if (domains == null) {
3680                                domains = new ArraySet<String>();
3681                            }
3682                            domains.addAll(filter.getHostsList());
3683                        }
3684                    }
3685                }
3686
3687                if (domains != null && domains.size() > 0) {
3688                    if (DEBUG_DOMAIN_VERIFICATION) {
3689                        Slog.v(TAG, "      + " + packageName);
3690                    }
3691                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3692                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3693                    // and then 'always' in the per-user state actually used for intent resolution.
3694                    final IntentFilterVerificationInfo ivi;
3695                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3696                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3697                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3698                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3699                } else {
3700                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3701                            + "' does not handle web links");
3702                }
3703            } else {
3704                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3705            }
3706        }
3707
3708        scheduleWritePackageRestrictionsLocked(userId);
3709        scheduleWriteSettingsLocked();
3710    }
3711
3712    private void applyFactoryDefaultBrowserLPw(int userId) {
3713        // The default browser app's package name is stored in a string resource,
3714        // with a product-specific overlay used for vendor customization.
3715        String browserPkg = mContext.getResources().getString(
3716                com.android.internal.R.string.default_browser);
3717        if (!TextUtils.isEmpty(browserPkg)) {
3718            // non-empty string => required to be a known package
3719            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3720            if (ps == null) {
3721                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3722                browserPkg = null;
3723            } else {
3724                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3725            }
3726        }
3727
3728        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3729        // default.  If there's more than one, just leave everything alone.
3730        if (browserPkg == null) {
3731            calculateDefaultBrowserLPw(userId);
3732        }
3733    }
3734
3735    private void calculateDefaultBrowserLPw(int userId) {
3736        List<String> allBrowsers = resolveAllBrowserApps(userId);
3737        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3738        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3739    }
3740
3741    private List<String> resolveAllBrowserApps(int userId) {
3742        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3743        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3744                PackageManager.MATCH_ALL, userId);
3745
3746        final int count = list.size();
3747        List<String> result = new ArrayList<String>(count);
3748        for (int i=0; i<count; i++) {
3749            ResolveInfo info = list.get(i);
3750            if (info.activityInfo == null
3751                    || !info.handleAllWebDataURI
3752                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3753                    || result.contains(info.activityInfo.packageName)) {
3754                continue;
3755            }
3756            result.add(info.activityInfo.packageName);
3757        }
3758
3759        return result;
3760    }
3761
3762    private boolean packageIsBrowser(String packageName, int userId) {
3763        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3764                PackageManager.MATCH_ALL, userId);
3765        final int N = list.size();
3766        for (int i = 0; i < N; i++) {
3767            ResolveInfo info = list.get(i);
3768            if (packageName.equals(info.activityInfo.packageName)) {
3769                return true;
3770            }
3771        }
3772        return false;
3773    }
3774
3775    private void checkDefaultBrowser() {
3776        final int myUserId = UserHandle.myUserId();
3777        final String packageName = getDefaultBrowserPackageName(myUserId);
3778        if (packageName != null) {
3779            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3780            if (info == null) {
3781                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3782                synchronized (mPackages) {
3783                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3784                }
3785            }
3786        }
3787    }
3788
3789    @Override
3790    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3791            throws RemoteException {
3792        try {
3793            return super.onTransact(code, data, reply, flags);
3794        } catch (RuntimeException e) {
3795            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3796                Slog.wtf(TAG, "Package Manager Crash", e);
3797            }
3798            throw e;
3799        }
3800    }
3801
3802    static int[] appendInts(int[] cur, int[] add) {
3803        if (add == null) return cur;
3804        if (cur == null) return add;
3805        final int N = add.length;
3806        for (int i=0; i<N; i++) {
3807            cur = appendInt(cur, add[i]);
3808        }
3809        return cur;
3810    }
3811
3812    /**
3813     * Returns whether or not a full application can see an instant application.
3814     * <p>
3815     * Currently, there are three cases in which this can occur:
3816     * <ol>
3817     * <li>The calling application is a "special" process. The special
3818     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3819     *     and {@code 0}</li>
3820     * <li>The calling application has the permission
3821     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3822     * <li>The calling application is the default launcher on the
3823     *     system partition.</li>
3824     * </ol>
3825     */
3826    private boolean canViewInstantApps(int callingUid, int userId) {
3827        if (callingUid == Process.SYSTEM_UID
3828                || callingUid == Process.SHELL_UID
3829                || callingUid == Process.ROOT_UID) {
3830            return true;
3831        }
3832        if (mContext.checkCallingOrSelfPermission(
3833                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3834            return true;
3835        }
3836        if (mContext.checkCallingOrSelfPermission(
3837                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3838            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3839            if (homeComponent != null
3840                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3841                return true;
3842            }
3843        }
3844        return false;
3845    }
3846
3847    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3848        if (!sUserManager.exists(userId)) return null;
3849        if (ps == null) {
3850            return null;
3851        }
3852        PackageParser.Package p = ps.pkg;
3853        if (p == null) {
3854            return null;
3855        }
3856        final int callingUid = Binder.getCallingUid();
3857        // Filter out ephemeral app metadata:
3858        //   * The system/shell/root can see metadata for any app
3859        //   * An installed app can see metadata for 1) other installed apps
3860        //     and 2) ephemeral apps that have explicitly interacted with it
3861        //   * Ephemeral apps can only see their own data and exposed installed apps
3862        //   * Holding a signature permission allows seeing instant apps
3863        if (filterAppAccessLPr(ps, callingUid, userId)) {
3864            return null;
3865        }
3866
3867        final PermissionsState permissionsState = ps.getPermissionsState();
3868
3869        // Compute GIDs only if requested
3870        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3871                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3872        // Compute granted permissions only if package has requested permissions
3873        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3874                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3875        final PackageUserState state = ps.readUserState(userId);
3876
3877        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3878                && ps.isSystem()) {
3879            flags |= MATCH_ANY_USER;
3880        }
3881
3882        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3883                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3884
3885        if (packageInfo == null) {
3886            return null;
3887        }
3888
3889        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3890                resolveExternalPackageNameLPr(p);
3891
3892        return packageInfo;
3893    }
3894
3895    @Override
3896    public void checkPackageStartable(String packageName, int userId) {
3897        final int callingUid = Binder.getCallingUid();
3898        if (getInstantAppPackageName(callingUid) != null) {
3899            throw new SecurityException("Instant applications don't have access to this method");
3900        }
3901        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3902        synchronized (mPackages) {
3903            final PackageSetting ps = mSettings.mPackages.get(packageName);
3904            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3905                throw new SecurityException("Package " + packageName + " was not found!");
3906            }
3907
3908            if (!ps.getInstalled(userId)) {
3909                throw new SecurityException(
3910                        "Package " + packageName + " was not installed for user " + userId + "!");
3911            }
3912
3913            if (mSafeMode && !ps.isSystem()) {
3914                throw new SecurityException("Package " + packageName + " not a system app!");
3915            }
3916
3917            if (mFrozenPackages.contains(packageName)) {
3918                throw new SecurityException("Package " + packageName + " is currently frozen!");
3919            }
3920
3921            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3922                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3923            }
3924        }
3925    }
3926
3927    @Override
3928    public boolean isPackageAvailable(String packageName, int userId) {
3929        if (!sUserManager.exists(userId)) return false;
3930        final int callingUid = Binder.getCallingUid();
3931        enforceCrossUserPermission(callingUid, userId,
3932                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3933        synchronized (mPackages) {
3934            PackageParser.Package p = mPackages.get(packageName);
3935            if (p != null) {
3936                final PackageSetting ps = (PackageSetting) p.mExtras;
3937                if (filterAppAccessLPr(ps, callingUid, userId)) {
3938                    return false;
3939                }
3940                if (ps != null) {
3941                    final PackageUserState state = ps.readUserState(userId);
3942                    if (state != null) {
3943                        return PackageParser.isAvailable(state);
3944                    }
3945                }
3946            }
3947        }
3948        return false;
3949    }
3950
3951    @Override
3952    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3953        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3954                flags, Binder.getCallingUid(), userId);
3955    }
3956
3957    @Override
3958    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3959            int flags, int userId) {
3960        return getPackageInfoInternal(versionedPackage.getPackageName(),
3961                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3962    }
3963
3964    /**
3965     * Important: The provided filterCallingUid is used exclusively to filter out packages
3966     * that can be seen based on user state. It's typically the original caller uid prior
3967     * to clearing. Because it can only be provided by trusted code, it's value can be
3968     * trusted and will be used as-is; unlike userId which will be validated by this method.
3969     */
3970    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3971            int flags, int filterCallingUid, int userId) {
3972        if (!sUserManager.exists(userId)) return null;
3973        flags = updateFlagsForPackage(flags, userId, packageName);
3974        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3975                false /* requireFullPermission */, false /* checkShell */, "get package info");
3976
3977        // reader
3978        synchronized (mPackages) {
3979            // Normalize package name to handle renamed packages and static libs
3980            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3981
3982            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3983            if (matchFactoryOnly) {
3984                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3985                if (ps != null) {
3986                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3987                        return null;
3988                    }
3989                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3990                        return null;
3991                    }
3992                    return generatePackageInfo(ps, flags, userId);
3993                }
3994            }
3995
3996            PackageParser.Package p = mPackages.get(packageName);
3997            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3998                return null;
3999            }
4000            if (DEBUG_PACKAGE_INFO)
4001                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
4002            if (p != null) {
4003                final PackageSetting ps = (PackageSetting) p.mExtras;
4004                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4005                    return null;
4006                }
4007                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
4008                    return null;
4009                }
4010                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
4011            }
4012            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
4013                final PackageSetting ps = mSettings.mPackages.get(packageName);
4014                if (ps == null) return null;
4015                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4016                    return null;
4017                }
4018                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4019                    return null;
4020                }
4021                return generatePackageInfo(ps, flags, userId);
4022            }
4023        }
4024        return null;
4025    }
4026
4027    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
4028        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
4029            return true;
4030        }
4031        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
4032            return true;
4033        }
4034        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
4035            return true;
4036        }
4037        return false;
4038    }
4039
4040    private boolean isComponentVisibleToInstantApp(
4041            @Nullable ComponentName component, @ComponentType int type) {
4042        if (type == TYPE_ACTIVITY) {
4043            final PackageParser.Activity activity = mActivities.mActivities.get(component);
4044            return activity != null
4045                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4046                    : false;
4047        } else if (type == TYPE_RECEIVER) {
4048            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
4049            return activity != null
4050                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4051                    : false;
4052        } else if (type == TYPE_SERVICE) {
4053            final PackageParser.Service service = mServices.mServices.get(component);
4054            return service != null
4055                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4056                    : false;
4057        } else if (type == TYPE_PROVIDER) {
4058            final PackageParser.Provider provider = mProviders.mProviders.get(component);
4059            return provider != null
4060                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4061                    : false;
4062        } else if (type == TYPE_UNKNOWN) {
4063            return isComponentVisibleToInstantApp(component);
4064        }
4065        return false;
4066    }
4067
4068    /**
4069     * Returns whether or not access to the application should be filtered.
4070     * <p>
4071     * Access may be limited based upon whether the calling or target applications
4072     * are instant applications.
4073     *
4074     * @see #canAccessInstantApps(int)
4075     */
4076    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4077            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4078        // if we're in an isolated process, get the real calling UID
4079        if (Process.isIsolated(callingUid)) {
4080            callingUid = mIsolatedOwners.get(callingUid);
4081        }
4082        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4083        final boolean callerIsInstantApp = instantAppPkgName != null;
4084        if (ps == null) {
4085            if (callerIsInstantApp) {
4086                // pretend the application exists, but, needs to be filtered
4087                return true;
4088            }
4089            return false;
4090        }
4091        // if the target and caller are the same application, don't filter
4092        if (isCallerSameApp(ps.name, callingUid)) {
4093            return false;
4094        }
4095        if (callerIsInstantApp) {
4096            // request for a specific component; if it hasn't been explicitly exposed, filter
4097            if (component != null) {
4098                return !isComponentVisibleToInstantApp(component, componentType);
4099            }
4100            // request for application; if no components have been explicitly exposed, filter
4101            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
4102        }
4103        if (ps.getInstantApp(userId)) {
4104            // caller can see all components of all instant applications, don't filter
4105            if (canViewInstantApps(callingUid, userId)) {
4106                return false;
4107            }
4108            // request for a specific instant application component, filter
4109            if (component != null) {
4110                return true;
4111            }
4112            // request for an instant application; if the caller hasn't been granted access, filter
4113            return !mInstantAppRegistry.isInstantAccessGranted(
4114                    userId, UserHandle.getAppId(callingUid), ps.appId);
4115        }
4116        return false;
4117    }
4118
4119    /**
4120     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4121     */
4122    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4123        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4124    }
4125
4126    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4127            int flags) {
4128        // Callers can access only the libs they depend on, otherwise they need to explicitly
4129        // ask for the shared libraries given the caller is allowed to access all static libs.
4130        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4131            // System/shell/root get to see all static libs
4132            final int appId = UserHandle.getAppId(uid);
4133            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4134                    || appId == Process.ROOT_UID) {
4135                return false;
4136            }
4137        }
4138
4139        // No package means no static lib as it is always on internal storage
4140        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4141            return false;
4142        }
4143
4144        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4145                ps.pkg.staticSharedLibVersion);
4146        if (libEntry == null) {
4147            return false;
4148        }
4149
4150        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4151        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4152        if (uidPackageNames == null) {
4153            return true;
4154        }
4155
4156        for (String uidPackageName : uidPackageNames) {
4157            if (ps.name.equals(uidPackageName)) {
4158                return false;
4159            }
4160            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4161            if (uidPs != null) {
4162                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4163                        libEntry.info.getName());
4164                if (index < 0) {
4165                    continue;
4166                }
4167                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
4168                    return false;
4169                }
4170            }
4171        }
4172        return true;
4173    }
4174
4175    @Override
4176    public String[] currentToCanonicalPackageNames(String[] names) {
4177        final int callingUid = Binder.getCallingUid();
4178        if (getInstantAppPackageName(callingUid) != null) {
4179            return names;
4180        }
4181        final String[] out = new String[names.length];
4182        // reader
4183        synchronized (mPackages) {
4184            final int callingUserId = UserHandle.getUserId(callingUid);
4185            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4186            for (int i=names.length-1; i>=0; i--) {
4187                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4188                boolean translateName = false;
4189                if (ps != null && ps.realName != null) {
4190                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4191                    translateName = !targetIsInstantApp
4192                            || canViewInstantApps
4193                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4194                                    UserHandle.getAppId(callingUid), ps.appId);
4195                }
4196                out[i] = translateName ? ps.realName : names[i];
4197            }
4198        }
4199        return out;
4200    }
4201
4202    @Override
4203    public String[] canonicalToCurrentPackageNames(String[] names) {
4204        final int callingUid = Binder.getCallingUid();
4205        if (getInstantAppPackageName(callingUid) != null) {
4206            return names;
4207        }
4208        final String[] out = new String[names.length];
4209        // reader
4210        synchronized (mPackages) {
4211            final int callingUserId = UserHandle.getUserId(callingUid);
4212            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4213            for (int i=names.length-1; i>=0; i--) {
4214                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4215                boolean translateName = false;
4216                if (cur != null) {
4217                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4218                    final boolean targetIsInstantApp =
4219                            ps != null && ps.getInstantApp(callingUserId);
4220                    translateName = !targetIsInstantApp
4221                            || canViewInstantApps
4222                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4223                                    UserHandle.getAppId(callingUid), ps.appId);
4224                }
4225                out[i] = translateName ? cur : names[i];
4226            }
4227        }
4228        return out;
4229    }
4230
4231    @Override
4232    public int getPackageUid(String packageName, int flags, int userId) {
4233        if (!sUserManager.exists(userId)) return -1;
4234        final int callingUid = Binder.getCallingUid();
4235        flags = updateFlagsForPackage(flags, userId, packageName);
4236        enforceCrossUserPermission(callingUid, userId,
4237                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4238
4239        // reader
4240        synchronized (mPackages) {
4241            final PackageParser.Package p = mPackages.get(packageName);
4242            if (p != null && p.isMatch(flags)) {
4243                PackageSetting ps = (PackageSetting) p.mExtras;
4244                if (filterAppAccessLPr(ps, callingUid, userId)) {
4245                    return -1;
4246                }
4247                return UserHandle.getUid(userId, p.applicationInfo.uid);
4248            }
4249            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4250                final PackageSetting ps = mSettings.mPackages.get(packageName);
4251                if (ps != null && ps.isMatch(flags)
4252                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4253                    return UserHandle.getUid(userId, ps.appId);
4254                }
4255            }
4256        }
4257
4258        return -1;
4259    }
4260
4261    @Override
4262    public int[] getPackageGids(String packageName, int flags, int userId) {
4263        if (!sUserManager.exists(userId)) return null;
4264        final int callingUid = Binder.getCallingUid();
4265        flags = updateFlagsForPackage(flags, userId, packageName);
4266        enforceCrossUserPermission(callingUid, userId,
4267                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4268
4269        // reader
4270        synchronized (mPackages) {
4271            final PackageParser.Package p = mPackages.get(packageName);
4272            if (p != null && p.isMatch(flags)) {
4273                PackageSetting ps = (PackageSetting) p.mExtras;
4274                if (filterAppAccessLPr(ps, callingUid, userId)) {
4275                    return null;
4276                }
4277                // TODO: Shouldn't this be checking for package installed state for userId and
4278                // return null?
4279                return ps.getPermissionsState().computeGids(userId);
4280            }
4281            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4282                final PackageSetting ps = mSettings.mPackages.get(packageName);
4283                if (ps != null && ps.isMatch(flags)
4284                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4285                    return ps.getPermissionsState().computeGids(userId);
4286                }
4287            }
4288        }
4289
4290        return null;
4291    }
4292
4293    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
4294        if (bp.perm != null) {
4295            return PackageParser.generatePermissionInfo(bp.perm, flags);
4296        }
4297        PermissionInfo pi = new PermissionInfo();
4298        pi.name = bp.name;
4299        pi.packageName = bp.sourcePackage;
4300        pi.nonLocalizedLabel = bp.name;
4301        pi.protectionLevel = bp.protectionLevel;
4302        return pi;
4303    }
4304
4305    @Override
4306    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4307        final int callingUid = Binder.getCallingUid();
4308        if (getInstantAppPackageName(callingUid) != null) {
4309            return null;
4310        }
4311        // reader
4312        synchronized (mPackages) {
4313            final BasePermission p = mSettings.mPermissions.get(name);
4314            if (p == null) {
4315                return null;
4316            }
4317            // If the caller is an app that targets pre 26 SDK drop protection flags.
4318            PermissionInfo permissionInfo = generatePermissionInfo(p, flags);
4319            if (permissionInfo != null) {
4320                final int protectionLevel = adjustPermissionProtectionFlagsLPr(
4321                        permissionInfo.protectionLevel, packageName, callingUid);
4322                if (permissionInfo.protectionLevel != protectionLevel) {
4323                    // If we return different protection level, don't use the cached info
4324                    if (p.perm != null && p.perm.info == permissionInfo) {
4325                        permissionInfo = new PermissionInfo(permissionInfo);
4326                    }
4327                    permissionInfo.protectionLevel = protectionLevel;
4328                }
4329            }
4330            return permissionInfo;
4331        }
4332    }
4333
4334    private int adjustPermissionProtectionFlagsLPr(int protectionLevel,
4335            String packageName, int uid) {
4336        // Signature permission flags area always reported
4337        final int protectionLevelMasked = protectionLevel
4338                & (PermissionInfo.PROTECTION_NORMAL
4339                | PermissionInfo.PROTECTION_DANGEROUS
4340                | PermissionInfo.PROTECTION_SIGNATURE);
4341        if (protectionLevelMasked == PermissionInfo.PROTECTION_SIGNATURE) {
4342            return protectionLevel;
4343        }
4344
4345        // System sees all flags.
4346        final int appId = UserHandle.getAppId(uid);
4347        if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID
4348                || appId == Process.SHELL_UID) {
4349            return protectionLevel;
4350        }
4351
4352        // Normalize package name to handle renamed packages and static libs
4353        packageName = resolveInternalPackageNameLPr(packageName,
4354                PackageManager.VERSION_CODE_HIGHEST);
4355
4356        // Apps that target O see flags for all protection levels.
4357        final PackageSetting ps = mSettings.mPackages.get(packageName);
4358        if (ps == null) {
4359            return protectionLevel;
4360        }
4361        if (ps.appId != appId) {
4362            return protectionLevel;
4363        }
4364
4365        final PackageParser.Package pkg = mPackages.get(packageName);
4366        if (pkg == null) {
4367            return protectionLevel;
4368        }
4369        if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
4370            return protectionLevelMasked;
4371        }
4372
4373        return protectionLevel;
4374    }
4375
4376    @Override
4377    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
4378            int flags) {
4379        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4380            return null;
4381        }
4382        // reader
4383        synchronized (mPackages) {
4384            if (group != null && !mPermissionGroups.containsKey(group)) {
4385                // This is thrown as NameNotFoundException
4386                return null;
4387            }
4388
4389            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4390            for (BasePermission p : mSettings.mPermissions.values()) {
4391                if (group == null) {
4392                    if (p.perm == null || p.perm.info.group == null) {
4393                        out.add(generatePermissionInfo(p, flags));
4394                    }
4395                } else {
4396                    if (p.perm != null && group.equals(p.perm.info.group)) {
4397                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
4398                    }
4399                }
4400            }
4401            return new ParceledListSlice<>(out);
4402        }
4403    }
4404
4405    @Override
4406    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4407        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4408            return null;
4409        }
4410        // reader
4411        synchronized (mPackages) {
4412            return PackageParser.generatePermissionGroupInfo(
4413                    mPermissionGroups.get(name), flags);
4414        }
4415    }
4416
4417    @Override
4418    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4419        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4420            return ParceledListSlice.emptyList();
4421        }
4422        // reader
4423        synchronized (mPackages) {
4424            final int N = mPermissionGroups.size();
4425            ArrayList<PermissionGroupInfo> out
4426                    = new ArrayList<PermissionGroupInfo>(N);
4427            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4428                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4429            }
4430            return new ParceledListSlice<>(out);
4431        }
4432    }
4433
4434    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4435            int filterCallingUid, int userId) {
4436        if (!sUserManager.exists(userId)) return null;
4437        PackageSetting ps = mSettings.mPackages.get(packageName);
4438        if (ps != null) {
4439            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4440                return null;
4441            }
4442            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4443                return null;
4444            }
4445            if (ps.pkg == null) {
4446                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4447                if (pInfo != null) {
4448                    return pInfo.applicationInfo;
4449                }
4450                return null;
4451            }
4452            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4453                    ps.readUserState(userId), userId);
4454            if (ai != null) {
4455                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4456            }
4457            return ai;
4458        }
4459        return null;
4460    }
4461
4462    @Override
4463    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4464        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4465    }
4466
4467    /**
4468     * Important: The provided filterCallingUid is used exclusively to filter out applications
4469     * that can be seen based on user state. It's typically the original caller uid prior
4470     * to clearing. Because it can only be provided by trusted code, it's value can be
4471     * trusted and will be used as-is; unlike userId which will be validated by this method.
4472     */
4473    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4474            int filterCallingUid, int userId) {
4475        if (!sUserManager.exists(userId)) return null;
4476        flags = updateFlagsForApplication(flags, userId, packageName);
4477        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4478                false /* requireFullPermission */, false /* checkShell */, "get application info");
4479
4480        // writer
4481        synchronized (mPackages) {
4482            // Normalize package name to handle renamed packages and static libs
4483            packageName = resolveInternalPackageNameLPr(packageName,
4484                    PackageManager.VERSION_CODE_HIGHEST);
4485
4486            PackageParser.Package p = mPackages.get(packageName);
4487            if (DEBUG_PACKAGE_INFO) Log.v(
4488                    TAG, "getApplicationInfo " + packageName
4489                    + ": " + p);
4490            if (p != null) {
4491                PackageSetting ps = mSettings.mPackages.get(packageName);
4492                if (ps == null) return null;
4493                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4494                    return null;
4495                }
4496                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4497                    return null;
4498                }
4499                // Note: isEnabledLP() does not apply here - always return info
4500                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4501                        p, flags, ps.readUserState(userId), userId);
4502                if (ai != null) {
4503                    ai.packageName = resolveExternalPackageNameLPr(p);
4504                }
4505                return ai;
4506            }
4507            if ("android".equals(packageName)||"system".equals(packageName)) {
4508                return mAndroidApplication;
4509            }
4510            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4511                // Already generates the external package name
4512                return generateApplicationInfoFromSettingsLPw(packageName,
4513                        flags, filterCallingUid, userId);
4514            }
4515        }
4516        return null;
4517    }
4518
4519    private String normalizePackageNameLPr(String packageName) {
4520        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4521        return normalizedPackageName != null ? normalizedPackageName : packageName;
4522    }
4523
4524    @Override
4525    public void deletePreloadsFileCache() {
4526        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4527            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4528        }
4529        File dir = Environment.getDataPreloadsFileCacheDirectory();
4530        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4531        FileUtils.deleteContents(dir);
4532    }
4533
4534    @Override
4535    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4536            final int storageFlags, final IPackageDataObserver observer) {
4537        mContext.enforceCallingOrSelfPermission(
4538                android.Manifest.permission.CLEAR_APP_CACHE, null);
4539        mHandler.post(() -> {
4540            boolean success = false;
4541            try {
4542                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4543                success = true;
4544            } catch (IOException e) {
4545                Slog.w(TAG, e);
4546            }
4547            if (observer != null) {
4548                try {
4549                    observer.onRemoveCompleted(null, success);
4550                } catch (RemoteException e) {
4551                    Slog.w(TAG, e);
4552                }
4553            }
4554        });
4555    }
4556
4557    @Override
4558    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4559            final int storageFlags, final IntentSender pi) {
4560        mContext.enforceCallingOrSelfPermission(
4561                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4562        mHandler.post(() -> {
4563            boolean success = false;
4564            try {
4565                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4566                success = true;
4567            } catch (IOException e) {
4568                Slog.w(TAG, e);
4569            }
4570            if (pi != null) {
4571                try {
4572                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4573                } catch (SendIntentException e) {
4574                    Slog.w(TAG, e);
4575                }
4576            }
4577        });
4578    }
4579
4580    /**
4581     * Blocking call to clear various types of cached data across the system
4582     * until the requested bytes are available.
4583     */
4584    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4585        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4586        final File file = storage.findPathForUuid(volumeUuid);
4587        if (file.getUsableSpace() >= bytes) return;
4588
4589        if (ENABLE_FREE_CACHE_V2) {
4590            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4591                    volumeUuid);
4592            final boolean aggressive = (storageFlags
4593                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4594            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4595
4596            // 1. Pre-flight to determine if we have any chance to succeed
4597            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4598            if (internalVolume && (aggressive || SystemProperties
4599                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4600                deletePreloadsFileCache();
4601                if (file.getUsableSpace() >= bytes) return;
4602            }
4603
4604            // 3. Consider parsed APK data (aggressive only)
4605            if (internalVolume && aggressive) {
4606                FileUtils.deleteContents(mCacheDir);
4607                if (file.getUsableSpace() >= bytes) return;
4608            }
4609
4610            // 4. Consider cached app data (above quotas)
4611            try {
4612                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4613                        Installer.FLAG_FREE_CACHE_V2);
4614            } catch (InstallerException ignored) {
4615            }
4616            if (file.getUsableSpace() >= bytes) return;
4617
4618            // 5. Consider shared libraries with refcount=0 and age>min cache period
4619            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4620                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4621                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4622                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4623                return;
4624            }
4625
4626            // 6. Consider dexopt output (aggressive only)
4627            // TODO: Implement
4628
4629            // 7. Consider installed instant apps unused longer than min cache period
4630            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4631                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4632                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4633                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4634                return;
4635            }
4636
4637            // 8. Consider cached app data (below quotas)
4638            try {
4639                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4640                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4641            } catch (InstallerException ignored) {
4642            }
4643            if (file.getUsableSpace() >= bytes) return;
4644
4645            // 9. Consider DropBox entries
4646            // TODO: Implement
4647
4648            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4649            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4650                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4651                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4652                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4653                return;
4654            }
4655        } else {
4656            try {
4657                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4658            } catch (InstallerException ignored) {
4659            }
4660            if (file.getUsableSpace() >= bytes) return;
4661        }
4662
4663        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4664    }
4665
4666    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4667            throws IOException {
4668        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4669        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4670
4671        List<VersionedPackage> packagesToDelete = null;
4672        final long now = System.currentTimeMillis();
4673
4674        synchronized (mPackages) {
4675            final int[] allUsers = sUserManager.getUserIds();
4676            final int libCount = mSharedLibraries.size();
4677            for (int i = 0; i < libCount; i++) {
4678                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4679                if (versionedLib == null) {
4680                    continue;
4681                }
4682                final int versionCount = versionedLib.size();
4683                for (int j = 0; j < versionCount; j++) {
4684                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4685                    // Skip packages that are not static shared libs.
4686                    if (!libInfo.isStatic()) {
4687                        break;
4688                    }
4689                    // Important: We skip static shared libs used for some user since
4690                    // in such a case we need to keep the APK on the device. The check for
4691                    // a lib being used for any user is performed by the uninstall call.
4692                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4693                    // Resolve the package name - we use synthetic package names internally
4694                    final String internalPackageName = resolveInternalPackageNameLPr(
4695                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4696                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4697                    // Skip unused static shared libs cached less than the min period
4698                    // to prevent pruning a lib needed by a subsequently installed package.
4699                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4700                        continue;
4701                    }
4702                    if (packagesToDelete == null) {
4703                        packagesToDelete = new ArrayList<>();
4704                    }
4705                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4706                            declaringPackage.getVersionCode()));
4707                }
4708            }
4709        }
4710
4711        if (packagesToDelete != null) {
4712            final int packageCount = packagesToDelete.size();
4713            for (int i = 0; i < packageCount; i++) {
4714                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4715                // Delete the package synchronously (will fail of the lib used for any user).
4716                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4717                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4718                                == PackageManager.DELETE_SUCCEEDED) {
4719                    if (volume.getUsableSpace() >= neededSpace) {
4720                        return true;
4721                    }
4722                }
4723            }
4724        }
4725
4726        return false;
4727    }
4728
4729    /**
4730     * Update given flags based on encryption status of current user.
4731     */
4732    private int updateFlags(int flags, int userId) {
4733        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4734                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4735            // Caller expressed an explicit opinion about what encryption
4736            // aware/unaware components they want to see, so fall through and
4737            // give them what they want
4738        } else {
4739            // Caller expressed no opinion, so match based on user state
4740            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4741                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4742            } else {
4743                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4744            }
4745        }
4746        return flags;
4747    }
4748
4749    private UserManagerInternal getUserManagerInternal() {
4750        if (mUserManagerInternal == null) {
4751            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4752        }
4753        return mUserManagerInternal;
4754    }
4755
4756    private DeviceIdleController.LocalService getDeviceIdleController() {
4757        if (mDeviceIdleController == null) {
4758            mDeviceIdleController =
4759                    LocalServices.getService(DeviceIdleController.LocalService.class);
4760        }
4761        return mDeviceIdleController;
4762    }
4763
4764    /**
4765     * Update given flags when being used to request {@link PackageInfo}.
4766     */
4767    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4768        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4769        boolean triaged = true;
4770        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4771                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4772            // Caller is asking for component details, so they'd better be
4773            // asking for specific encryption matching behavior, or be triaged
4774            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4775                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4776                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4777                triaged = false;
4778            }
4779        }
4780        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4781                | PackageManager.MATCH_SYSTEM_ONLY
4782                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4783            triaged = false;
4784        }
4785        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4786            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4787                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4788                    + Debug.getCallers(5));
4789        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4790                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4791            // If the caller wants all packages and has a restricted profile associated with it,
4792            // then match all users. This is to make sure that launchers that need to access work
4793            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4794            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4795            flags |= PackageManager.MATCH_ANY_USER;
4796        }
4797        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4798            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4799                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4800        }
4801        return updateFlags(flags, userId);
4802    }
4803
4804    /**
4805     * Update given flags when being used to request {@link ApplicationInfo}.
4806     */
4807    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4808        return updateFlagsForPackage(flags, userId, cookie);
4809    }
4810
4811    /**
4812     * Update given flags when being used to request {@link ComponentInfo}.
4813     */
4814    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4815        if (cookie instanceof Intent) {
4816            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4817                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4818            }
4819        }
4820
4821        boolean triaged = true;
4822        // Caller is asking for component details, so they'd better be
4823        // asking for specific encryption matching behavior, or be triaged
4824        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4825                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4826                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4827            triaged = false;
4828        }
4829        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4830            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4831                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4832        }
4833
4834        return updateFlags(flags, userId);
4835    }
4836
4837    /**
4838     * Update given intent when being used to request {@link ResolveInfo}.
4839     */
4840    private Intent updateIntentForResolve(Intent intent) {
4841        if (intent.getSelector() != null) {
4842            intent = intent.getSelector();
4843        }
4844        if (DEBUG_PREFERRED) {
4845            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4846        }
4847        return intent;
4848    }
4849
4850    /**
4851     * Update given flags when being used to request {@link ResolveInfo}.
4852     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4853     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4854     * flag set. However, this flag is only honoured in three circumstances:
4855     * <ul>
4856     * <li>when called from a system process</li>
4857     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4858     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4859     * action and a {@code android.intent.category.BROWSABLE} category</li>
4860     * </ul>
4861     */
4862    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4863        return updateFlagsForResolve(flags, userId, intent, callingUid,
4864                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4865    }
4866    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4867            boolean wantInstantApps) {
4868        return updateFlagsForResolve(flags, userId, intent, callingUid,
4869                wantInstantApps, false /*onlyExposedExplicitly*/);
4870    }
4871    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4872            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4873        // Safe mode means we shouldn't match any third-party components
4874        if (mSafeMode) {
4875            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4876        }
4877        if (getInstantAppPackageName(callingUid) != null) {
4878            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4879            if (onlyExposedExplicitly) {
4880                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4881            }
4882            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4883            flags |= PackageManager.MATCH_INSTANT;
4884        } else {
4885            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4886            final boolean allowMatchInstant =
4887                    (wantInstantApps
4888                            && Intent.ACTION_VIEW.equals(intent.getAction())
4889                            && hasWebURI(intent))
4890                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4891            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4892                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4893            if (!allowMatchInstant) {
4894                flags &= ~PackageManager.MATCH_INSTANT;
4895            }
4896        }
4897        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4898    }
4899
4900    @Override
4901    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4902        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4903    }
4904
4905    /**
4906     * Important: The provided filterCallingUid is used exclusively to filter out activities
4907     * that can be seen based on user state. It's typically the original caller uid prior
4908     * to clearing. Because it can only be provided by trusted code, it's value can be
4909     * trusted and will be used as-is; unlike userId which will be validated by this method.
4910     */
4911    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4912            int filterCallingUid, int userId) {
4913        if (!sUserManager.exists(userId)) return null;
4914        flags = updateFlagsForComponent(flags, userId, component);
4915        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4916                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4917        synchronized (mPackages) {
4918            PackageParser.Activity a = mActivities.mActivities.get(component);
4919
4920            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4921            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4922                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4923                if (ps == null) return null;
4924                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4925                    return null;
4926                }
4927                return PackageParser.generateActivityInfo(
4928                        a, flags, ps.readUserState(userId), userId);
4929            }
4930            if (mResolveComponentName.equals(component)) {
4931                return PackageParser.generateActivityInfo(
4932                        mResolveActivity, flags, new PackageUserState(), userId);
4933            }
4934        }
4935        return null;
4936    }
4937
4938    @Override
4939    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4940            String resolvedType) {
4941        synchronized (mPackages) {
4942            if (component.equals(mResolveComponentName)) {
4943                // The resolver supports EVERYTHING!
4944                return true;
4945            }
4946            final int callingUid = Binder.getCallingUid();
4947            final int callingUserId = UserHandle.getUserId(callingUid);
4948            PackageParser.Activity a = mActivities.mActivities.get(component);
4949            if (a == null) {
4950                return false;
4951            }
4952            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4953            if (ps == null) {
4954                return false;
4955            }
4956            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4957                return false;
4958            }
4959            for (int i=0; i<a.intents.size(); i++) {
4960                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4961                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4962                    return true;
4963                }
4964            }
4965            return false;
4966        }
4967    }
4968
4969    @Override
4970    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4971        if (!sUserManager.exists(userId)) return null;
4972        final int callingUid = Binder.getCallingUid();
4973        flags = updateFlagsForComponent(flags, userId, component);
4974        enforceCrossUserPermission(callingUid, userId,
4975                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4976        synchronized (mPackages) {
4977            PackageParser.Activity a = mReceivers.mActivities.get(component);
4978            if (DEBUG_PACKAGE_INFO) Log.v(
4979                TAG, "getReceiverInfo " + component + ": " + a);
4980            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4981                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4982                if (ps == null) return null;
4983                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4984                    return null;
4985                }
4986                return PackageParser.generateActivityInfo(
4987                        a, flags, ps.readUserState(userId), userId);
4988            }
4989        }
4990        return null;
4991    }
4992
4993    @Override
4994    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4995            int flags, int userId) {
4996        if (!sUserManager.exists(userId)) return null;
4997        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4998        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4999            return null;
5000        }
5001
5002        flags = updateFlagsForPackage(flags, userId, null);
5003
5004        final boolean canSeeStaticLibraries =
5005                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
5006                        == PERMISSION_GRANTED
5007                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
5008                        == PERMISSION_GRANTED
5009                || canRequestPackageInstallsInternal(packageName,
5010                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
5011                        false  /* throwIfPermNotDeclared*/)
5012                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
5013                        == PERMISSION_GRANTED;
5014
5015        synchronized (mPackages) {
5016            List<SharedLibraryInfo> result = null;
5017
5018            final int libCount = mSharedLibraries.size();
5019            for (int i = 0; i < libCount; i++) {
5020                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5021                if (versionedLib == null) {
5022                    continue;
5023                }
5024
5025                final int versionCount = versionedLib.size();
5026                for (int j = 0; j < versionCount; j++) {
5027                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
5028                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
5029                        break;
5030                    }
5031                    final long identity = Binder.clearCallingIdentity();
5032                    try {
5033                        PackageInfo packageInfo = getPackageInfoVersioned(
5034                                libInfo.getDeclaringPackage(), flags
5035                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
5036                        if (packageInfo == null) {
5037                            continue;
5038                        }
5039                    } finally {
5040                        Binder.restoreCallingIdentity(identity);
5041                    }
5042
5043                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
5044                            libInfo.getVersion(), libInfo.getType(),
5045                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
5046                            flags, userId));
5047
5048                    if (result == null) {
5049                        result = new ArrayList<>();
5050                    }
5051                    result.add(resLibInfo);
5052                }
5053            }
5054
5055            return result != null ? new ParceledListSlice<>(result) : null;
5056        }
5057    }
5058
5059    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
5060            SharedLibraryInfo libInfo, int flags, int userId) {
5061        List<VersionedPackage> versionedPackages = null;
5062        final int packageCount = mSettings.mPackages.size();
5063        for (int i = 0; i < packageCount; i++) {
5064            PackageSetting ps = mSettings.mPackages.valueAt(i);
5065
5066            if (ps == null) {
5067                continue;
5068            }
5069
5070            if (!ps.getUserState().get(userId).isAvailable(flags)) {
5071                continue;
5072            }
5073
5074            final String libName = libInfo.getName();
5075            if (libInfo.isStatic()) {
5076                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
5077                if (libIdx < 0) {
5078                    continue;
5079                }
5080                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
5081                    continue;
5082                }
5083                if (versionedPackages == null) {
5084                    versionedPackages = new ArrayList<>();
5085                }
5086                // If the dependent is a static shared lib, use the public package name
5087                String dependentPackageName = ps.name;
5088                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
5089                    dependentPackageName = ps.pkg.manifestPackageName;
5090                }
5091                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
5092            } else if (ps.pkg != null) {
5093                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5094                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5095                    if (versionedPackages == null) {
5096                        versionedPackages = new ArrayList<>();
5097                    }
5098                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5099                }
5100            }
5101        }
5102
5103        return versionedPackages;
5104    }
5105
5106    @Override
5107    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5108        if (!sUserManager.exists(userId)) return null;
5109        final int callingUid = Binder.getCallingUid();
5110        flags = updateFlagsForComponent(flags, userId, component);
5111        enforceCrossUserPermission(callingUid, userId,
5112                false /* requireFullPermission */, false /* checkShell */, "get service info");
5113        synchronized (mPackages) {
5114            PackageParser.Service s = mServices.mServices.get(component);
5115            if (DEBUG_PACKAGE_INFO) Log.v(
5116                TAG, "getServiceInfo " + component + ": " + s);
5117            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5118                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5119                if (ps == null) return null;
5120                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5121                    return null;
5122                }
5123                return PackageParser.generateServiceInfo(
5124                        s, flags, ps.readUserState(userId), userId);
5125            }
5126        }
5127        return null;
5128    }
5129
5130    @Override
5131    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5132        if (!sUserManager.exists(userId)) return null;
5133        final int callingUid = Binder.getCallingUid();
5134        flags = updateFlagsForComponent(flags, userId, component);
5135        enforceCrossUserPermission(callingUid, userId,
5136                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5137        synchronized (mPackages) {
5138            PackageParser.Provider p = mProviders.mProviders.get(component);
5139            if (DEBUG_PACKAGE_INFO) Log.v(
5140                TAG, "getProviderInfo " + component + ": " + p);
5141            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5142                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5143                if (ps == null) return null;
5144                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5145                    return null;
5146                }
5147                return PackageParser.generateProviderInfo(
5148                        p, flags, ps.readUserState(userId), userId);
5149            }
5150        }
5151        return null;
5152    }
5153
5154    @Override
5155    public String[] getSystemSharedLibraryNames() {
5156        // allow instant applications
5157        synchronized (mPackages) {
5158            Set<String> libs = null;
5159            final int libCount = mSharedLibraries.size();
5160            for (int i = 0; i < libCount; i++) {
5161                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5162                if (versionedLib == null) {
5163                    continue;
5164                }
5165                final int versionCount = versionedLib.size();
5166                for (int j = 0; j < versionCount; j++) {
5167                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5168                    if (!libEntry.info.isStatic()) {
5169                        if (libs == null) {
5170                            libs = new ArraySet<>();
5171                        }
5172                        libs.add(libEntry.info.getName());
5173                        break;
5174                    }
5175                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5176                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5177                            UserHandle.getUserId(Binder.getCallingUid()),
5178                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5179                        if (libs == null) {
5180                            libs = new ArraySet<>();
5181                        }
5182                        libs.add(libEntry.info.getName());
5183                        break;
5184                    }
5185                }
5186            }
5187
5188            if (libs != null) {
5189                String[] libsArray = new String[libs.size()];
5190                libs.toArray(libsArray);
5191                return libsArray;
5192            }
5193
5194            return null;
5195        }
5196    }
5197
5198    @Override
5199    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5200        // allow instant applications
5201        synchronized (mPackages) {
5202            return mServicesSystemSharedLibraryPackageName;
5203        }
5204    }
5205
5206    @Override
5207    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5208        // allow instant applications
5209        synchronized (mPackages) {
5210            return mSharedSystemSharedLibraryPackageName;
5211        }
5212    }
5213
5214    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5215        for (int i = userList.length - 1; i >= 0; --i) {
5216            final int userId = userList[i];
5217            // don't add instant app to the list of updates
5218            if (pkgSetting.getInstantApp(userId)) {
5219                continue;
5220            }
5221            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5222            if (changedPackages == null) {
5223                changedPackages = new SparseArray<>();
5224                mChangedPackages.put(userId, changedPackages);
5225            }
5226            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5227            if (sequenceNumbers == null) {
5228                sequenceNumbers = new HashMap<>();
5229                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5230            }
5231            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5232            if (sequenceNumber != null) {
5233                changedPackages.remove(sequenceNumber);
5234            }
5235            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5236            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5237        }
5238        mChangedPackagesSequenceNumber++;
5239    }
5240
5241    @Override
5242    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5243        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5244            return null;
5245        }
5246        synchronized (mPackages) {
5247            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5248                return null;
5249            }
5250            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5251            if (changedPackages == null) {
5252                return null;
5253            }
5254            final List<String> packageNames =
5255                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5256            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5257                final String packageName = changedPackages.get(i);
5258                if (packageName != null) {
5259                    packageNames.add(packageName);
5260                }
5261            }
5262            return packageNames.isEmpty()
5263                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5264        }
5265    }
5266
5267    @Override
5268    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5269        // allow instant applications
5270        ArrayList<FeatureInfo> res;
5271        synchronized (mAvailableFeatures) {
5272            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5273            res.addAll(mAvailableFeatures.values());
5274        }
5275        final FeatureInfo fi = new FeatureInfo();
5276        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5277                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5278        res.add(fi);
5279
5280        return new ParceledListSlice<>(res);
5281    }
5282
5283    @Override
5284    public boolean hasSystemFeature(String name, int version) {
5285        // allow instant applications
5286        synchronized (mAvailableFeatures) {
5287            final FeatureInfo feat = mAvailableFeatures.get(name);
5288            if (feat == null) {
5289                return false;
5290            } else {
5291                return feat.version >= version;
5292            }
5293        }
5294    }
5295
5296    @Override
5297    public int checkPermission(String permName, String pkgName, int userId) {
5298        if (!sUserManager.exists(userId)) {
5299            return PackageManager.PERMISSION_DENIED;
5300        }
5301        final int callingUid = Binder.getCallingUid();
5302
5303        synchronized (mPackages) {
5304            final PackageParser.Package p = mPackages.get(pkgName);
5305            if (p != null && p.mExtras != null) {
5306                final PackageSetting ps = (PackageSetting) p.mExtras;
5307                if (filterAppAccessLPr(ps, callingUid, userId)) {
5308                    return PackageManager.PERMISSION_DENIED;
5309                }
5310                final boolean instantApp = ps.getInstantApp(userId);
5311                final PermissionsState permissionsState = ps.getPermissionsState();
5312                if (permissionsState.hasPermission(permName, userId)) {
5313                    if (instantApp) {
5314                        BasePermission bp = mSettings.mPermissions.get(permName);
5315                        if (bp != null && bp.isInstant()) {
5316                            return PackageManager.PERMISSION_GRANTED;
5317                        }
5318                    } else {
5319                        return PackageManager.PERMISSION_GRANTED;
5320                    }
5321                }
5322                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5323                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5324                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5325                    return PackageManager.PERMISSION_GRANTED;
5326                }
5327            }
5328        }
5329
5330        return PackageManager.PERMISSION_DENIED;
5331    }
5332
5333    @Override
5334    public int checkUidPermission(String permName, int uid) {
5335        final int callingUid = Binder.getCallingUid();
5336        final int callingUserId = UserHandle.getUserId(callingUid);
5337        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5338        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
5339        final int userId = UserHandle.getUserId(uid);
5340        if (!sUserManager.exists(userId)) {
5341            return PackageManager.PERMISSION_DENIED;
5342        }
5343
5344        synchronized (mPackages) {
5345            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5346            if (obj != null) {
5347                if (obj instanceof SharedUserSetting) {
5348                    if (isCallerInstantApp) {
5349                        return PackageManager.PERMISSION_DENIED;
5350                    }
5351                } else if (obj instanceof PackageSetting) {
5352                    final PackageSetting ps = (PackageSetting) obj;
5353                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5354                        return PackageManager.PERMISSION_DENIED;
5355                    }
5356                }
5357                final SettingBase settingBase = (SettingBase) obj;
5358                final PermissionsState permissionsState = settingBase.getPermissionsState();
5359                if (permissionsState.hasPermission(permName, userId)) {
5360                    if (isUidInstantApp) {
5361                        BasePermission bp = mSettings.mPermissions.get(permName);
5362                        if (bp != null && bp.isInstant()) {
5363                            return PackageManager.PERMISSION_GRANTED;
5364                        }
5365                    } else {
5366                        return PackageManager.PERMISSION_GRANTED;
5367                    }
5368                }
5369                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5370                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5371                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5372                    return PackageManager.PERMISSION_GRANTED;
5373                }
5374            } else {
5375                ArraySet<String> perms = mSystemPermissions.get(uid);
5376                if (perms != null) {
5377                    if (perms.contains(permName)) {
5378                        return PackageManager.PERMISSION_GRANTED;
5379                    }
5380                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5381                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5382                        return PackageManager.PERMISSION_GRANTED;
5383                    }
5384                }
5385            }
5386        }
5387
5388        return PackageManager.PERMISSION_DENIED;
5389    }
5390
5391    @Override
5392    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5393        if (UserHandle.getCallingUserId() != userId) {
5394            mContext.enforceCallingPermission(
5395                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5396                    "isPermissionRevokedByPolicy for user " + userId);
5397        }
5398
5399        if (checkPermission(permission, packageName, userId)
5400                == PackageManager.PERMISSION_GRANTED) {
5401            return false;
5402        }
5403
5404        final int callingUid = Binder.getCallingUid();
5405        if (getInstantAppPackageName(callingUid) != null) {
5406            if (!isCallerSameApp(packageName, callingUid)) {
5407                return false;
5408            }
5409        } else {
5410            if (isInstantApp(packageName, userId)) {
5411                return false;
5412            }
5413        }
5414
5415        final long identity = Binder.clearCallingIdentity();
5416        try {
5417            final int flags = getPermissionFlags(permission, packageName, userId);
5418            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5419        } finally {
5420            Binder.restoreCallingIdentity(identity);
5421        }
5422    }
5423
5424    @Override
5425    public String getPermissionControllerPackageName() {
5426        synchronized (mPackages) {
5427            return mRequiredInstallerPackage;
5428        }
5429    }
5430
5431    /**
5432     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
5433     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
5434     * @param checkShell whether to prevent shell from access if there's a debugging restriction
5435     * @param message the message to log on security exception
5436     */
5437    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
5438            boolean checkShell, String message) {
5439        if (userId < 0) {
5440            throw new IllegalArgumentException("Invalid userId " + userId);
5441        }
5442        if (checkShell) {
5443            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
5444        }
5445        if (userId == UserHandle.getUserId(callingUid)) return;
5446        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5447            if (requireFullPermission) {
5448                mContext.enforceCallingOrSelfPermission(
5449                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5450            } else {
5451                try {
5452                    mContext.enforceCallingOrSelfPermission(
5453                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5454                } catch (SecurityException se) {
5455                    mContext.enforceCallingOrSelfPermission(
5456                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5457                }
5458            }
5459        }
5460    }
5461
5462    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5463        if (callingUid == Process.SHELL_UID) {
5464            if (userHandle >= 0
5465                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
5466                throw new SecurityException("Shell does not have permission to access user "
5467                        + userHandle);
5468            } else if (userHandle < 0) {
5469                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5470                        + Debug.getCallers(3));
5471            }
5472        }
5473    }
5474
5475    private BasePermission findPermissionTreeLP(String permName) {
5476        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
5477            if (permName.startsWith(bp.name) &&
5478                    permName.length() > bp.name.length() &&
5479                    permName.charAt(bp.name.length()) == '.') {
5480                return bp;
5481            }
5482        }
5483        return null;
5484    }
5485
5486    private BasePermission checkPermissionTreeLP(String permName) {
5487        if (permName != null) {
5488            BasePermission bp = findPermissionTreeLP(permName);
5489            if (bp != null) {
5490                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
5491                    return bp;
5492                }
5493                throw new SecurityException("Calling uid "
5494                        + Binder.getCallingUid()
5495                        + " is not allowed to add to permission tree "
5496                        + bp.name + " owned by uid " + bp.uid);
5497            }
5498        }
5499        throw new SecurityException("No permission tree found for " + permName);
5500    }
5501
5502    static boolean compareStrings(CharSequence s1, CharSequence s2) {
5503        if (s1 == null) {
5504            return s2 == null;
5505        }
5506        if (s2 == null) {
5507            return false;
5508        }
5509        if (s1.getClass() != s2.getClass()) {
5510            return false;
5511        }
5512        return s1.equals(s2);
5513    }
5514
5515    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5516        if (pi1.icon != pi2.icon) return false;
5517        if (pi1.logo != pi2.logo) return false;
5518        if (pi1.protectionLevel != pi2.protectionLevel) return false;
5519        if (!compareStrings(pi1.name, pi2.name)) return false;
5520        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5521        // We'll take care of setting this one.
5522        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5523        // These are not currently stored in settings.
5524        //if (!compareStrings(pi1.group, pi2.group)) return false;
5525        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5526        //if (pi1.labelRes != pi2.labelRes) return false;
5527        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5528        return true;
5529    }
5530
5531    int permissionInfoFootprint(PermissionInfo info) {
5532        int size = info.name.length();
5533        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5534        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5535        return size;
5536    }
5537
5538    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5539        int size = 0;
5540        for (BasePermission perm : mSettings.mPermissions.values()) {
5541            if (perm.uid == tree.uid) {
5542                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5543            }
5544        }
5545        return size;
5546    }
5547
5548    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5549        // We calculate the max size of permissions defined by this uid and throw
5550        // if that plus the size of 'info' would exceed our stated maximum.
5551        if (tree.uid != Process.SYSTEM_UID) {
5552            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5553            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5554                throw new SecurityException("Permission tree size cap exceeded");
5555            }
5556        }
5557    }
5558
5559    boolean addPermissionLocked(PermissionInfo info, boolean async) {
5560        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5561            throw new SecurityException("Instant apps can't add permissions");
5562        }
5563        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5564            throw new SecurityException("Label must be specified in permission");
5565        }
5566        BasePermission tree = checkPermissionTreeLP(info.name);
5567        BasePermission bp = mSettings.mPermissions.get(info.name);
5568        boolean added = bp == null;
5569        boolean changed = true;
5570        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5571        if (added) {
5572            enforcePermissionCapLocked(info, tree);
5573            bp = new BasePermission(info.name, tree.sourcePackage,
5574                    BasePermission.TYPE_DYNAMIC);
5575        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5576            throw new SecurityException(
5577                    "Not allowed to modify non-dynamic permission "
5578                    + info.name);
5579        } else {
5580            if (bp.protectionLevel == fixedLevel
5581                    && bp.perm.owner.equals(tree.perm.owner)
5582                    && bp.uid == tree.uid
5583                    && comparePermissionInfos(bp.perm.info, info)) {
5584                changed = false;
5585            }
5586        }
5587        bp.protectionLevel = fixedLevel;
5588        info = new PermissionInfo(info);
5589        info.protectionLevel = fixedLevel;
5590        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5591        bp.perm.info.packageName = tree.perm.info.packageName;
5592        bp.uid = tree.uid;
5593        if (added) {
5594            mSettings.mPermissions.put(info.name, bp);
5595        }
5596        if (changed) {
5597            if (!async) {
5598                mSettings.writeLPr();
5599            } else {
5600                scheduleWriteSettingsLocked();
5601            }
5602        }
5603        return added;
5604    }
5605
5606    @Override
5607    public boolean addPermission(PermissionInfo info) {
5608        synchronized (mPackages) {
5609            return addPermissionLocked(info, false);
5610        }
5611    }
5612
5613    @Override
5614    public boolean addPermissionAsync(PermissionInfo info) {
5615        synchronized (mPackages) {
5616            return addPermissionLocked(info, true);
5617        }
5618    }
5619
5620    @Override
5621    public void removePermission(String name) {
5622        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5623            throw new SecurityException("Instant applications don't have access to this method");
5624        }
5625        synchronized (mPackages) {
5626            checkPermissionTreeLP(name);
5627            BasePermission bp = mSettings.mPermissions.get(name);
5628            if (bp != null) {
5629                if (bp.type != BasePermission.TYPE_DYNAMIC) {
5630                    throw new SecurityException(
5631                            "Not allowed to modify non-dynamic permission "
5632                            + name);
5633                }
5634                mSettings.mPermissions.remove(name);
5635                mSettings.writeLPr();
5636            }
5637        }
5638    }
5639
5640    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5641            PackageParser.Package pkg, BasePermission bp) {
5642        int index = pkg.requestedPermissions.indexOf(bp.name);
5643        if (index == -1) {
5644            throw new SecurityException("Package " + pkg.packageName
5645                    + " has not requested permission " + bp.name);
5646        }
5647        if (!bp.isRuntime() && !bp.isDevelopment()) {
5648            throw new SecurityException("Permission " + bp.name
5649                    + " is not a changeable permission type");
5650        }
5651    }
5652
5653    @Override
5654    public void grantRuntimePermission(String packageName, String name, final int userId) {
5655        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5656    }
5657
5658    private void grantRuntimePermission(String packageName, String name, final int userId,
5659            boolean overridePolicy) {
5660        if (!sUserManager.exists(userId)) {
5661            Log.e(TAG, "No such user:" + userId);
5662            return;
5663        }
5664        final int callingUid = Binder.getCallingUid();
5665
5666        mContext.enforceCallingOrSelfPermission(
5667                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5668                "grantRuntimePermission");
5669
5670        enforceCrossUserPermission(callingUid, userId,
5671                true /* requireFullPermission */, true /* checkShell */,
5672                "grantRuntimePermission");
5673
5674        final int uid;
5675        final PackageSetting ps;
5676
5677        synchronized (mPackages) {
5678            final PackageParser.Package pkg = mPackages.get(packageName);
5679            if (pkg == null) {
5680                throw new IllegalArgumentException("Unknown package: " + packageName);
5681            }
5682            final BasePermission bp = mSettings.mPermissions.get(name);
5683            if (bp == null) {
5684                throw new IllegalArgumentException("Unknown permission: " + name);
5685            }
5686            ps = (PackageSetting) pkg.mExtras;
5687            if (ps == null
5688                    || filterAppAccessLPr(ps, callingUid, userId)) {
5689                throw new IllegalArgumentException("Unknown package: " + packageName);
5690            }
5691
5692            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5693
5694            // If a permission review is required for legacy apps we represent
5695            // their permissions as always granted runtime ones since we need
5696            // to keep the review required permission flag per user while an
5697            // install permission's state is shared across all users.
5698            if (mPermissionReviewRequired
5699                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5700                    && bp.isRuntime()) {
5701                return;
5702            }
5703
5704            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5705
5706            final PermissionsState permissionsState = ps.getPermissionsState();
5707
5708            final int flags = permissionsState.getPermissionFlags(name, userId);
5709            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5710                throw new SecurityException("Cannot grant system fixed permission "
5711                        + name + " for package " + packageName);
5712            }
5713            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5714                throw new SecurityException("Cannot grant policy fixed permission "
5715                        + name + " for package " + packageName);
5716            }
5717
5718            if (bp.isDevelopment()) {
5719                // Development permissions must be handled specially, since they are not
5720                // normal runtime permissions.  For now they apply to all users.
5721                if (permissionsState.grantInstallPermission(bp) !=
5722                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5723                    scheduleWriteSettingsLocked();
5724                }
5725                return;
5726            }
5727
5728            if (ps.getInstantApp(userId) && !bp.isInstant()) {
5729                throw new SecurityException("Cannot grant non-ephemeral permission"
5730                        + name + " for package " + packageName);
5731            }
5732
5733            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5734                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5735                return;
5736            }
5737
5738            final int result = permissionsState.grantRuntimePermission(bp, userId);
5739            switch (result) {
5740                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5741                    return;
5742                }
5743
5744                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5745                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5746                    mHandler.post(new Runnable() {
5747                        @Override
5748                        public void run() {
5749                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5750                        }
5751                    });
5752                }
5753                break;
5754            }
5755
5756            if (bp.isRuntime()) {
5757                logPermissionGranted(mContext, name, packageName);
5758            }
5759
5760            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5761
5762            // Not critical if that is lost - app has to request again.
5763            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5764        }
5765
5766        // Only need to do this if user is initialized. Otherwise it's a new user
5767        // and there are no processes running as the user yet and there's no need
5768        // to make an expensive call to remount processes for the changed permissions.
5769        if (READ_EXTERNAL_STORAGE.equals(name)
5770                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5771            final long token = Binder.clearCallingIdentity();
5772            try {
5773                if (sUserManager.isInitialized(userId)) {
5774                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5775                            StorageManagerInternal.class);
5776                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5777                }
5778            } finally {
5779                Binder.restoreCallingIdentity(token);
5780            }
5781        }
5782    }
5783
5784    @Override
5785    public void revokeRuntimePermission(String packageName, String name, int userId) {
5786        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5787    }
5788
5789    private void revokeRuntimePermission(String packageName, String name, int userId,
5790            boolean overridePolicy) {
5791        if (!sUserManager.exists(userId)) {
5792            Log.e(TAG, "No such user:" + userId);
5793            return;
5794        }
5795
5796        mContext.enforceCallingOrSelfPermission(
5797                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5798                "revokeRuntimePermission");
5799
5800        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5801                true /* requireFullPermission */, true /* checkShell */,
5802                "revokeRuntimePermission");
5803
5804        final int appId;
5805
5806        synchronized (mPackages) {
5807            final PackageParser.Package pkg = mPackages.get(packageName);
5808            if (pkg == null) {
5809                throw new IllegalArgumentException("Unknown package: " + packageName);
5810            }
5811            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5812            if (ps == null
5813                    || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
5814                throw new IllegalArgumentException("Unknown package: " + packageName);
5815            }
5816            final BasePermission bp = mSettings.mPermissions.get(name);
5817            if (bp == null) {
5818                throw new IllegalArgumentException("Unknown permission: " + name);
5819            }
5820
5821            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5822
5823            // If a permission review is required for legacy apps we represent
5824            // their permissions as always granted runtime ones since we need
5825            // to keep the review required permission flag per user while an
5826            // install permission's state is shared across all users.
5827            if (mPermissionReviewRequired
5828                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5829                    && bp.isRuntime()) {
5830                return;
5831            }
5832
5833            final PermissionsState permissionsState = ps.getPermissionsState();
5834
5835            final int flags = permissionsState.getPermissionFlags(name, userId);
5836            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5837                throw new SecurityException("Cannot revoke system fixed permission "
5838                        + name + " for package " + packageName);
5839            }
5840            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5841                throw new SecurityException("Cannot revoke policy fixed permission "
5842                        + name + " for package " + packageName);
5843            }
5844
5845            if (bp.isDevelopment()) {
5846                // Development permissions must be handled specially, since they are not
5847                // normal runtime permissions.  For now they apply to all users.
5848                if (permissionsState.revokeInstallPermission(bp) !=
5849                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5850                    scheduleWriteSettingsLocked();
5851                }
5852                return;
5853            }
5854
5855            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5856                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5857                return;
5858            }
5859
5860            if (bp.isRuntime()) {
5861                logPermissionRevoked(mContext, name, packageName);
5862            }
5863
5864            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5865
5866            // Critical, after this call app should never have the permission.
5867            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5868
5869            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5870        }
5871
5872        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5873    }
5874
5875    /**
5876     * Get the first event id for the permission.
5877     *
5878     * <p>There are four events for each permission: <ul>
5879     *     <li>Request permission: first id + 0</li>
5880     *     <li>Grant permission: first id + 1</li>
5881     *     <li>Request for permission denied: first id + 2</li>
5882     *     <li>Revoke permission: first id + 3</li>
5883     * </ul></p>
5884     *
5885     * @param name name of the permission
5886     *
5887     * @return The first event id for the permission
5888     */
5889    private static int getBaseEventId(@NonNull String name) {
5890        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5891
5892        if (eventIdIndex == -1) {
5893            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5894                    || Build.IS_USER) {
5895                Log.i(TAG, "Unknown permission " + name);
5896
5897                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5898            } else {
5899                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5900                //
5901                // Also update
5902                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5903                // - metrics_constants.proto
5904                throw new IllegalStateException("Unknown permission " + name);
5905            }
5906        }
5907
5908        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5909    }
5910
5911    /**
5912     * Log that a permission was revoked.
5913     *
5914     * @param context Context of the caller
5915     * @param name name of the permission
5916     * @param packageName package permission if for
5917     */
5918    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5919            @NonNull String packageName) {
5920        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5921    }
5922
5923    /**
5924     * Log that a permission request was granted.
5925     *
5926     * @param context Context of the caller
5927     * @param name name of the permission
5928     * @param packageName package permission if for
5929     */
5930    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5931            @NonNull String packageName) {
5932        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5933    }
5934
5935    @Override
5936    public void resetRuntimePermissions() {
5937        mContext.enforceCallingOrSelfPermission(
5938                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5939                "revokeRuntimePermission");
5940
5941        int callingUid = Binder.getCallingUid();
5942        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5943            mContext.enforceCallingOrSelfPermission(
5944                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5945                    "resetRuntimePermissions");
5946        }
5947
5948        synchronized (mPackages) {
5949            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5950            for (int userId : UserManagerService.getInstance().getUserIds()) {
5951                final int packageCount = mPackages.size();
5952                for (int i = 0; i < packageCount; i++) {
5953                    PackageParser.Package pkg = mPackages.valueAt(i);
5954                    if (!(pkg.mExtras instanceof PackageSetting)) {
5955                        continue;
5956                    }
5957                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5958                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5959                }
5960            }
5961        }
5962    }
5963
5964    @Override
5965    public int getPermissionFlags(String name, String packageName, int userId) {
5966        if (!sUserManager.exists(userId)) {
5967            return 0;
5968        }
5969
5970        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5971
5972        final int callingUid = Binder.getCallingUid();
5973        enforceCrossUserPermission(callingUid, userId,
5974                true /* requireFullPermission */, false /* checkShell */,
5975                "getPermissionFlags");
5976
5977        synchronized (mPackages) {
5978            final PackageParser.Package pkg = mPackages.get(packageName);
5979            if (pkg == null) {
5980                return 0;
5981            }
5982            final BasePermission bp = mSettings.mPermissions.get(name);
5983            if (bp == null) {
5984                return 0;
5985            }
5986            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5987            if (ps == null
5988                    || filterAppAccessLPr(ps, callingUid, userId)) {
5989                return 0;
5990            }
5991            PermissionsState permissionsState = ps.getPermissionsState();
5992            return permissionsState.getPermissionFlags(name, userId);
5993        }
5994    }
5995
5996    @Override
5997    public void updatePermissionFlags(String name, String packageName, int flagMask,
5998            int flagValues, int userId) {
5999        if (!sUserManager.exists(userId)) {
6000            return;
6001        }
6002
6003        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
6004
6005        final int callingUid = Binder.getCallingUid();
6006        enforceCrossUserPermission(callingUid, userId,
6007                true /* requireFullPermission */, true /* checkShell */,
6008                "updatePermissionFlags");
6009
6010        // Only the system can change these flags and nothing else.
6011        if (getCallingUid() != Process.SYSTEM_UID) {
6012            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
6013            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
6014            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
6015            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
6016            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
6017        }
6018
6019        synchronized (mPackages) {
6020            final PackageParser.Package pkg = mPackages.get(packageName);
6021            if (pkg == null) {
6022                throw new IllegalArgumentException("Unknown package: " + packageName);
6023            }
6024            final PackageSetting ps = (PackageSetting) pkg.mExtras;
6025            if (ps == null
6026                    || filterAppAccessLPr(ps, callingUid, userId)) {
6027                throw new IllegalArgumentException("Unknown package: " + packageName);
6028            }
6029
6030            final BasePermission bp = mSettings.mPermissions.get(name);
6031            if (bp == null) {
6032                throw new IllegalArgumentException("Unknown permission: " + name);
6033            }
6034
6035            PermissionsState permissionsState = ps.getPermissionsState();
6036
6037            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
6038
6039            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
6040                // Install and runtime permissions are stored in different places,
6041                // so figure out what permission changed and persist the change.
6042                if (permissionsState.getInstallPermissionState(name) != null) {
6043                    scheduleWriteSettingsLocked();
6044                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
6045                        || hadState) {
6046                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
6047                }
6048            }
6049        }
6050    }
6051
6052    /**
6053     * Update the permission flags for all packages and runtime permissions of a user in order
6054     * to allow device or profile owner to remove POLICY_FIXED.
6055     */
6056    @Override
6057    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
6058        if (!sUserManager.exists(userId)) {
6059            return;
6060        }
6061
6062        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
6063
6064        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6065                true /* requireFullPermission */, true /* checkShell */,
6066                "updatePermissionFlagsForAllApps");
6067
6068        // Only the system can change system fixed flags.
6069        if (getCallingUid() != Process.SYSTEM_UID) {
6070            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
6071            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
6072        }
6073
6074        synchronized (mPackages) {
6075            boolean changed = false;
6076            final int packageCount = mPackages.size();
6077            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
6078                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
6079                final PackageSetting ps = (PackageSetting) pkg.mExtras;
6080                if (ps == null) {
6081                    continue;
6082                }
6083                PermissionsState permissionsState = ps.getPermissionsState();
6084                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
6085                        userId, flagMask, flagValues);
6086            }
6087            if (changed) {
6088                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
6089            }
6090        }
6091    }
6092
6093    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
6094        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
6095                != PackageManager.PERMISSION_GRANTED
6096            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
6097                != PackageManager.PERMISSION_GRANTED) {
6098            throw new SecurityException(message + " requires "
6099                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
6100                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
6101        }
6102    }
6103
6104    @Override
6105    public boolean shouldShowRequestPermissionRationale(String permissionName,
6106            String packageName, int userId) {
6107        if (UserHandle.getCallingUserId() != userId) {
6108            mContext.enforceCallingPermission(
6109                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
6110                    "canShowRequestPermissionRationale for user " + userId);
6111        }
6112
6113        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
6114        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
6115            return false;
6116        }
6117
6118        if (checkPermission(permissionName, packageName, userId)
6119                == PackageManager.PERMISSION_GRANTED) {
6120            return false;
6121        }
6122
6123        final int flags;
6124
6125        final long identity = Binder.clearCallingIdentity();
6126        try {
6127            flags = getPermissionFlags(permissionName,
6128                    packageName, userId);
6129        } finally {
6130            Binder.restoreCallingIdentity(identity);
6131        }
6132
6133        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
6134                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
6135                | PackageManager.FLAG_PERMISSION_USER_FIXED;
6136
6137        if ((flags & fixedFlags) != 0) {
6138            return false;
6139        }
6140
6141        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
6142    }
6143
6144    @Override
6145    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6146        mContext.enforceCallingOrSelfPermission(
6147                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
6148                "addOnPermissionsChangeListener");
6149
6150        synchronized (mPackages) {
6151            mOnPermissionChangeListeners.addListenerLocked(listener);
6152        }
6153    }
6154
6155    @Override
6156    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6157        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6158            throw new SecurityException("Instant applications don't have access to this method");
6159        }
6160        synchronized (mPackages) {
6161            mOnPermissionChangeListeners.removeListenerLocked(listener);
6162        }
6163    }
6164
6165    @Override
6166    public boolean isProtectedBroadcast(String actionName) {
6167        // allow instant applications
6168        synchronized (mProtectedBroadcasts) {
6169            if (mProtectedBroadcasts.contains(actionName)) {
6170                return true;
6171            } else if (actionName != null) {
6172                // TODO: remove these terrible hacks
6173                if (actionName.startsWith("android.net.netmon.lingerExpired")
6174                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
6175                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
6176                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
6177                    return true;
6178                }
6179            }
6180        }
6181        return false;
6182    }
6183
6184    @Override
6185    public int checkSignatures(String pkg1, String pkg2) {
6186        synchronized (mPackages) {
6187            final PackageParser.Package p1 = mPackages.get(pkg1);
6188            final PackageParser.Package p2 = mPackages.get(pkg2);
6189            if (p1 == null || p1.mExtras == null
6190                    || p2 == null || p2.mExtras == null) {
6191                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6192            }
6193            final int callingUid = Binder.getCallingUid();
6194            final int callingUserId = UserHandle.getUserId(callingUid);
6195            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
6196            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
6197            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
6198                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
6199                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6200            }
6201            return compareSignatures(p1.mSignatures, p2.mSignatures);
6202        }
6203    }
6204
6205    @Override
6206    public int checkUidSignatures(int uid1, int uid2) {
6207        final int callingUid = Binder.getCallingUid();
6208        final int callingUserId = UserHandle.getUserId(callingUid);
6209        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6210        // Map to base uids.
6211        uid1 = UserHandle.getAppId(uid1);
6212        uid2 = UserHandle.getAppId(uid2);
6213        // reader
6214        synchronized (mPackages) {
6215            Signature[] s1;
6216            Signature[] s2;
6217            Object obj = mSettings.getUserIdLPr(uid1);
6218            if (obj != null) {
6219                if (obj instanceof SharedUserSetting) {
6220                    if (isCallerInstantApp) {
6221                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6222                    }
6223                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
6224                } else if (obj instanceof PackageSetting) {
6225                    final PackageSetting ps = (PackageSetting) obj;
6226                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6227                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6228                    }
6229                    s1 = ps.signatures.mSignatures;
6230                } else {
6231                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6232                }
6233            } else {
6234                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6235            }
6236            obj = mSettings.getUserIdLPr(uid2);
6237            if (obj != null) {
6238                if (obj instanceof SharedUserSetting) {
6239                    if (isCallerInstantApp) {
6240                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6241                    }
6242                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
6243                } else if (obj instanceof PackageSetting) {
6244                    final PackageSetting ps = (PackageSetting) obj;
6245                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6246                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6247                    }
6248                    s2 = ps.signatures.mSignatures;
6249                } else {
6250                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6251                }
6252            } else {
6253                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6254            }
6255            return compareSignatures(s1, s2);
6256        }
6257    }
6258
6259    /**
6260     * This method should typically only be used when granting or revoking
6261     * permissions, since the app may immediately restart after this call.
6262     * <p>
6263     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
6264     * guard your work against the app being relaunched.
6265     */
6266    private void killUid(int appId, int userId, String reason) {
6267        final long identity = Binder.clearCallingIdentity();
6268        try {
6269            IActivityManager am = ActivityManager.getService();
6270            if (am != null) {
6271                try {
6272                    am.killUid(appId, userId, reason);
6273                } catch (RemoteException e) {
6274                    /* ignore - same process */
6275                }
6276            }
6277        } finally {
6278            Binder.restoreCallingIdentity(identity);
6279        }
6280    }
6281
6282    /**
6283     * Compares two sets of signatures. Returns:
6284     * <br />
6285     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
6286     * <br />
6287     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
6288     * <br />
6289     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
6290     * <br />
6291     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
6292     * <br />
6293     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
6294     */
6295    static int compareSignatures(Signature[] s1, Signature[] s2) {
6296        if (s1 == null) {
6297            return s2 == null
6298                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
6299                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
6300        }
6301
6302        if (s2 == null) {
6303            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
6304        }
6305
6306        if (s1.length != s2.length) {
6307            return PackageManager.SIGNATURE_NO_MATCH;
6308        }
6309
6310        // Since both signature sets are of size 1, we can compare without HashSets.
6311        if (s1.length == 1) {
6312            return s1[0].equals(s2[0]) ?
6313                    PackageManager.SIGNATURE_MATCH :
6314                    PackageManager.SIGNATURE_NO_MATCH;
6315        }
6316
6317        ArraySet<Signature> set1 = new ArraySet<Signature>();
6318        for (Signature sig : s1) {
6319            set1.add(sig);
6320        }
6321        ArraySet<Signature> set2 = new ArraySet<Signature>();
6322        for (Signature sig : s2) {
6323            set2.add(sig);
6324        }
6325        // Make sure s2 contains all signatures in s1.
6326        if (set1.equals(set2)) {
6327            return PackageManager.SIGNATURE_MATCH;
6328        }
6329        return PackageManager.SIGNATURE_NO_MATCH;
6330    }
6331
6332    /**
6333     * If the database version for this type of package (internal storage or
6334     * external storage) is less than the version where package signatures
6335     * were updated, return true.
6336     */
6337    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6338        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6339        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
6340    }
6341
6342    /**
6343     * Used for backward compatibility to make sure any packages with
6344     * certificate chains get upgraded to the new style. {@code existingSigs}
6345     * will be in the old format (since they were stored on disk from before the
6346     * system upgrade) and {@code scannedSigs} will be in the newer format.
6347     */
6348    private int compareSignaturesCompat(PackageSignatures existingSigs,
6349            PackageParser.Package scannedPkg) {
6350        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
6351            return PackageManager.SIGNATURE_NO_MATCH;
6352        }
6353
6354        ArraySet<Signature> existingSet = new ArraySet<Signature>();
6355        for (Signature sig : existingSigs.mSignatures) {
6356            existingSet.add(sig);
6357        }
6358        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
6359        for (Signature sig : scannedPkg.mSignatures) {
6360            try {
6361                Signature[] chainSignatures = sig.getChainSignatures();
6362                for (Signature chainSig : chainSignatures) {
6363                    scannedCompatSet.add(chainSig);
6364                }
6365            } catch (CertificateEncodingException e) {
6366                scannedCompatSet.add(sig);
6367            }
6368        }
6369        /*
6370         * Make sure the expanded scanned set contains all signatures in the
6371         * existing one.
6372         */
6373        if (scannedCompatSet.equals(existingSet)) {
6374            // Migrate the old signatures to the new scheme.
6375            existingSigs.assignSignatures(scannedPkg.mSignatures);
6376            // The new KeySets will be re-added later in the scanning process.
6377            synchronized (mPackages) {
6378                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
6379            }
6380            return PackageManager.SIGNATURE_MATCH;
6381        }
6382        return PackageManager.SIGNATURE_NO_MATCH;
6383    }
6384
6385    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6386        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6387        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6388    }
6389
6390    private int compareSignaturesRecover(PackageSignatures existingSigs,
6391            PackageParser.Package scannedPkg) {
6392        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
6393            return PackageManager.SIGNATURE_NO_MATCH;
6394        }
6395
6396        String msg = null;
6397        try {
6398            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
6399                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
6400                        + scannedPkg.packageName);
6401                return PackageManager.SIGNATURE_MATCH;
6402            }
6403        } catch (CertificateException e) {
6404            msg = e.getMessage();
6405        }
6406
6407        logCriticalInfo(Log.INFO,
6408                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
6409        return PackageManager.SIGNATURE_NO_MATCH;
6410    }
6411
6412    @Override
6413    public List<String> getAllPackages() {
6414        final int callingUid = Binder.getCallingUid();
6415        final int callingUserId = UserHandle.getUserId(callingUid);
6416        synchronized (mPackages) {
6417            if (canViewInstantApps(callingUid, callingUserId)) {
6418                return new ArrayList<String>(mPackages.keySet());
6419            }
6420            final String instantAppPkgName = getInstantAppPackageName(callingUid);
6421            final List<String> result = new ArrayList<>();
6422            if (instantAppPkgName != null) {
6423                // caller is an instant application; filter unexposed applications
6424                for (PackageParser.Package pkg : mPackages.values()) {
6425                    if (!pkg.visibleToInstantApps) {
6426                        continue;
6427                    }
6428                    result.add(pkg.packageName);
6429                }
6430            } else {
6431                // caller is a normal application; filter instant applications
6432                for (PackageParser.Package pkg : mPackages.values()) {
6433                    final PackageSetting ps =
6434                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6435                    if (ps != null
6436                            && ps.getInstantApp(callingUserId)
6437                            && !mInstantAppRegistry.isInstantAccessGranted(
6438                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6439                        continue;
6440                    }
6441                    result.add(pkg.packageName);
6442                }
6443            }
6444            return result;
6445        }
6446    }
6447
6448    @Override
6449    public String[] getPackagesForUid(int uid) {
6450        final int callingUid = Binder.getCallingUid();
6451        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6452        final int userId = UserHandle.getUserId(uid);
6453        uid = UserHandle.getAppId(uid);
6454        // reader
6455        synchronized (mPackages) {
6456            Object obj = mSettings.getUserIdLPr(uid);
6457            if (obj instanceof SharedUserSetting) {
6458                if (isCallerInstantApp) {
6459                    return null;
6460                }
6461                final SharedUserSetting sus = (SharedUserSetting) obj;
6462                final int N = sus.packages.size();
6463                String[] res = new String[N];
6464                final Iterator<PackageSetting> it = sus.packages.iterator();
6465                int i = 0;
6466                while (it.hasNext()) {
6467                    PackageSetting ps = it.next();
6468                    if (ps.getInstalled(userId)) {
6469                        res[i++] = ps.name;
6470                    } else {
6471                        res = ArrayUtils.removeElement(String.class, res, res[i]);
6472                    }
6473                }
6474                return res;
6475            } else if (obj instanceof PackageSetting) {
6476                final PackageSetting ps = (PackageSetting) obj;
6477                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6478                    return new String[]{ps.name};
6479                }
6480            }
6481        }
6482        return null;
6483    }
6484
6485    @Override
6486    public String getNameForUid(int uid) {
6487        final int callingUid = Binder.getCallingUid();
6488        if (getInstantAppPackageName(callingUid) != null) {
6489            return null;
6490        }
6491        synchronized (mPackages) {
6492            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6493            if (obj instanceof SharedUserSetting) {
6494                final SharedUserSetting sus = (SharedUserSetting) obj;
6495                return sus.name + ":" + sus.userId;
6496            } else if (obj instanceof PackageSetting) {
6497                final PackageSetting ps = (PackageSetting) obj;
6498                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6499                    return null;
6500                }
6501                return ps.name;
6502            }
6503            return null;
6504        }
6505    }
6506
6507    @Override
6508    public String[] getNamesForUids(int[] uids) {
6509        if (uids == null || uids.length == 0) {
6510            return null;
6511        }
6512        final int callingUid = Binder.getCallingUid();
6513        if (getInstantAppPackageName(callingUid) != null) {
6514            return null;
6515        }
6516        final String[] names = new String[uids.length];
6517        synchronized (mPackages) {
6518            for (int i = uids.length - 1; i >= 0; i--) {
6519                final int uid = uids[i];
6520                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6521                if (obj instanceof SharedUserSetting) {
6522                    final SharedUserSetting sus = (SharedUserSetting) obj;
6523                    names[i] = "shared:" + sus.name;
6524                } else if (obj instanceof PackageSetting) {
6525                    final PackageSetting ps = (PackageSetting) obj;
6526                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6527                        names[i] = null;
6528                    } else {
6529                        names[i] = ps.name;
6530                    }
6531                } else {
6532                    names[i] = null;
6533                }
6534            }
6535        }
6536        return names;
6537    }
6538
6539    @Override
6540    public int getUidForSharedUser(String sharedUserName) {
6541        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6542            return -1;
6543        }
6544        if (sharedUserName == null) {
6545            return -1;
6546        }
6547        // reader
6548        synchronized (mPackages) {
6549            SharedUserSetting suid;
6550            try {
6551                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6552                if (suid != null) {
6553                    return suid.userId;
6554                }
6555            } catch (PackageManagerException ignore) {
6556                // can't happen, but, still need to catch it
6557            }
6558            return -1;
6559        }
6560    }
6561
6562    @Override
6563    public int getFlagsForUid(int uid) {
6564        final int callingUid = Binder.getCallingUid();
6565        if (getInstantAppPackageName(callingUid) != null) {
6566            return 0;
6567        }
6568        synchronized (mPackages) {
6569            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6570            if (obj instanceof SharedUserSetting) {
6571                final SharedUserSetting sus = (SharedUserSetting) obj;
6572                return sus.pkgFlags;
6573            } else if (obj instanceof PackageSetting) {
6574                final PackageSetting ps = (PackageSetting) obj;
6575                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6576                    return 0;
6577                }
6578                return ps.pkgFlags;
6579            }
6580        }
6581        return 0;
6582    }
6583
6584    @Override
6585    public int getPrivateFlagsForUid(int uid) {
6586        final int callingUid = Binder.getCallingUid();
6587        if (getInstantAppPackageName(callingUid) != null) {
6588            return 0;
6589        }
6590        synchronized (mPackages) {
6591            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6592            if (obj instanceof SharedUserSetting) {
6593                final SharedUserSetting sus = (SharedUserSetting) obj;
6594                return sus.pkgPrivateFlags;
6595            } else if (obj instanceof PackageSetting) {
6596                final PackageSetting ps = (PackageSetting) obj;
6597                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6598                    return 0;
6599                }
6600                return ps.pkgPrivateFlags;
6601            }
6602        }
6603        return 0;
6604    }
6605
6606    @Override
6607    public boolean isUidPrivileged(int uid) {
6608        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6609            return false;
6610        }
6611        uid = UserHandle.getAppId(uid);
6612        // reader
6613        synchronized (mPackages) {
6614            Object obj = mSettings.getUserIdLPr(uid);
6615            if (obj instanceof SharedUserSetting) {
6616                final SharedUserSetting sus = (SharedUserSetting) obj;
6617                final Iterator<PackageSetting> it = sus.packages.iterator();
6618                while (it.hasNext()) {
6619                    if (it.next().isPrivileged()) {
6620                        return true;
6621                    }
6622                }
6623            } else if (obj instanceof PackageSetting) {
6624                final PackageSetting ps = (PackageSetting) obj;
6625                return ps.isPrivileged();
6626            }
6627        }
6628        return false;
6629    }
6630
6631    @Override
6632    public String[] getAppOpPermissionPackages(String permissionName) {
6633        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6634            return null;
6635        }
6636        synchronized (mPackages) {
6637            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6638            if (pkgs == null) {
6639                return null;
6640            }
6641            return pkgs.toArray(new String[pkgs.size()]);
6642        }
6643    }
6644
6645    @Override
6646    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6647            int flags, int userId) {
6648        return resolveIntentInternal(
6649                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6650    }
6651
6652    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6653            int flags, int userId, boolean resolveForStart) {
6654        try {
6655            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6656
6657            if (!sUserManager.exists(userId)) return null;
6658            final int callingUid = Binder.getCallingUid();
6659            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6660            enforceCrossUserPermission(callingUid, userId,
6661                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6662
6663            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6664            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6665                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
6666            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6667
6668            final ResolveInfo bestChoice =
6669                    chooseBestActivity(intent, resolvedType, flags, query, userId);
6670            return bestChoice;
6671        } finally {
6672            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6673        }
6674    }
6675
6676    @Override
6677    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6678        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6679            throw new SecurityException(
6680                    "findPersistentPreferredActivity can only be run by the system");
6681        }
6682        if (!sUserManager.exists(userId)) {
6683            return null;
6684        }
6685        final int callingUid = Binder.getCallingUid();
6686        intent = updateIntentForResolve(intent);
6687        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6688        final int flags = updateFlagsForResolve(
6689                0, userId, intent, callingUid, false /*includeInstantApps*/);
6690        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6691                userId);
6692        synchronized (mPackages) {
6693            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6694                    userId);
6695        }
6696    }
6697
6698    @Override
6699    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6700            IntentFilter filter, int match, ComponentName activity) {
6701        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6702            return;
6703        }
6704        final int userId = UserHandle.getCallingUserId();
6705        if (DEBUG_PREFERRED) {
6706            Log.v(TAG, "setLastChosenActivity intent=" + intent
6707                + " resolvedType=" + resolvedType
6708                + " flags=" + flags
6709                + " filter=" + filter
6710                + " match=" + match
6711                + " activity=" + activity);
6712            filter.dump(new PrintStreamPrinter(System.out), "    ");
6713        }
6714        intent.setComponent(null);
6715        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6716                userId);
6717        // Find any earlier preferred or last chosen entries and nuke them
6718        findPreferredActivity(intent, resolvedType,
6719                flags, query, 0, false, true, false, userId);
6720        // Add the new activity as the last chosen for this filter
6721        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6722                "Setting last chosen");
6723    }
6724
6725    @Override
6726    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6727        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6728            return null;
6729        }
6730        final int userId = UserHandle.getCallingUserId();
6731        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6732        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6733                userId);
6734        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6735                false, false, false, userId);
6736    }
6737
6738    /**
6739     * Returns whether or not instant apps have been disabled remotely.
6740     */
6741    private boolean isEphemeralDisabled() {
6742        return mEphemeralAppsDisabled;
6743    }
6744
6745    private boolean isInstantAppAllowed(
6746            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6747            boolean skipPackageCheck) {
6748        if (mInstantAppResolverConnection == null) {
6749            return false;
6750        }
6751        if (mInstantAppInstallerActivity == null) {
6752            return false;
6753        }
6754        if (intent.getComponent() != null) {
6755            return false;
6756        }
6757        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6758            return false;
6759        }
6760        if (!skipPackageCheck && intent.getPackage() != null) {
6761            return false;
6762        }
6763        final boolean isWebUri = hasWebURI(intent);
6764        if (!isWebUri || intent.getData().getHost() == null) {
6765            return false;
6766        }
6767        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6768        // Or if there's already an ephemeral app installed that handles the action
6769        synchronized (mPackages) {
6770            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6771            for (int n = 0; n < count; n++) {
6772                final ResolveInfo info = resolvedActivities.get(n);
6773                final String packageName = info.activityInfo.packageName;
6774                final PackageSetting ps = mSettings.mPackages.get(packageName);
6775                if (ps != null) {
6776                    // only check domain verification status if the app is not a browser
6777                    if (!info.handleAllWebDataURI) {
6778                        // Try to get the status from User settings first
6779                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6780                        final int status = (int) (packedStatus >> 32);
6781                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6782                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6783                            if (DEBUG_EPHEMERAL) {
6784                                Slog.v(TAG, "DENY instant app;"
6785                                    + " pkg: " + packageName + ", status: " + status);
6786                            }
6787                            return false;
6788                        }
6789                    }
6790                    if (ps.getInstantApp(userId)) {
6791                        if (DEBUG_EPHEMERAL) {
6792                            Slog.v(TAG, "DENY instant app installed;"
6793                                    + " pkg: " + packageName);
6794                        }
6795                        return false;
6796                    }
6797                }
6798            }
6799        }
6800        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6801        return true;
6802    }
6803
6804    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6805            Intent origIntent, String resolvedType, String callingPackage,
6806            Bundle verificationBundle, int userId) {
6807        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6808                new InstantAppRequest(responseObj, origIntent, resolvedType,
6809                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
6810        mHandler.sendMessage(msg);
6811    }
6812
6813    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6814            int flags, List<ResolveInfo> query, int userId) {
6815        if (query != null) {
6816            final int N = query.size();
6817            if (N == 1) {
6818                return query.get(0);
6819            } else if (N > 1) {
6820                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6821                // If there is more than one activity with the same priority,
6822                // then let the user decide between them.
6823                ResolveInfo r0 = query.get(0);
6824                ResolveInfo r1 = query.get(1);
6825                if (DEBUG_INTENT_MATCHING || debug) {
6826                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6827                            + r1.activityInfo.name + "=" + r1.priority);
6828                }
6829                // If the first activity has a higher priority, or a different
6830                // default, then it is always desirable to pick it.
6831                if (r0.priority != r1.priority
6832                        || r0.preferredOrder != r1.preferredOrder
6833                        || r0.isDefault != r1.isDefault) {
6834                    return query.get(0);
6835                }
6836                // If we have saved a preference for a preferred activity for
6837                // this Intent, use that.
6838                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6839                        flags, query, r0.priority, true, false, debug, userId);
6840                if (ri != null) {
6841                    return ri;
6842                }
6843                // If we have an ephemeral app, use it
6844                for (int i = 0; i < N; i++) {
6845                    ri = query.get(i);
6846                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6847                        final String packageName = ri.activityInfo.packageName;
6848                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6849                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6850                        final int status = (int)(packedStatus >> 32);
6851                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6852                            return ri;
6853                        }
6854                    }
6855                }
6856                ri = new ResolveInfo(mResolveInfo);
6857                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6858                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6859                // If all of the options come from the same package, show the application's
6860                // label and icon instead of the generic resolver's.
6861                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6862                // and then throw away the ResolveInfo itself, meaning that the caller loses
6863                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6864                // a fallback for this case; we only set the target package's resources on
6865                // the ResolveInfo, not the ActivityInfo.
6866                final String intentPackage = intent.getPackage();
6867                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6868                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6869                    ri.resolvePackageName = intentPackage;
6870                    if (userNeedsBadging(userId)) {
6871                        ri.noResourceId = true;
6872                    } else {
6873                        ri.icon = appi.icon;
6874                    }
6875                    ri.iconResourceId = appi.icon;
6876                    ri.labelRes = appi.labelRes;
6877                }
6878                ri.activityInfo.applicationInfo = new ApplicationInfo(
6879                        ri.activityInfo.applicationInfo);
6880                if (userId != 0) {
6881                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6882                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6883                }
6884                // Make sure that the resolver is displayable in car mode
6885                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6886                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6887                return ri;
6888            }
6889        }
6890        return null;
6891    }
6892
6893    /**
6894     * Return true if the given list is not empty and all of its contents have
6895     * an activityInfo with the given package name.
6896     */
6897    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6898        if (ArrayUtils.isEmpty(list)) {
6899            return false;
6900        }
6901        for (int i = 0, N = list.size(); i < N; i++) {
6902            final ResolveInfo ri = list.get(i);
6903            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6904            if (ai == null || !packageName.equals(ai.packageName)) {
6905                return false;
6906            }
6907        }
6908        return true;
6909    }
6910
6911    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6912            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6913        final int N = query.size();
6914        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6915                .get(userId);
6916        // Get the list of persistent preferred activities that handle the intent
6917        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6918        List<PersistentPreferredActivity> pprefs = ppir != null
6919                ? ppir.queryIntent(intent, resolvedType,
6920                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6921                        userId)
6922                : null;
6923        if (pprefs != null && pprefs.size() > 0) {
6924            final int M = pprefs.size();
6925            for (int i=0; i<M; i++) {
6926                final PersistentPreferredActivity ppa = pprefs.get(i);
6927                if (DEBUG_PREFERRED || debug) {
6928                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6929                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6930                            + "\n  component=" + ppa.mComponent);
6931                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6932                }
6933                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6934                        flags | MATCH_DISABLED_COMPONENTS, userId);
6935                if (DEBUG_PREFERRED || debug) {
6936                    Slog.v(TAG, "Found persistent preferred activity:");
6937                    if (ai != null) {
6938                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6939                    } else {
6940                        Slog.v(TAG, "  null");
6941                    }
6942                }
6943                if (ai == null) {
6944                    // This previously registered persistent preferred activity
6945                    // component is no longer known. Ignore it and do NOT remove it.
6946                    continue;
6947                }
6948                for (int j=0; j<N; j++) {
6949                    final ResolveInfo ri = query.get(j);
6950                    if (!ri.activityInfo.applicationInfo.packageName
6951                            .equals(ai.applicationInfo.packageName)) {
6952                        continue;
6953                    }
6954                    if (!ri.activityInfo.name.equals(ai.name)) {
6955                        continue;
6956                    }
6957                    //  Found a persistent preference that can handle the intent.
6958                    if (DEBUG_PREFERRED || debug) {
6959                        Slog.v(TAG, "Returning persistent preferred activity: " +
6960                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6961                    }
6962                    return ri;
6963                }
6964            }
6965        }
6966        return null;
6967    }
6968
6969    // TODO: handle preferred activities missing while user has amnesia
6970    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6971            List<ResolveInfo> query, int priority, boolean always,
6972            boolean removeMatches, boolean debug, int userId) {
6973        if (!sUserManager.exists(userId)) return null;
6974        final int callingUid = Binder.getCallingUid();
6975        flags = updateFlagsForResolve(
6976                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6977        intent = updateIntentForResolve(intent);
6978        // writer
6979        synchronized (mPackages) {
6980            // Try to find a matching persistent preferred activity.
6981            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6982                    debug, userId);
6983
6984            // If a persistent preferred activity matched, use it.
6985            if (pri != null) {
6986                return pri;
6987            }
6988
6989            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6990            // Get the list of preferred activities that handle the intent
6991            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6992            List<PreferredActivity> prefs = pir != null
6993                    ? pir.queryIntent(intent, resolvedType,
6994                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6995                            userId)
6996                    : null;
6997            if (prefs != null && prefs.size() > 0) {
6998                boolean changed = false;
6999                try {
7000                    // First figure out how good the original match set is.
7001                    // We will only allow preferred activities that came
7002                    // from the same match quality.
7003                    int match = 0;
7004
7005                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
7006
7007                    final int N = query.size();
7008                    for (int j=0; j<N; j++) {
7009                        final ResolveInfo ri = query.get(j);
7010                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
7011                                + ": 0x" + Integer.toHexString(match));
7012                        if (ri.match > match) {
7013                            match = ri.match;
7014                        }
7015                    }
7016
7017                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
7018                            + Integer.toHexString(match));
7019
7020                    match &= IntentFilter.MATCH_CATEGORY_MASK;
7021                    final int M = prefs.size();
7022                    for (int i=0; i<M; i++) {
7023                        final PreferredActivity pa = prefs.get(i);
7024                        if (DEBUG_PREFERRED || debug) {
7025                            Slog.v(TAG, "Checking PreferredActivity ds="
7026                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
7027                                    + "\n  component=" + pa.mPref.mComponent);
7028                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
7029                        }
7030                        if (pa.mPref.mMatch != match) {
7031                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
7032                                    + Integer.toHexString(pa.mPref.mMatch));
7033                            continue;
7034                        }
7035                        // If it's not an "always" type preferred activity and that's what we're
7036                        // looking for, skip it.
7037                        if (always && !pa.mPref.mAlways) {
7038                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
7039                            continue;
7040                        }
7041                        final ActivityInfo ai = getActivityInfo(
7042                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
7043                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
7044                                userId);
7045                        if (DEBUG_PREFERRED || debug) {
7046                            Slog.v(TAG, "Found preferred activity:");
7047                            if (ai != null) {
7048                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
7049                            } else {
7050                                Slog.v(TAG, "  null");
7051                            }
7052                        }
7053                        if (ai == null) {
7054                            // This previously registered preferred activity
7055                            // component is no longer known.  Most likely an update
7056                            // to the app was installed and in the new version this
7057                            // component no longer exists.  Clean it up by removing
7058                            // it from the preferred activities list, and skip it.
7059                            Slog.w(TAG, "Removing dangling preferred activity: "
7060                                    + pa.mPref.mComponent);
7061                            pir.removeFilter(pa);
7062                            changed = true;
7063                            continue;
7064                        }
7065                        for (int j=0; j<N; j++) {
7066                            final ResolveInfo ri = query.get(j);
7067                            if (!ri.activityInfo.applicationInfo.packageName
7068                                    .equals(ai.applicationInfo.packageName)) {
7069                                continue;
7070                            }
7071                            if (!ri.activityInfo.name.equals(ai.name)) {
7072                                continue;
7073                            }
7074
7075                            if (removeMatches) {
7076                                pir.removeFilter(pa);
7077                                changed = true;
7078                                if (DEBUG_PREFERRED) {
7079                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
7080                                }
7081                                break;
7082                            }
7083
7084                            // Okay we found a previously set preferred or last chosen app.
7085                            // If the result set is different from when this
7086                            // was created, and is not a subset of the preferred set, we need to
7087                            // clear it and re-ask the user their preference, if we're looking for
7088                            // an "always" type entry.
7089                            if (always && !pa.mPref.sameSet(query)) {
7090                                if (pa.mPref.isSuperset(query)) {
7091                                    // some components of the set are no longer present in
7092                                    // the query, but the preferred activity can still be reused
7093                                    if (DEBUG_PREFERRED) {
7094                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
7095                                                + " still valid as only non-preferred components"
7096                                                + " were removed for " + intent + " type "
7097                                                + resolvedType);
7098                                    }
7099                                    // remove obsolete components and re-add the up-to-date filter
7100                                    PreferredActivity freshPa = new PreferredActivity(pa,
7101                                            pa.mPref.mMatch,
7102                                            pa.mPref.discardObsoleteComponents(query),
7103                                            pa.mPref.mComponent,
7104                                            pa.mPref.mAlways);
7105                                    pir.removeFilter(pa);
7106                                    pir.addFilter(freshPa);
7107                                    changed = true;
7108                                } else {
7109                                    Slog.i(TAG,
7110                                            "Result set changed, dropping preferred activity for "
7111                                                    + intent + " type " + resolvedType);
7112                                    if (DEBUG_PREFERRED) {
7113                                        Slog.v(TAG, "Removing preferred activity since set changed "
7114                                                + pa.mPref.mComponent);
7115                                    }
7116                                    pir.removeFilter(pa);
7117                                    // Re-add the filter as a "last chosen" entry (!always)
7118                                    PreferredActivity lastChosen = new PreferredActivity(
7119                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
7120                                    pir.addFilter(lastChosen);
7121                                    changed = true;
7122                                    return null;
7123                                }
7124                            }
7125
7126                            // Yay! Either the set matched or we're looking for the last chosen
7127                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
7128                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
7129                            return ri;
7130                        }
7131                    }
7132                } finally {
7133                    if (changed) {
7134                        if (DEBUG_PREFERRED) {
7135                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
7136                        }
7137                        scheduleWritePackageRestrictionsLocked(userId);
7138                    }
7139                }
7140            }
7141        }
7142        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
7143        return null;
7144    }
7145
7146    /*
7147     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
7148     */
7149    @Override
7150    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
7151            int targetUserId) {
7152        mContext.enforceCallingOrSelfPermission(
7153                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
7154        List<CrossProfileIntentFilter> matches =
7155                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
7156        if (matches != null) {
7157            int size = matches.size();
7158            for (int i = 0; i < size; i++) {
7159                if (matches.get(i).getTargetUserId() == targetUserId) return true;
7160            }
7161        }
7162        if (hasWebURI(intent)) {
7163            // cross-profile app linking works only towards the parent.
7164            final int callingUid = Binder.getCallingUid();
7165            final UserInfo parent = getProfileParent(sourceUserId);
7166            synchronized(mPackages) {
7167                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
7168                        false /*includeInstantApps*/);
7169                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
7170                        intent, resolvedType, flags, sourceUserId, parent.id);
7171                return xpDomainInfo != null;
7172            }
7173        }
7174        return false;
7175    }
7176
7177    private UserInfo getProfileParent(int userId) {
7178        final long identity = Binder.clearCallingIdentity();
7179        try {
7180            return sUserManager.getProfileParent(userId);
7181        } finally {
7182            Binder.restoreCallingIdentity(identity);
7183        }
7184    }
7185
7186    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
7187            String resolvedType, int userId) {
7188        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
7189        if (resolver != null) {
7190            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
7191        }
7192        return null;
7193    }
7194
7195    @Override
7196    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
7197            String resolvedType, int flags, int userId) {
7198        try {
7199            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
7200
7201            return new ParceledListSlice<>(
7202                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
7203        } finally {
7204            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7205        }
7206    }
7207
7208    /**
7209     * Returns the package name of the calling Uid if it's an instant app. If it isn't
7210     * instant, returns {@code null}.
7211     */
7212    private String getInstantAppPackageName(int callingUid) {
7213        synchronized (mPackages) {
7214            // If the caller is an isolated app use the owner's uid for the lookup.
7215            if (Process.isIsolated(callingUid)) {
7216                callingUid = mIsolatedOwners.get(callingUid);
7217            }
7218            final int appId = UserHandle.getAppId(callingUid);
7219            final Object obj = mSettings.getUserIdLPr(appId);
7220            if (obj instanceof PackageSetting) {
7221                final PackageSetting ps = (PackageSetting) obj;
7222                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
7223                return isInstantApp ? ps.pkg.packageName : null;
7224            }
7225        }
7226        return null;
7227    }
7228
7229    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7230            String resolvedType, int flags, int userId) {
7231        return queryIntentActivitiesInternal(
7232                intent, resolvedType, flags, Binder.getCallingUid(), userId,
7233                false /*resolveForStart*/, true /*allowDynamicSplits*/);
7234    }
7235
7236    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7237            String resolvedType, int flags, int filterCallingUid, int userId,
7238            boolean resolveForStart, boolean allowDynamicSplits) {
7239        if (!sUserManager.exists(userId)) return Collections.emptyList();
7240        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
7241        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7242                false /* requireFullPermission */, false /* checkShell */,
7243                "query intent activities");
7244        final String pkgName = intent.getPackage();
7245        ComponentName comp = intent.getComponent();
7246        if (comp == null) {
7247            if (intent.getSelector() != null) {
7248                intent = intent.getSelector();
7249                comp = intent.getComponent();
7250            }
7251        }
7252
7253        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
7254                comp != null || pkgName != null /*onlyExposedExplicitly*/);
7255        if (comp != null) {
7256            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7257            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
7258            if (ai != null) {
7259                // When specifying an explicit component, we prevent the activity from being
7260                // used when either 1) the calling package is normal and the activity is within
7261                // an ephemeral application or 2) the calling package is ephemeral and the
7262                // activity is not visible to ephemeral applications.
7263                final boolean matchInstantApp =
7264                        (flags & PackageManager.MATCH_INSTANT) != 0;
7265                final boolean matchVisibleToInstantAppOnly =
7266                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7267                final boolean matchExplicitlyVisibleOnly =
7268                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7269                final boolean isCallerInstantApp =
7270                        instantAppPkgName != null;
7271                final boolean isTargetSameInstantApp =
7272                        comp.getPackageName().equals(instantAppPkgName);
7273                final boolean isTargetInstantApp =
7274                        (ai.applicationInfo.privateFlags
7275                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7276                final boolean isTargetVisibleToInstantApp =
7277                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7278                final boolean isTargetExplicitlyVisibleToInstantApp =
7279                        isTargetVisibleToInstantApp
7280                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7281                final boolean isTargetHiddenFromInstantApp =
7282                        !isTargetVisibleToInstantApp
7283                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7284                final boolean blockResolution =
7285                        !isTargetSameInstantApp
7286                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7287                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7288                                        && isTargetHiddenFromInstantApp));
7289                if (!blockResolution) {
7290                    final ResolveInfo ri = new ResolveInfo();
7291                    ri.activityInfo = ai;
7292                    list.add(ri);
7293                }
7294            }
7295            return applyPostResolutionFilter(
7296                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
7297        }
7298
7299        // reader
7300        boolean sortResult = false;
7301        boolean addEphemeral = false;
7302        List<ResolveInfo> result;
7303        final boolean ephemeralDisabled = isEphemeralDisabled();
7304        synchronized (mPackages) {
7305            if (pkgName == null) {
7306                List<CrossProfileIntentFilter> matchingFilters =
7307                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
7308                // Check for results that need to skip the current profile.
7309                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
7310                        resolvedType, flags, userId);
7311                if (xpResolveInfo != null) {
7312                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
7313                    xpResult.add(xpResolveInfo);
7314                    return applyPostResolutionFilter(
7315                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
7316                            allowDynamicSplits, filterCallingUid, userId);
7317                }
7318
7319                // Check for results in the current profile.
7320                result = filterIfNotSystemUser(mActivities.queryIntent(
7321                        intent, resolvedType, flags, userId), userId);
7322                addEphemeral = !ephemeralDisabled
7323                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
7324                // Check for cross profile results.
7325                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
7326                xpResolveInfo = queryCrossProfileIntents(
7327                        matchingFilters, intent, resolvedType, flags, userId,
7328                        hasNonNegativePriorityResult);
7329                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
7330                    boolean isVisibleToUser = filterIfNotSystemUser(
7331                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
7332                    if (isVisibleToUser) {
7333                        result.add(xpResolveInfo);
7334                        sortResult = true;
7335                    }
7336                }
7337                if (hasWebURI(intent)) {
7338                    CrossProfileDomainInfo xpDomainInfo = null;
7339                    final UserInfo parent = getProfileParent(userId);
7340                    if (parent != null) {
7341                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
7342                                flags, userId, parent.id);
7343                    }
7344                    if (xpDomainInfo != null) {
7345                        if (xpResolveInfo != null) {
7346                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
7347                            // in the result.
7348                            result.remove(xpResolveInfo);
7349                        }
7350                        if (result.size() == 0 && !addEphemeral) {
7351                            // No result in current profile, but found candidate in parent user.
7352                            // And we are not going to add emphemeral app, so we can return the
7353                            // result straight away.
7354                            result.add(xpDomainInfo.resolveInfo);
7355                            return applyPostResolutionFilter(result, instantAppPkgName,
7356                                    allowDynamicSplits, filterCallingUid, userId);
7357                        }
7358                    } else if (result.size() <= 1 && !addEphemeral) {
7359                        // No result in parent user and <= 1 result in current profile, and we
7360                        // are not going to add emphemeral app, so we can return the result without
7361                        // further processing.
7362                        return applyPostResolutionFilter(result, instantAppPkgName,
7363                                allowDynamicSplits, filterCallingUid, userId);
7364                    }
7365                    // We have more than one candidate (combining results from current and parent
7366                    // profile), so we need filtering and sorting.
7367                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
7368                            intent, flags, result, xpDomainInfo, userId);
7369                    sortResult = true;
7370                }
7371            } else {
7372                final PackageParser.Package pkg = mPackages.get(pkgName);
7373                result = null;
7374                if (pkg != null) {
7375                    result = filterIfNotSystemUser(
7376                            mActivities.queryIntentForPackage(
7377                                    intent, resolvedType, flags, pkg.activities, userId),
7378                            userId);
7379                }
7380                if (result == null || result.size() == 0) {
7381                    // the caller wants to resolve for a particular package; however, there
7382                    // were no installed results, so, try to find an ephemeral result
7383                    addEphemeral = !ephemeralDisabled
7384                            && isInstantAppAllowed(
7385                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
7386                    if (result == null) {
7387                        result = new ArrayList<>();
7388                    }
7389                }
7390            }
7391        }
7392        if (addEphemeral) {
7393            result = maybeAddInstantAppInstaller(
7394                    result, intent, resolvedType, flags, userId, resolveForStart);
7395        }
7396        if (sortResult) {
7397            Collections.sort(result, mResolvePrioritySorter);
7398        }
7399        return applyPostResolutionFilter(
7400                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
7401    }
7402
7403    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
7404            String resolvedType, int flags, int userId, boolean resolveForStart) {
7405        // first, check to see if we've got an instant app already installed
7406        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
7407        ResolveInfo localInstantApp = null;
7408        boolean blockResolution = false;
7409        if (!alreadyResolvedLocally) {
7410            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
7411                    flags
7412                        | PackageManager.GET_RESOLVED_FILTER
7413                        | PackageManager.MATCH_INSTANT
7414                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
7415                    userId);
7416            for (int i = instantApps.size() - 1; i >= 0; --i) {
7417                final ResolveInfo info = instantApps.get(i);
7418                final String packageName = info.activityInfo.packageName;
7419                final PackageSetting ps = mSettings.mPackages.get(packageName);
7420                if (ps.getInstantApp(userId)) {
7421                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7422                    final int status = (int)(packedStatus >> 32);
7423                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7424                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7425                        // there's a local instant application installed, but, the user has
7426                        // chosen to never use it; skip resolution and don't acknowledge
7427                        // an instant application is even available
7428                        if (DEBUG_EPHEMERAL) {
7429                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7430                        }
7431                        blockResolution = true;
7432                        break;
7433                    } else {
7434                        // we have a locally installed instant application; skip resolution
7435                        // but acknowledge there's an instant application available
7436                        if (DEBUG_EPHEMERAL) {
7437                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7438                        }
7439                        localInstantApp = info;
7440                        break;
7441                    }
7442                }
7443            }
7444        }
7445        // no app installed, let's see if one's available
7446        AuxiliaryResolveInfo auxiliaryResponse = null;
7447        if (!blockResolution) {
7448            if (localInstantApp == null) {
7449                // we don't have an instant app locally, resolve externally
7450                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7451                final InstantAppRequest requestObject = new InstantAppRequest(
7452                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
7453                        null /*callingPackage*/, userId, null /*verificationBundle*/,
7454                        resolveForStart);
7455                auxiliaryResponse =
7456                        InstantAppResolver.doInstantAppResolutionPhaseOne(
7457                                mContext, mInstantAppResolverConnection, requestObject);
7458                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7459            } else {
7460                // we have an instant application locally, but, we can't admit that since
7461                // callers shouldn't be able to determine prior browsing. create a dummy
7462                // auxiliary response so the downstream code behaves as if there's an
7463                // instant application available externally. when it comes time to start
7464                // the instant application, we'll do the right thing.
7465                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7466                auxiliaryResponse = new AuxiliaryResolveInfo(
7467                        ai.packageName, null /*splitName*/, null /*failureActivity*/,
7468                        ai.versionCode, null /*failureIntent*/);
7469            }
7470        }
7471        if (auxiliaryResponse != null) {
7472            if (DEBUG_EPHEMERAL) {
7473                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7474            }
7475            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7476            final PackageSetting ps =
7477                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7478            if (ps != null) {
7479                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7480                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7481                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
7482                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7483                // make sure this resolver is the default
7484                ephemeralInstaller.isDefault = true;
7485                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7486                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7487                // add a non-generic filter
7488                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
7489                ephemeralInstaller.filter.addDataPath(
7490                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7491                ephemeralInstaller.isInstantAppAvailable = true;
7492                result.add(ephemeralInstaller);
7493            }
7494        }
7495        return result;
7496    }
7497
7498    private static class CrossProfileDomainInfo {
7499        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7500        ResolveInfo resolveInfo;
7501        /* Best domain verification status of the activities found in the other profile */
7502        int bestDomainVerificationStatus;
7503    }
7504
7505    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7506            String resolvedType, int flags, int sourceUserId, int parentUserId) {
7507        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7508                sourceUserId)) {
7509            return null;
7510        }
7511        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7512                resolvedType, flags, parentUserId);
7513
7514        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7515            return null;
7516        }
7517        CrossProfileDomainInfo result = null;
7518        int size = resultTargetUser.size();
7519        for (int i = 0; i < size; i++) {
7520            ResolveInfo riTargetUser = resultTargetUser.get(i);
7521            // Intent filter verification is only for filters that specify a host. So don't return
7522            // those that handle all web uris.
7523            if (riTargetUser.handleAllWebDataURI) {
7524                continue;
7525            }
7526            String packageName = riTargetUser.activityInfo.packageName;
7527            PackageSetting ps = mSettings.mPackages.get(packageName);
7528            if (ps == null) {
7529                continue;
7530            }
7531            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7532            int status = (int)(verificationState >> 32);
7533            if (result == null) {
7534                result = new CrossProfileDomainInfo();
7535                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7536                        sourceUserId, parentUserId);
7537                result.bestDomainVerificationStatus = status;
7538            } else {
7539                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7540                        result.bestDomainVerificationStatus);
7541            }
7542        }
7543        // Don't consider matches with status NEVER across profiles.
7544        if (result != null && result.bestDomainVerificationStatus
7545                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7546            return null;
7547        }
7548        return result;
7549    }
7550
7551    /**
7552     * Verification statuses are ordered from the worse to the best, except for
7553     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7554     */
7555    private int bestDomainVerificationStatus(int status1, int status2) {
7556        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7557            return status2;
7558        }
7559        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7560            return status1;
7561        }
7562        return (int) MathUtils.max(status1, status2);
7563    }
7564
7565    private boolean isUserEnabled(int userId) {
7566        long callingId = Binder.clearCallingIdentity();
7567        try {
7568            UserInfo userInfo = sUserManager.getUserInfo(userId);
7569            return userInfo != null && userInfo.isEnabled();
7570        } finally {
7571            Binder.restoreCallingIdentity(callingId);
7572        }
7573    }
7574
7575    /**
7576     * Filter out activities with systemUserOnly flag set, when current user is not System.
7577     *
7578     * @return filtered list
7579     */
7580    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7581        if (userId == UserHandle.USER_SYSTEM) {
7582            return resolveInfos;
7583        }
7584        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7585            ResolveInfo info = resolveInfos.get(i);
7586            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7587                resolveInfos.remove(i);
7588            }
7589        }
7590        return resolveInfos;
7591    }
7592
7593    /**
7594     * Filters out ephemeral activities.
7595     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7596     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7597     *
7598     * @param resolveInfos The pre-filtered list of resolved activities
7599     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7600     *          is performed.
7601     * @return A filtered list of resolved activities.
7602     */
7603    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7604            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) {
7605        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7606            final ResolveInfo info = resolveInfos.get(i);
7607            // allow activities that are defined in the provided package
7608            if (allowDynamicSplits
7609                    && info.activityInfo.splitName != null
7610                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7611                            info.activityInfo.splitName)) {
7612                // requested activity is defined in a split that hasn't been installed yet.
7613                // add the installer to the resolve list
7614                if (DEBUG_INSTALL) {
7615                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
7616                }
7617                final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7618                final ComponentName installFailureActivity = findInstallFailureActivity(
7619                        info.activityInfo.packageName,  filterCallingUid, userId);
7620                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7621                        info.activityInfo.packageName, info.activityInfo.splitName,
7622                        installFailureActivity,
7623                        info.activityInfo.applicationInfo.versionCode,
7624                        null /*failureIntent*/);
7625                // make sure this resolver is the default
7626                installerInfo.isDefault = true;
7627                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7628                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7629                // add a non-generic filter
7630                installerInfo.filter = new IntentFilter();
7631                // load resources from the correct package
7632                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7633                resolveInfos.set(i, installerInfo);
7634                continue;
7635            }
7636            // caller is a full app, don't need to apply any other filtering
7637            if (ephemeralPkgName == null) {
7638                continue;
7639            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
7640                // caller is same app; don't need to apply any other filtering
7641                continue;
7642            }
7643            // allow activities that have been explicitly exposed to ephemeral apps
7644            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7645            if (!isEphemeralApp
7646                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7647                continue;
7648            }
7649            resolveInfos.remove(i);
7650        }
7651        return resolveInfos;
7652    }
7653
7654    /**
7655     * Returns the activity component that can handle install failures.
7656     * <p>By default, the instant application installer handles failures. However, an
7657     * application may want to handle failures on its own. Applications do this by
7658     * creating an activity with an intent filter that handles the action
7659     * {@link Intent#ACTION_INSTALL_FAILURE}.
7660     */
7661    private @Nullable ComponentName findInstallFailureActivity(
7662            String packageName, int filterCallingUid, int userId) {
7663        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
7664        failureActivityIntent.setPackage(packageName);
7665        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
7666        final List<ResolveInfo> result = queryIntentActivitiesInternal(
7667                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
7668                false /*resolveForStart*/, false /*allowDynamicSplits*/);
7669        final int NR = result.size();
7670        if (NR > 0) {
7671            for (int i = 0; i < NR; i++) {
7672                final ResolveInfo info = result.get(i);
7673                if (info.activityInfo.splitName != null) {
7674                    continue;
7675                }
7676                return new ComponentName(packageName, info.activityInfo.name);
7677            }
7678        }
7679        return null;
7680    }
7681
7682    /**
7683     * @param resolveInfos list of resolve infos in descending priority order
7684     * @return if the list contains a resolve info with non-negative priority
7685     */
7686    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7687        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7688    }
7689
7690    private static boolean hasWebURI(Intent intent) {
7691        if (intent.getData() == null) {
7692            return false;
7693        }
7694        final String scheme = intent.getScheme();
7695        if (TextUtils.isEmpty(scheme)) {
7696            return false;
7697        }
7698        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7699    }
7700
7701    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7702            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7703            int userId) {
7704        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7705
7706        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7707            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7708                    candidates.size());
7709        }
7710
7711        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7712        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7713        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7714        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7715        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7716        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7717
7718        synchronized (mPackages) {
7719            final int count = candidates.size();
7720            // First, try to use linked apps. Partition the candidates into four lists:
7721            // one for the final results, one for the "do not use ever", one for "undefined status"
7722            // and finally one for "browser app type".
7723            for (int n=0; n<count; n++) {
7724                ResolveInfo info = candidates.get(n);
7725                String packageName = info.activityInfo.packageName;
7726                PackageSetting ps = mSettings.mPackages.get(packageName);
7727                if (ps != null) {
7728                    // Add to the special match all list (Browser use case)
7729                    if (info.handleAllWebDataURI) {
7730                        matchAllList.add(info);
7731                        continue;
7732                    }
7733                    // Try to get the status from User settings first
7734                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7735                    int status = (int)(packedStatus >> 32);
7736                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7737                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7738                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7739                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7740                                    + " : linkgen=" + linkGeneration);
7741                        }
7742                        // Use link-enabled generation as preferredOrder, i.e.
7743                        // prefer newly-enabled over earlier-enabled.
7744                        info.preferredOrder = linkGeneration;
7745                        alwaysList.add(info);
7746                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7747                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7748                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7749                        }
7750                        neverList.add(info);
7751                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7752                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7753                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7754                        }
7755                        alwaysAskList.add(info);
7756                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7757                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7758                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7759                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7760                        }
7761                        undefinedList.add(info);
7762                    }
7763                }
7764            }
7765
7766            // We'll want to include browser possibilities in a few cases
7767            boolean includeBrowser = false;
7768
7769            // First try to add the "always" resolution(s) for the current user, if any
7770            if (alwaysList.size() > 0) {
7771                result.addAll(alwaysList);
7772            } else {
7773                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7774                result.addAll(undefinedList);
7775                // Maybe add one for the other profile.
7776                if (xpDomainInfo != null && (
7777                        xpDomainInfo.bestDomainVerificationStatus
7778                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7779                    result.add(xpDomainInfo.resolveInfo);
7780                }
7781                includeBrowser = true;
7782            }
7783
7784            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7785            // If there were 'always' entries their preferred order has been set, so we also
7786            // back that off to make the alternatives equivalent
7787            if (alwaysAskList.size() > 0) {
7788                for (ResolveInfo i : result) {
7789                    i.preferredOrder = 0;
7790                }
7791                result.addAll(alwaysAskList);
7792                includeBrowser = true;
7793            }
7794
7795            if (includeBrowser) {
7796                // Also add browsers (all of them or only the default one)
7797                if (DEBUG_DOMAIN_VERIFICATION) {
7798                    Slog.v(TAG, "   ...including browsers in candidate set");
7799                }
7800                if ((matchFlags & MATCH_ALL) != 0) {
7801                    result.addAll(matchAllList);
7802                } else {
7803                    // Browser/generic handling case.  If there's a default browser, go straight
7804                    // to that (but only if there is no other higher-priority match).
7805                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7806                    int maxMatchPrio = 0;
7807                    ResolveInfo defaultBrowserMatch = null;
7808                    final int numCandidates = matchAllList.size();
7809                    for (int n = 0; n < numCandidates; n++) {
7810                        ResolveInfo info = matchAllList.get(n);
7811                        // track the highest overall match priority...
7812                        if (info.priority > maxMatchPrio) {
7813                            maxMatchPrio = info.priority;
7814                        }
7815                        // ...and the highest-priority default browser match
7816                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7817                            if (defaultBrowserMatch == null
7818                                    || (defaultBrowserMatch.priority < info.priority)) {
7819                                if (debug) {
7820                                    Slog.v(TAG, "Considering default browser match " + info);
7821                                }
7822                                defaultBrowserMatch = info;
7823                            }
7824                        }
7825                    }
7826                    if (defaultBrowserMatch != null
7827                            && defaultBrowserMatch.priority >= maxMatchPrio
7828                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7829                    {
7830                        if (debug) {
7831                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7832                        }
7833                        result.add(defaultBrowserMatch);
7834                    } else {
7835                        result.addAll(matchAllList);
7836                    }
7837                }
7838
7839                // If there is nothing selected, add all candidates and remove the ones that the user
7840                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7841                if (result.size() == 0) {
7842                    result.addAll(candidates);
7843                    result.removeAll(neverList);
7844                }
7845            }
7846        }
7847        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7848            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7849                    result.size());
7850            for (ResolveInfo info : result) {
7851                Slog.v(TAG, "  + " + info.activityInfo);
7852            }
7853        }
7854        return result;
7855    }
7856
7857    // Returns a packed value as a long:
7858    //
7859    // high 'int'-sized word: link status: undefined/ask/never/always.
7860    // low 'int'-sized word: relative priority among 'always' results.
7861    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7862        long result = ps.getDomainVerificationStatusForUser(userId);
7863        // if none available, get the master status
7864        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7865            if (ps.getIntentFilterVerificationInfo() != null) {
7866                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7867            }
7868        }
7869        return result;
7870    }
7871
7872    private ResolveInfo querySkipCurrentProfileIntents(
7873            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7874            int flags, int sourceUserId) {
7875        if (matchingFilters != null) {
7876            int size = matchingFilters.size();
7877            for (int i = 0; i < size; i ++) {
7878                CrossProfileIntentFilter filter = matchingFilters.get(i);
7879                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7880                    // Checking if there are activities in the target user that can handle the
7881                    // intent.
7882                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7883                            resolvedType, flags, sourceUserId);
7884                    if (resolveInfo != null) {
7885                        return resolveInfo;
7886                    }
7887                }
7888            }
7889        }
7890        return null;
7891    }
7892
7893    // Return matching ResolveInfo in target user if any.
7894    private ResolveInfo queryCrossProfileIntents(
7895            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7896            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7897        if (matchingFilters != null) {
7898            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7899            // match the same intent. For performance reasons, it is better not to
7900            // run queryIntent twice for the same userId
7901            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7902            int size = matchingFilters.size();
7903            for (int i = 0; i < size; i++) {
7904                CrossProfileIntentFilter filter = matchingFilters.get(i);
7905                int targetUserId = filter.getTargetUserId();
7906                boolean skipCurrentProfile =
7907                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7908                boolean skipCurrentProfileIfNoMatchFound =
7909                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7910                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7911                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7912                    // Checking if there are activities in the target user that can handle the
7913                    // intent.
7914                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7915                            resolvedType, flags, sourceUserId);
7916                    if (resolveInfo != null) return resolveInfo;
7917                    alreadyTriedUserIds.put(targetUserId, true);
7918                }
7919            }
7920        }
7921        return null;
7922    }
7923
7924    /**
7925     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7926     * will forward the intent to the filter's target user.
7927     * Otherwise, returns null.
7928     */
7929    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7930            String resolvedType, int flags, int sourceUserId) {
7931        int targetUserId = filter.getTargetUserId();
7932        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7933                resolvedType, flags, targetUserId);
7934        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7935            // If all the matches in the target profile are suspended, return null.
7936            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7937                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7938                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7939                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7940                            targetUserId);
7941                }
7942            }
7943        }
7944        return null;
7945    }
7946
7947    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7948            int sourceUserId, int targetUserId) {
7949        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7950        long ident = Binder.clearCallingIdentity();
7951        boolean targetIsProfile;
7952        try {
7953            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7954        } finally {
7955            Binder.restoreCallingIdentity(ident);
7956        }
7957        String className;
7958        if (targetIsProfile) {
7959            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7960        } else {
7961            className = FORWARD_INTENT_TO_PARENT;
7962        }
7963        ComponentName forwardingActivityComponentName = new ComponentName(
7964                mAndroidApplication.packageName, className);
7965        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7966                sourceUserId);
7967        if (!targetIsProfile) {
7968            forwardingActivityInfo.showUserIcon = targetUserId;
7969            forwardingResolveInfo.noResourceId = true;
7970        }
7971        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7972        forwardingResolveInfo.priority = 0;
7973        forwardingResolveInfo.preferredOrder = 0;
7974        forwardingResolveInfo.match = 0;
7975        forwardingResolveInfo.isDefault = true;
7976        forwardingResolveInfo.filter = filter;
7977        forwardingResolveInfo.targetUserId = targetUserId;
7978        return forwardingResolveInfo;
7979    }
7980
7981    @Override
7982    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7983            Intent[] specifics, String[] specificTypes, Intent intent,
7984            String resolvedType, int flags, int userId) {
7985        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7986                specificTypes, intent, resolvedType, flags, userId));
7987    }
7988
7989    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7990            Intent[] specifics, String[] specificTypes, Intent intent,
7991            String resolvedType, int flags, int userId) {
7992        if (!sUserManager.exists(userId)) return Collections.emptyList();
7993        final int callingUid = Binder.getCallingUid();
7994        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7995                false /*includeInstantApps*/);
7996        enforceCrossUserPermission(callingUid, userId,
7997                false /*requireFullPermission*/, false /*checkShell*/,
7998                "query intent activity options");
7999        final String resultsAction = intent.getAction();
8000
8001        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
8002                | PackageManager.GET_RESOLVED_FILTER, userId);
8003
8004        if (DEBUG_INTENT_MATCHING) {
8005            Log.v(TAG, "Query " + intent + ": " + results);
8006        }
8007
8008        int specificsPos = 0;
8009        int N;
8010
8011        // todo: note that the algorithm used here is O(N^2).  This
8012        // isn't a problem in our current environment, but if we start running
8013        // into situations where we have more than 5 or 10 matches then this
8014        // should probably be changed to something smarter...
8015
8016        // First we go through and resolve each of the specific items
8017        // that were supplied, taking care of removing any corresponding
8018        // duplicate items in the generic resolve list.
8019        if (specifics != null) {
8020            for (int i=0; i<specifics.length; i++) {
8021                final Intent sintent = specifics[i];
8022                if (sintent == null) {
8023                    continue;
8024                }
8025
8026                if (DEBUG_INTENT_MATCHING) {
8027                    Log.v(TAG, "Specific #" + i + ": " + sintent);
8028                }
8029
8030                String action = sintent.getAction();
8031                if (resultsAction != null && resultsAction.equals(action)) {
8032                    // If this action was explicitly requested, then don't
8033                    // remove things that have it.
8034                    action = null;
8035                }
8036
8037                ResolveInfo ri = null;
8038                ActivityInfo ai = null;
8039
8040                ComponentName comp = sintent.getComponent();
8041                if (comp == null) {
8042                    ri = resolveIntent(
8043                        sintent,
8044                        specificTypes != null ? specificTypes[i] : null,
8045                            flags, userId);
8046                    if (ri == null) {
8047                        continue;
8048                    }
8049                    if (ri == mResolveInfo) {
8050                        // ACK!  Must do something better with this.
8051                    }
8052                    ai = ri.activityInfo;
8053                    comp = new ComponentName(ai.applicationInfo.packageName,
8054                            ai.name);
8055                } else {
8056                    ai = getActivityInfo(comp, flags, userId);
8057                    if (ai == null) {
8058                        continue;
8059                    }
8060                }
8061
8062                // Look for any generic query activities that are duplicates
8063                // of this specific one, and remove them from the results.
8064                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
8065                N = results.size();
8066                int j;
8067                for (j=specificsPos; j<N; j++) {
8068                    ResolveInfo sri = results.get(j);
8069                    if ((sri.activityInfo.name.equals(comp.getClassName())
8070                            && sri.activityInfo.applicationInfo.packageName.equals(
8071                                    comp.getPackageName()))
8072                        || (action != null && sri.filter.matchAction(action))) {
8073                        results.remove(j);
8074                        if (DEBUG_INTENT_MATCHING) Log.v(
8075                            TAG, "Removing duplicate item from " + j
8076                            + " due to specific " + specificsPos);
8077                        if (ri == null) {
8078                            ri = sri;
8079                        }
8080                        j--;
8081                        N--;
8082                    }
8083                }
8084
8085                // Add this specific item to its proper place.
8086                if (ri == null) {
8087                    ri = new ResolveInfo();
8088                    ri.activityInfo = ai;
8089                }
8090                results.add(specificsPos, ri);
8091                ri.specificIndex = i;
8092                specificsPos++;
8093            }
8094        }
8095
8096        // Now we go through the remaining generic results and remove any
8097        // duplicate actions that are found here.
8098        N = results.size();
8099        for (int i=specificsPos; i<N-1; i++) {
8100            final ResolveInfo rii = results.get(i);
8101            if (rii.filter == null) {
8102                continue;
8103            }
8104
8105            // Iterate over all of the actions of this result's intent
8106            // filter...  typically this should be just one.
8107            final Iterator<String> it = rii.filter.actionsIterator();
8108            if (it == null) {
8109                continue;
8110            }
8111            while (it.hasNext()) {
8112                final String action = it.next();
8113                if (resultsAction != null && resultsAction.equals(action)) {
8114                    // If this action was explicitly requested, then don't
8115                    // remove things that have it.
8116                    continue;
8117                }
8118                for (int j=i+1; j<N; j++) {
8119                    final ResolveInfo rij = results.get(j);
8120                    if (rij.filter != null && rij.filter.hasAction(action)) {
8121                        results.remove(j);
8122                        if (DEBUG_INTENT_MATCHING) Log.v(
8123                            TAG, "Removing duplicate item from " + j
8124                            + " due to action " + action + " at " + i);
8125                        j--;
8126                        N--;
8127                    }
8128                }
8129            }
8130
8131            // If the caller didn't request filter information, drop it now
8132            // so we don't have to marshall/unmarshall it.
8133            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
8134                rii.filter = null;
8135            }
8136        }
8137
8138        // Filter out the caller activity if so requested.
8139        if (caller != null) {
8140            N = results.size();
8141            for (int i=0; i<N; i++) {
8142                ActivityInfo ainfo = results.get(i).activityInfo;
8143                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
8144                        && caller.getClassName().equals(ainfo.name)) {
8145                    results.remove(i);
8146                    break;
8147                }
8148            }
8149        }
8150
8151        // If the caller didn't request filter information,
8152        // drop them now so we don't have to
8153        // marshall/unmarshall it.
8154        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
8155            N = results.size();
8156            for (int i=0; i<N; i++) {
8157                results.get(i).filter = null;
8158            }
8159        }
8160
8161        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
8162        return results;
8163    }
8164
8165    @Override
8166    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
8167            String resolvedType, int flags, int userId) {
8168        return new ParceledListSlice<>(
8169                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
8170                        false /*allowDynamicSplits*/));
8171    }
8172
8173    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
8174            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
8175        if (!sUserManager.exists(userId)) return Collections.emptyList();
8176        final int callingUid = Binder.getCallingUid();
8177        enforceCrossUserPermission(callingUid, userId,
8178                false /*requireFullPermission*/, false /*checkShell*/,
8179                "query intent receivers");
8180        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8181        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8182                false /*includeInstantApps*/);
8183        ComponentName comp = intent.getComponent();
8184        if (comp == null) {
8185            if (intent.getSelector() != null) {
8186                intent = intent.getSelector();
8187                comp = intent.getComponent();
8188            }
8189        }
8190        if (comp != null) {
8191            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8192            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
8193            if (ai != null) {
8194                // When specifying an explicit component, we prevent the activity from being
8195                // used when either 1) the calling package is normal and the activity is within
8196                // an instant application or 2) the calling package is ephemeral and the
8197                // activity is not visible to instant applications.
8198                final boolean matchInstantApp =
8199                        (flags & PackageManager.MATCH_INSTANT) != 0;
8200                final boolean matchVisibleToInstantAppOnly =
8201                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8202                final boolean matchExplicitlyVisibleOnly =
8203                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
8204                final boolean isCallerInstantApp =
8205                        instantAppPkgName != null;
8206                final boolean isTargetSameInstantApp =
8207                        comp.getPackageName().equals(instantAppPkgName);
8208                final boolean isTargetInstantApp =
8209                        (ai.applicationInfo.privateFlags
8210                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8211                final boolean isTargetVisibleToInstantApp =
8212                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
8213                final boolean isTargetExplicitlyVisibleToInstantApp =
8214                        isTargetVisibleToInstantApp
8215                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
8216                final boolean isTargetHiddenFromInstantApp =
8217                        !isTargetVisibleToInstantApp
8218                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
8219                final boolean blockResolution =
8220                        !isTargetSameInstantApp
8221                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8222                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8223                                        && isTargetHiddenFromInstantApp));
8224                if (!blockResolution) {
8225                    ResolveInfo ri = new ResolveInfo();
8226                    ri.activityInfo = ai;
8227                    list.add(ri);
8228                }
8229            }
8230            return applyPostResolutionFilter(
8231                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8232        }
8233
8234        // reader
8235        synchronized (mPackages) {
8236            String pkgName = intent.getPackage();
8237            if (pkgName == null) {
8238                final List<ResolveInfo> result =
8239                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
8240                return applyPostResolutionFilter(
8241                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8242            }
8243            final PackageParser.Package pkg = mPackages.get(pkgName);
8244            if (pkg != null) {
8245                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
8246                        intent, resolvedType, flags, pkg.receivers, userId);
8247                return applyPostResolutionFilter(
8248                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8249            }
8250            return Collections.emptyList();
8251        }
8252    }
8253
8254    @Override
8255    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
8256        final int callingUid = Binder.getCallingUid();
8257        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
8258    }
8259
8260    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
8261            int userId, int callingUid) {
8262        if (!sUserManager.exists(userId)) return null;
8263        flags = updateFlagsForResolve(
8264                flags, userId, intent, callingUid, false /*includeInstantApps*/);
8265        List<ResolveInfo> query = queryIntentServicesInternal(
8266                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
8267        if (query != null) {
8268            if (query.size() >= 1) {
8269                // If there is more than one service with the same priority,
8270                // just arbitrarily pick the first one.
8271                return query.get(0);
8272            }
8273        }
8274        return null;
8275    }
8276
8277    @Override
8278    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
8279            String resolvedType, int flags, int userId) {
8280        final int callingUid = Binder.getCallingUid();
8281        return new ParceledListSlice<>(queryIntentServicesInternal(
8282                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
8283    }
8284
8285    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
8286            String resolvedType, int flags, int userId, int callingUid,
8287            boolean includeInstantApps) {
8288        if (!sUserManager.exists(userId)) return Collections.emptyList();
8289        enforceCrossUserPermission(callingUid, userId,
8290                false /*requireFullPermission*/, false /*checkShell*/,
8291                "query intent receivers");
8292        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8293        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
8294        ComponentName comp = intent.getComponent();
8295        if (comp == null) {
8296            if (intent.getSelector() != null) {
8297                intent = intent.getSelector();
8298                comp = intent.getComponent();
8299            }
8300        }
8301        if (comp != null) {
8302            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8303            final ServiceInfo si = getServiceInfo(comp, flags, userId);
8304            if (si != null) {
8305                // When specifying an explicit component, we prevent the service from being
8306                // used when either 1) the service is in an instant application and the
8307                // caller is not the same instant application or 2) the calling package is
8308                // ephemeral and the activity is not visible to ephemeral applications.
8309                final boolean matchInstantApp =
8310                        (flags & PackageManager.MATCH_INSTANT) != 0;
8311                final boolean matchVisibleToInstantAppOnly =
8312                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8313                final boolean isCallerInstantApp =
8314                        instantAppPkgName != null;
8315                final boolean isTargetSameInstantApp =
8316                        comp.getPackageName().equals(instantAppPkgName);
8317                final boolean isTargetInstantApp =
8318                        (si.applicationInfo.privateFlags
8319                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8320                final boolean isTargetHiddenFromInstantApp =
8321                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8322                final boolean blockResolution =
8323                        !isTargetSameInstantApp
8324                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8325                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8326                                        && isTargetHiddenFromInstantApp));
8327                if (!blockResolution) {
8328                    final ResolveInfo ri = new ResolveInfo();
8329                    ri.serviceInfo = si;
8330                    list.add(ri);
8331                }
8332            }
8333            return list;
8334        }
8335
8336        // reader
8337        synchronized (mPackages) {
8338            String pkgName = intent.getPackage();
8339            if (pkgName == null) {
8340                return applyPostServiceResolutionFilter(
8341                        mServices.queryIntent(intent, resolvedType, flags, userId),
8342                        instantAppPkgName);
8343            }
8344            final PackageParser.Package pkg = mPackages.get(pkgName);
8345            if (pkg != null) {
8346                return applyPostServiceResolutionFilter(
8347                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
8348                                userId),
8349                        instantAppPkgName);
8350            }
8351            return Collections.emptyList();
8352        }
8353    }
8354
8355    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
8356            String instantAppPkgName) {
8357        if (instantAppPkgName == null) {
8358            return resolveInfos;
8359        }
8360        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8361            final ResolveInfo info = resolveInfos.get(i);
8362            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
8363            // allow services that are defined in the provided package
8364            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
8365                if (info.serviceInfo.splitName != null
8366                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
8367                                info.serviceInfo.splitName)) {
8368                    // requested service is defined in a split that hasn't been installed yet.
8369                    // add the installer to the resolve list
8370                    if (DEBUG_EPHEMERAL) {
8371                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8372                    }
8373                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8374                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8375                            info.serviceInfo.packageName, info.serviceInfo.splitName,
8376                            null /*failureActivity*/, info.serviceInfo.applicationInfo.versionCode,
8377                            null /*failureIntent*/);
8378                    // make sure this resolver is the default
8379                    installerInfo.isDefault = true;
8380                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8381                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8382                    // add a non-generic filter
8383                    installerInfo.filter = new IntentFilter();
8384                    // load resources from the correct package
8385                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8386                    resolveInfos.set(i, installerInfo);
8387                }
8388                continue;
8389            }
8390            // allow services that have been explicitly exposed to ephemeral apps
8391            if (!isEphemeralApp
8392                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8393                continue;
8394            }
8395            resolveInfos.remove(i);
8396        }
8397        return resolveInfos;
8398    }
8399
8400    @Override
8401    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
8402            String resolvedType, int flags, int userId) {
8403        return new ParceledListSlice<>(
8404                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
8405    }
8406
8407    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
8408            Intent intent, String resolvedType, int flags, int userId) {
8409        if (!sUserManager.exists(userId)) return Collections.emptyList();
8410        final int callingUid = Binder.getCallingUid();
8411        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8412        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8413                false /*includeInstantApps*/);
8414        ComponentName comp = intent.getComponent();
8415        if (comp == null) {
8416            if (intent.getSelector() != null) {
8417                intent = intent.getSelector();
8418                comp = intent.getComponent();
8419            }
8420        }
8421        if (comp != null) {
8422            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8423            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
8424            if (pi != null) {
8425                // When specifying an explicit component, we prevent the provider from being
8426                // used when either 1) the provider is in an instant application and the
8427                // caller is not the same instant application or 2) the calling package is an
8428                // instant application and the provider is not visible to instant applications.
8429                final boolean matchInstantApp =
8430                        (flags & PackageManager.MATCH_INSTANT) != 0;
8431                final boolean matchVisibleToInstantAppOnly =
8432                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8433                final boolean isCallerInstantApp =
8434                        instantAppPkgName != null;
8435                final boolean isTargetSameInstantApp =
8436                        comp.getPackageName().equals(instantAppPkgName);
8437                final boolean isTargetInstantApp =
8438                        (pi.applicationInfo.privateFlags
8439                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8440                final boolean isTargetHiddenFromInstantApp =
8441                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8442                final boolean blockResolution =
8443                        !isTargetSameInstantApp
8444                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8445                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8446                                        && isTargetHiddenFromInstantApp));
8447                if (!blockResolution) {
8448                    final ResolveInfo ri = new ResolveInfo();
8449                    ri.providerInfo = pi;
8450                    list.add(ri);
8451                }
8452            }
8453            return list;
8454        }
8455
8456        // reader
8457        synchronized (mPackages) {
8458            String pkgName = intent.getPackage();
8459            if (pkgName == null) {
8460                return applyPostContentProviderResolutionFilter(
8461                        mProviders.queryIntent(intent, resolvedType, flags, userId),
8462                        instantAppPkgName);
8463            }
8464            final PackageParser.Package pkg = mPackages.get(pkgName);
8465            if (pkg != null) {
8466                return applyPostContentProviderResolutionFilter(
8467                        mProviders.queryIntentForPackage(
8468                        intent, resolvedType, flags, pkg.providers, userId),
8469                        instantAppPkgName);
8470            }
8471            return Collections.emptyList();
8472        }
8473    }
8474
8475    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8476            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8477        if (instantAppPkgName == null) {
8478            return resolveInfos;
8479        }
8480        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8481            final ResolveInfo info = resolveInfos.get(i);
8482            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8483            // allow providers that are defined in the provided package
8484            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8485                if (info.providerInfo.splitName != null
8486                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8487                                info.providerInfo.splitName)) {
8488                    // requested provider is defined in a split that hasn't been installed yet.
8489                    // add the installer to the resolve list
8490                    if (DEBUG_EPHEMERAL) {
8491                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8492                    }
8493                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8494                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8495                            info.providerInfo.packageName, info.providerInfo.splitName,
8496                            null /*failureActivity*/, info.providerInfo.applicationInfo.versionCode,
8497                            null /*failureIntent*/);
8498                    // make sure this resolver is the default
8499                    installerInfo.isDefault = true;
8500                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8501                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8502                    // add a non-generic filter
8503                    installerInfo.filter = new IntentFilter();
8504                    // load resources from the correct package
8505                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8506                    resolveInfos.set(i, installerInfo);
8507                }
8508                continue;
8509            }
8510            // allow providers that have been explicitly exposed to instant applications
8511            if (!isEphemeralApp
8512                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8513                continue;
8514            }
8515            resolveInfos.remove(i);
8516        }
8517        return resolveInfos;
8518    }
8519
8520    @Override
8521    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8522        final int callingUid = Binder.getCallingUid();
8523        if (getInstantAppPackageName(callingUid) != null) {
8524            return ParceledListSlice.emptyList();
8525        }
8526        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8527        flags = updateFlagsForPackage(flags, userId, null);
8528        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8529        enforceCrossUserPermission(callingUid, userId,
8530                true /* requireFullPermission */, false /* checkShell */,
8531                "get installed packages");
8532
8533        // writer
8534        synchronized (mPackages) {
8535            ArrayList<PackageInfo> list;
8536            if (listUninstalled) {
8537                list = new ArrayList<>(mSettings.mPackages.size());
8538                for (PackageSetting ps : mSettings.mPackages.values()) {
8539                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8540                        continue;
8541                    }
8542                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8543                        continue;
8544                    }
8545                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8546                    if (pi != null) {
8547                        list.add(pi);
8548                    }
8549                }
8550            } else {
8551                list = new ArrayList<>(mPackages.size());
8552                for (PackageParser.Package p : mPackages.values()) {
8553                    final PackageSetting ps = (PackageSetting) p.mExtras;
8554                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8555                        continue;
8556                    }
8557                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8558                        continue;
8559                    }
8560                    final PackageInfo pi = generatePackageInfo((PackageSetting)
8561                            p.mExtras, flags, userId);
8562                    if (pi != null) {
8563                        list.add(pi);
8564                    }
8565                }
8566            }
8567
8568            return new ParceledListSlice<>(list);
8569        }
8570    }
8571
8572    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8573            String[] permissions, boolean[] tmp, int flags, int userId) {
8574        int numMatch = 0;
8575        final PermissionsState permissionsState = ps.getPermissionsState();
8576        for (int i=0; i<permissions.length; i++) {
8577            final String permission = permissions[i];
8578            if (permissionsState.hasPermission(permission, userId)) {
8579                tmp[i] = true;
8580                numMatch++;
8581            } else {
8582                tmp[i] = false;
8583            }
8584        }
8585        if (numMatch == 0) {
8586            return;
8587        }
8588        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8589
8590        // The above might return null in cases of uninstalled apps or install-state
8591        // skew across users/profiles.
8592        if (pi != null) {
8593            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8594                if (numMatch == permissions.length) {
8595                    pi.requestedPermissions = permissions;
8596                } else {
8597                    pi.requestedPermissions = new String[numMatch];
8598                    numMatch = 0;
8599                    for (int i=0; i<permissions.length; i++) {
8600                        if (tmp[i]) {
8601                            pi.requestedPermissions[numMatch] = permissions[i];
8602                            numMatch++;
8603                        }
8604                    }
8605                }
8606            }
8607            list.add(pi);
8608        }
8609    }
8610
8611    @Override
8612    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8613            String[] permissions, int flags, int userId) {
8614        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8615        flags = updateFlagsForPackage(flags, userId, permissions);
8616        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8617                true /* requireFullPermission */, false /* checkShell */,
8618                "get packages holding permissions");
8619        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8620
8621        // writer
8622        synchronized (mPackages) {
8623            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8624            boolean[] tmpBools = new boolean[permissions.length];
8625            if (listUninstalled) {
8626                for (PackageSetting ps : mSettings.mPackages.values()) {
8627                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8628                            userId);
8629                }
8630            } else {
8631                for (PackageParser.Package pkg : mPackages.values()) {
8632                    PackageSetting ps = (PackageSetting)pkg.mExtras;
8633                    if (ps != null) {
8634                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8635                                userId);
8636                    }
8637                }
8638            }
8639
8640            return new ParceledListSlice<PackageInfo>(list);
8641        }
8642    }
8643
8644    @Override
8645    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8646        final int callingUid = Binder.getCallingUid();
8647        if (getInstantAppPackageName(callingUid) != null) {
8648            return ParceledListSlice.emptyList();
8649        }
8650        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8651        flags = updateFlagsForApplication(flags, userId, null);
8652        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8653
8654        // writer
8655        synchronized (mPackages) {
8656            ArrayList<ApplicationInfo> list;
8657            if (listUninstalled) {
8658                list = new ArrayList<>(mSettings.mPackages.size());
8659                for (PackageSetting ps : mSettings.mPackages.values()) {
8660                    ApplicationInfo ai;
8661                    int effectiveFlags = flags;
8662                    if (ps.isSystem()) {
8663                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8664                    }
8665                    if (ps.pkg != null) {
8666                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8667                            continue;
8668                        }
8669                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8670                            continue;
8671                        }
8672                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8673                                ps.readUserState(userId), userId);
8674                        if (ai != null) {
8675                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8676                        }
8677                    } else {
8678                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8679                        // and already converts to externally visible package name
8680                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8681                                callingUid, effectiveFlags, userId);
8682                    }
8683                    if (ai != null) {
8684                        list.add(ai);
8685                    }
8686                }
8687            } else {
8688                list = new ArrayList<>(mPackages.size());
8689                for (PackageParser.Package p : mPackages.values()) {
8690                    if (p.mExtras != null) {
8691                        PackageSetting ps = (PackageSetting) p.mExtras;
8692                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8693                            continue;
8694                        }
8695                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8696                            continue;
8697                        }
8698                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8699                                ps.readUserState(userId), userId);
8700                        if (ai != null) {
8701                            ai.packageName = resolveExternalPackageNameLPr(p);
8702                            list.add(ai);
8703                        }
8704                    }
8705                }
8706            }
8707
8708            return new ParceledListSlice<>(list);
8709        }
8710    }
8711
8712    @Override
8713    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8714        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8715            return null;
8716        }
8717        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8718            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8719                    "getEphemeralApplications");
8720        }
8721        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8722                true /* requireFullPermission */, false /* checkShell */,
8723                "getEphemeralApplications");
8724        synchronized (mPackages) {
8725            List<InstantAppInfo> instantApps = mInstantAppRegistry
8726                    .getInstantAppsLPr(userId);
8727            if (instantApps != null) {
8728                return new ParceledListSlice<>(instantApps);
8729            }
8730        }
8731        return null;
8732    }
8733
8734    @Override
8735    public boolean isInstantApp(String packageName, int userId) {
8736        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8737                true /* requireFullPermission */, false /* checkShell */,
8738                "isInstantApp");
8739        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8740            return false;
8741        }
8742
8743        synchronized (mPackages) {
8744            int callingUid = Binder.getCallingUid();
8745            if (Process.isIsolated(callingUid)) {
8746                callingUid = mIsolatedOwners.get(callingUid);
8747            }
8748            final PackageSetting ps = mSettings.mPackages.get(packageName);
8749            PackageParser.Package pkg = mPackages.get(packageName);
8750            final boolean returnAllowed =
8751                    ps != null
8752                    && (isCallerSameApp(packageName, callingUid)
8753                            || canViewInstantApps(callingUid, userId)
8754                            || mInstantAppRegistry.isInstantAccessGranted(
8755                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8756            if (returnAllowed) {
8757                return ps.getInstantApp(userId);
8758            }
8759        }
8760        return false;
8761    }
8762
8763    @Override
8764    public byte[] getInstantAppCookie(String packageName, int userId) {
8765        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8766            return null;
8767        }
8768
8769        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8770                true /* requireFullPermission */, false /* checkShell */,
8771                "getInstantAppCookie");
8772        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8773            return null;
8774        }
8775        synchronized (mPackages) {
8776            return mInstantAppRegistry.getInstantAppCookieLPw(
8777                    packageName, userId);
8778        }
8779    }
8780
8781    @Override
8782    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8783        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8784            return true;
8785        }
8786
8787        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8788                true /* requireFullPermission */, true /* checkShell */,
8789                "setInstantAppCookie");
8790        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8791            return false;
8792        }
8793        synchronized (mPackages) {
8794            return mInstantAppRegistry.setInstantAppCookieLPw(
8795                    packageName, cookie, userId);
8796        }
8797    }
8798
8799    @Override
8800    public Bitmap getInstantAppIcon(String packageName, int userId) {
8801        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8802            return null;
8803        }
8804
8805        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8806            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8807                    "getInstantAppIcon");
8808        }
8809        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8810                true /* requireFullPermission */, false /* checkShell */,
8811                "getInstantAppIcon");
8812
8813        synchronized (mPackages) {
8814            return mInstantAppRegistry.getInstantAppIconLPw(
8815                    packageName, userId);
8816        }
8817    }
8818
8819    private boolean isCallerSameApp(String packageName, int uid) {
8820        PackageParser.Package pkg = mPackages.get(packageName);
8821        return pkg != null
8822                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8823    }
8824
8825    @Override
8826    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8827        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8828            return ParceledListSlice.emptyList();
8829        }
8830        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8831    }
8832
8833    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8834        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8835
8836        // reader
8837        synchronized (mPackages) {
8838            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8839            final int userId = UserHandle.getCallingUserId();
8840            while (i.hasNext()) {
8841                final PackageParser.Package p = i.next();
8842                if (p.applicationInfo == null) continue;
8843
8844                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8845                        && !p.applicationInfo.isDirectBootAware();
8846                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8847                        && p.applicationInfo.isDirectBootAware();
8848
8849                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8850                        && (!mSafeMode || isSystemApp(p))
8851                        && (matchesUnaware || matchesAware)) {
8852                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8853                    if (ps != null) {
8854                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8855                                ps.readUserState(userId), userId);
8856                        if (ai != null) {
8857                            finalList.add(ai);
8858                        }
8859                    }
8860                }
8861            }
8862        }
8863
8864        return finalList;
8865    }
8866
8867    @Override
8868    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8869        if (!sUserManager.exists(userId)) return null;
8870        flags = updateFlagsForComponent(flags, userId, name);
8871        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8872        // reader
8873        synchronized (mPackages) {
8874            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8875            PackageSetting ps = provider != null
8876                    ? mSettings.mPackages.get(provider.owner.packageName)
8877                    : null;
8878            if (ps != null) {
8879                final boolean isInstantApp = ps.getInstantApp(userId);
8880                // normal application; filter out instant application provider
8881                if (instantAppPkgName == null && isInstantApp) {
8882                    return null;
8883                }
8884                // instant application; filter out other instant applications
8885                if (instantAppPkgName != null
8886                        && isInstantApp
8887                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8888                    return null;
8889                }
8890                // instant application; filter out non-exposed provider
8891                if (instantAppPkgName != null
8892                        && !isInstantApp
8893                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8894                    return null;
8895                }
8896                // provider not enabled
8897                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8898                    return null;
8899                }
8900                return PackageParser.generateProviderInfo(
8901                        provider, flags, ps.readUserState(userId), userId);
8902            }
8903            return null;
8904        }
8905    }
8906
8907    /**
8908     * @deprecated
8909     */
8910    @Deprecated
8911    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8912        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8913            return;
8914        }
8915        // reader
8916        synchronized (mPackages) {
8917            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8918                    .entrySet().iterator();
8919            final int userId = UserHandle.getCallingUserId();
8920            while (i.hasNext()) {
8921                Map.Entry<String, PackageParser.Provider> entry = i.next();
8922                PackageParser.Provider p = entry.getValue();
8923                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8924
8925                if (ps != null && p.syncable
8926                        && (!mSafeMode || (p.info.applicationInfo.flags
8927                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8928                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8929                            ps.readUserState(userId), userId);
8930                    if (info != null) {
8931                        outNames.add(entry.getKey());
8932                        outInfo.add(info);
8933                    }
8934                }
8935            }
8936        }
8937    }
8938
8939    @Override
8940    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8941            int uid, int flags, String metaDataKey) {
8942        final int callingUid = Binder.getCallingUid();
8943        final int userId = processName != null ? UserHandle.getUserId(uid)
8944                : UserHandle.getCallingUserId();
8945        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8946        flags = updateFlagsForComponent(flags, userId, processName);
8947        ArrayList<ProviderInfo> finalList = null;
8948        // reader
8949        synchronized (mPackages) {
8950            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8951            while (i.hasNext()) {
8952                final PackageParser.Provider p = i.next();
8953                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8954                if (ps != null && p.info.authority != null
8955                        && (processName == null
8956                                || (p.info.processName.equals(processName)
8957                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8958                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8959
8960                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8961                    // parameter.
8962                    if (metaDataKey != null
8963                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8964                        continue;
8965                    }
8966                    final ComponentName component =
8967                            new ComponentName(p.info.packageName, p.info.name);
8968                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8969                        continue;
8970                    }
8971                    if (finalList == null) {
8972                        finalList = new ArrayList<ProviderInfo>(3);
8973                    }
8974                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8975                            ps.readUserState(userId), userId);
8976                    if (info != null) {
8977                        finalList.add(info);
8978                    }
8979                }
8980            }
8981        }
8982
8983        if (finalList != null) {
8984            Collections.sort(finalList, mProviderInitOrderSorter);
8985            return new ParceledListSlice<ProviderInfo>(finalList);
8986        }
8987
8988        return ParceledListSlice.emptyList();
8989    }
8990
8991    @Override
8992    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8993        // reader
8994        synchronized (mPackages) {
8995            final int callingUid = Binder.getCallingUid();
8996            final int callingUserId = UserHandle.getUserId(callingUid);
8997            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8998            if (ps == null) return null;
8999            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
9000                return null;
9001            }
9002            final PackageParser.Instrumentation i = mInstrumentation.get(component);
9003            return PackageParser.generateInstrumentationInfo(i, flags);
9004        }
9005    }
9006
9007    @Override
9008    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
9009            String targetPackage, int flags) {
9010        final int callingUid = Binder.getCallingUid();
9011        final int callingUserId = UserHandle.getUserId(callingUid);
9012        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
9013        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
9014            return ParceledListSlice.emptyList();
9015        }
9016        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
9017    }
9018
9019    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
9020            int flags) {
9021        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
9022
9023        // reader
9024        synchronized (mPackages) {
9025            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
9026            while (i.hasNext()) {
9027                final PackageParser.Instrumentation p = i.next();
9028                if (targetPackage == null
9029                        || targetPackage.equals(p.info.targetPackage)) {
9030                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
9031                            flags);
9032                    if (ii != null) {
9033                        finalList.add(ii);
9034                    }
9035                }
9036            }
9037        }
9038
9039        return finalList;
9040    }
9041
9042    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
9043        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
9044        try {
9045            scanDirLI(dir, parseFlags, scanFlags, currentTime);
9046        } finally {
9047            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9048        }
9049    }
9050
9051    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
9052        final File[] files = dir.listFiles();
9053        if (ArrayUtils.isEmpty(files)) {
9054            Log.d(TAG, "No files in app dir " + dir);
9055            return;
9056        }
9057
9058        if (DEBUG_PACKAGE_SCANNING) {
9059            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
9060                    + " flags=0x" + Integer.toHexString(parseFlags));
9061        }
9062        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
9063                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
9064                mParallelPackageParserCallback);
9065
9066        // Submit files for parsing in parallel
9067        int fileCount = 0;
9068        for (File file : files) {
9069            final boolean isPackage = (isApkFile(file) || file.isDirectory())
9070                    && !PackageInstallerService.isStageName(file.getName());
9071            if (!isPackage) {
9072                // Ignore entries which are not packages
9073                continue;
9074            }
9075            parallelPackageParser.submit(file, parseFlags);
9076            fileCount++;
9077        }
9078
9079        // Process results one by one
9080        for (; fileCount > 0; fileCount--) {
9081            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
9082            Throwable throwable = parseResult.throwable;
9083            int errorCode = PackageManager.INSTALL_SUCCEEDED;
9084
9085            if (throwable == null) {
9086                // Static shared libraries have synthetic package names
9087                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
9088                    renameStaticSharedLibraryPackage(parseResult.pkg);
9089                }
9090                try {
9091                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
9092                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
9093                                currentTime, null);
9094                    }
9095                } catch (PackageManagerException e) {
9096                    errorCode = e.error;
9097                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
9098                }
9099            } else if (throwable instanceof PackageParser.PackageParserException) {
9100                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
9101                        throwable;
9102                errorCode = e.error;
9103                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
9104            } else {
9105                throw new IllegalStateException("Unexpected exception occurred while parsing "
9106                        + parseResult.scanFile, throwable);
9107            }
9108
9109            // Delete invalid userdata apps
9110            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
9111                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
9112                logCriticalInfo(Log.WARN,
9113                        "Deleting invalid package at " + parseResult.scanFile);
9114                removeCodePathLI(parseResult.scanFile);
9115            }
9116        }
9117        parallelPackageParser.close();
9118    }
9119
9120    private static File getSettingsProblemFile() {
9121        File dataDir = Environment.getDataDirectory();
9122        File systemDir = new File(dataDir, "system");
9123        File fname = new File(systemDir, "uiderrors.txt");
9124        return fname;
9125    }
9126
9127    static void reportSettingsProblem(int priority, String msg) {
9128        logCriticalInfo(priority, msg);
9129    }
9130
9131    public static void logCriticalInfo(int priority, String msg) {
9132        Slog.println(priority, TAG, msg);
9133        EventLogTags.writePmCriticalInfo(msg);
9134        try {
9135            File fname = getSettingsProblemFile();
9136            FileOutputStream out = new FileOutputStream(fname, true);
9137            PrintWriter pw = new FastPrintWriter(out);
9138            SimpleDateFormat formatter = new SimpleDateFormat();
9139            String dateString = formatter.format(new Date(System.currentTimeMillis()));
9140            pw.println(dateString + ": " + msg);
9141            pw.close();
9142            FileUtils.setPermissions(
9143                    fname.toString(),
9144                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
9145                    -1, -1);
9146        } catch (java.io.IOException e) {
9147        }
9148    }
9149
9150    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
9151        if (srcFile.isDirectory()) {
9152            final File baseFile = new File(pkg.baseCodePath);
9153            long maxModifiedTime = baseFile.lastModified();
9154            if (pkg.splitCodePaths != null) {
9155                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
9156                    final File splitFile = new File(pkg.splitCodePaths[i]);
9157                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
9158                }
9159            }
9160            return maxModifiedTime;
9161        }
9162        return srcFile.lastModified();
9163    }
9164
9165    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
9166            final int policyFlags) throws PackageManagerException {
9167        // When upgrading from pre-N MR1, verify the package time stamp using the package
9168        // directory and not the APK file.
9169        final long lastModifiedTime = mIsPreNMR1Upgrade
9170                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
9171        if (ps != null
9172                && ps.codePath.equals(srcFile)
9173                && ps.timeStamp == lastModifiedTime
9174                && !isCompatSignatureUpdateNeeded(pkg)
9175                && !isRecoverSignatureUpdateNeeded(pkg)) {
9176            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
9177            KeySetManagerService ksms = mSettings.mKeySetManagerService;
9178            ArraySet<PublicKey> signingKs;
9179            synchronized (mPackages) {
9180                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
9181            }
9182            if (ps.signatures.mSignatures != null
9183                    && ps.signatures.mSignatures.length != 0
9184                    && signingKs != null) {
9185                // Optimization: reuse the existing cached certificates
9186                // if the package appears to be unchanged.
9187                pkg.mSignatures = ps.signatures.mSignatures;
9188                pkg.mSigningKeys = signingKs;
9189                return;
9190            }
9191
9192            Slog.w(TAG, "PackageSetting for " + ps.name
9193                    + " is missing signatures.  Collecting certs again to recover them.");
9194        } else {
9195            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
9196        }
9197
9198        try {
9199            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
9200            PackageParser.collectCertificates(pkg, policyFlags);
9201        } catch (PackageParserException e) {
9202            throw PackageManagerException.from(e);
9203        } finally {
9204            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9205        }
9206    }
9207
9208    /**
9209     *  Traces a package scan.
9210     *  @see #scanPackageLI(File, int, int, long, UserHandle)
9211     */
9212    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
9213            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
9214        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
9215        try {
9216            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
9217        } finally {
9218            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9219        }
9220    }
9221
9222    /**
9223     *  Scans a package and returns the newly parsed package.
9224     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
9225     */
9226    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
9227            long currentTime, UserHandle user) throws PackageManagerException {
9228        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
9229        PackageParser pp = new PackageParser();
9230        pp.setSeparateProcesses(mSeparateProcesses);
9231        pp.setOnlyCoreApps(mOnlyCore);
9232        pp.setDisplayMetrics(mMetrics);
9233        pp.setCallback(mPackageParserCallback);
9234
9235        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
9236            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
9237        }
9238
9239        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
9240        final PackageParser.Package pkg;
9241        try {
9242            pkg = pp.parsePackage(scanFile, parseFlags);
9243        } catch (PackageParserException e) {
9244            throw PackageManagerException.from(e);
9245        } finally {
9246            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9247        }
9248
9249        // Static shared libraries have synthetic package names
9250        if (pkg.applicationInfo.isStaticSharedLibrary()) {
9251            renameStaticSharedLibraryPackage(pkg);
9252        }
9253
9254        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
9255    }
9256
9257    /**
9258     *  Scans a package and returns the newly parsed package.
9259     *  @throws PackageManagerException on a parse error.
9260     */
9261    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
9262            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9263            throws PackageManagerException {
9264        // If the package has children and this is the first dive in the function
9265        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
9266        // packages (parent and children) would be successfully scanned before the
9267        // actual scan since scanning mutates internal state and we want to atomically
9268        // install the package and its children.
9269        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9270            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9271                scanFlags |= SCAN_CHECK_ONLY;
9272            }
9273        } else {
9274            scanFlags &= ~SCAN_CHECK_ONLY;
9275        }
9276
9277        // Scan the parent
9278        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
9279                scanFlags, currentTime, user);
9280
9281        // Scan the children
9282        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9283        for (int i = 0; i < childCount; i++) {
9284            PackageParser.Package childPackage = pkg.childPackages.get(i);
9285            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
9286                    currentTime, user);
9287        }
9288
9289
9290        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9291            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
9292        }
9293
9294        return scannedPkg;
9295    }
9296
9297    /**
9298     *  Scans a package and returns the newly parsed package.
9299     *  @throws PackageManagerException on a parse error.
9300     */
9301    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
9302            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9303            throws PackageManagerException {
9304        PackageSetting ps = null;
9305        PackageSetting updatedPkg;
9306        // reader
9307        synchronized (mPackages) {
9308            // Look to see if we already know about this package.
9309            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
9310            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
9311                // This package has been renamed to its original name.  Let's
9312                // use that.
9313                ps = mSettings.getPackageLPr(oldName);
9314            }
9315            // If there was no original package, see one for the real package name.
9316            if (ps == null) {
9317                ps = mSettings.getPackageLPr(pkg.packageName);
9318            }
9319            // Check to see if this package could be hiding/updating a system
9320            // package.  Must look for it either under the original or real
9321            // package name depending on our state.
9322            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
9323            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
9324
9325            // If this is a package we don't know about on the system partition, we
9326            // may need to remove disabled child packages on the system partition
9327            // or may need to not add child packages if the parent apk is updated
9328            // on the data partition and no longer defines this child package.
9329            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
9330                // If this is a parent package for an updated system app and this system
9331                // app got an OTA update which no longer defines some of the child packages
9332                // we have to prune them from the disabled system packages.
9333                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9334                if (disabledPs != null) {
9335                    final int scannedChildCount = (pkg.childPackages != null)
9336                            ? pkg.childPackages.size() : 0;
9337                    final int disabledChildCount = disabledPs.childPackageNames != null
9338                            ? disabledPs.childPackageNames.size() : 0;
9339                    for (int i = 0; i < disabledChildCount; i++) {
9340                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
9341                        boolean disabledPackageAvailable = false;
9342                        for (int j = 0; j < scannedChildCount; j++) {
9343                            PackageParser.Package childPkg = pkg.childPackages.get(j);
9344                            if (childPkg.packageName.equals(disabledChildPackageName)) {
9345                                disabledPackageAvailable = true;
9346                                break;
9347                            }
9348                         }
9349                         if (!disabledPackageAvailable) {
9350                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
9351                         }
9352                    }
9353                }
9354            }
9355        }
9356
9357        final boolean isUpdatedPkg = updatedPkg != null;
9358        final boolean isUpdatedSystemPkg = isUpdatedPkg
9359                && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0;
9360        boolean isUpdatedPkgBetter = false;
9361        // First check if this is a system package that may involve an update
9362        if (isUpdatedSystemPkg) {
9363            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
9364            // it needs to drop FLAG_PRIVILEGED.
9365            if (locationIsPrivileged(scanFile)) {
9366                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9367            } else {
9368                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9369            }
9370            // If new package is not located in "/oem" (e.g. due to an OTA),
9371            // it needs to drop FLAG_OEM.
9372            if (locationIsOem(scanFile)) {
9373                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
9374            } else {
9375                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_OEM;
9376            }
9377
9378            if (ps != null && !ps.codePath.equals(scanFile)) {
9379                // The path has changed from what was last scanned...  check the
9380                // version of the new path against what we have stored to determine
9381                // what to do.
9382                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
9383                if (pkg.mVersionCode <= ps.versionCode) {
9384                    // The system package has been updated and the code path does not match
9385                    // Ignore entry. Skip it.
9386                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
9387                            + " ignored: updated version " + ps.versionCode
9388                            + " better than this " + pkg.mVersionCode);
9389                    if (!updatedPkg.codePath.equals(scanFile)) {
9390                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
9391                                + ps.name + " changing from " + updatedPkg.codePathString
9392                                + " to " + scanFile);
9393                        updatedPkg.codePath = scanFile;
9394                        updatedPkg.codePathString = scanFile.toString();
9395                        updatedPkg.resourcePath = scanFile;
9396                        updatedPkg.resourcePathString = scanFile.toString();
9397                    }
9398                    updatedPkg.pkg = pkg;
9399                    updatedPkg.versionCode = pkg.mVersionCode;
9400
9401                    // Update the disabled system child packages to point to the package too.
9402                    final int childCount = updatedPkg.childPackageNames != null
9403                            ? updatedPkg.childPackageNames.size() : 0;
9404                    for (int i = 0; i < childCount; i++) {
9405                        String childPackageName = updatedPkg.childPackageNames.get(i);
9406                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
9407                                childPackageName);
9408                        if (updatedChildPkg != null) {
9409                            updatedChildPkg.pkg = pkg;
9410                            updatedChildPkg.versionCode = pkg.mVersionCode;
9411                        }
9412                    }
9413                } else {
9414                    // The current app on the system partition is better than
9415                    // what we have updated to on the data partition; switch
9416                    // back to the system partition version.
9417                    // At this point, its safely assumed that package installation for
9418                    // apps in system partition will go through. If not there won't be a working
9419                    // version of the app
9420                    // writer
9421                    synchronized (mPackages) {
9422                        // Just remove the loaded entries from package lists.
9423                        mPackages.remove(ps.name);
9424                    }
9425
9426                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9427                            + " reverting from " + ps.codePathString
9428                            + ": new version " + pkg.mVersionCode
9429                            + " better than installed " + ps.versionCode);
9430
9431                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9432                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9433                    synchronized (mInstallLock) {
9434                        args.cleanUpResourcesLI();
9435                    }
9436                    synchronized (mPackages) {
9437                        mSettings.enableSystemPackageLPw(ps.name);
9438                    }
9439                    isUpdatedPkgBetter = true;
9440                }
9441            }
9442        }
9443
9444        String resourcePath = null;
9445        String baseResourcePath = null;
9446        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) {
9447            if (ps != null && ps.resourcePathString != null) {
9448                resourcePath = ps.resourcePathString;
9449                baseResourcePath = ps.resourcePathString;
9450            } else {
9451                // Should not happen at all. Just log an error.
9452                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9453            }
9454        } else {
9455            resourcePath = pkg.codePath;
9456            baseResourcePath = pkg.baseCodePath;
9457        }
9458
9459        // Set application objects path explicitly.
9460        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9461        pkg.setApplicationInfoCodePath(pkg.codePath);
9462        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9463        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9464        pkg.setApplicationInfoResourcePath(resourcePath);
9465        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9466        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9467
9468        // throw an exception if we have an update to a system application, but, it's not more
9469        // recent than the package we've already scanned
9470        if (isUpdatedSystemPkg && !isUpdatedPkgBetter) {
9471            // Set CPU Abis to application info.
9472            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9473                final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, updatedPkg);
9474                derivePackageAbi(pkg, scanFile, cpuAbiOverride, false, mAppLib32InstallDir);
9475            } else {
9476                pkg.applicationInfo.primaryCpuAbi = updatedPkg.primaryCpuAbiString;
9477                pkg.applicationInfo.secondaryCpuAbi = updatedPkg.secondaryCpuAbiString;
9478            }
9479
9480            throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
9481                    + scanFile + " ignored: updated version " + ps.versionCode
9482                    + " better than this " + pkg.mVersionCode);
9483        }
9484
9485        if (isUpdatedPkg) {
9486            // An updated system app will not have the PARSE_IS_SYSTEM flag set
9487            // initially
9488            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
9489
9490            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
9491            // flag set initially
9492            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9493                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9494            }
9495
9496            // An updated OEM app will not have the PARSE_IS_OEM
9497            // flag set initially
9498            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
9499                policyFlags |= PackageParser.PARSE_IS_OEM;
9500            }
9501        }
9502
9503        // Verify certificates against what was last scanned
9504        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
9505
9506        /*
9507         * A new system app appeared, but we already had a non-system one of the
9508         * same name installed earlier.
9509         */
9510        boolean shouldHideSystemApp = false;
9511        if (!isUpdatedPkg && ps != null
9512                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
9513            /*
9514             * Check to make sure the signatures match first. If they don't,
9515             * wipe the installed application and its data.
9516             */
9517            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
9518                    != PackageManager.SIGNATURE_MATCH) {
9519                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
9520                        + " signatures don't match existing userdata copy; removing");
9521                try (PackageFreezer freezer = freezePackage(pkg.packageName,
9522                        "scanPackageInternalLI")) {
9523                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9524                }
9525                ps = null;
9526            } else {
9527                /*
9528                 * If the newly-added system app is an older version than the
9529                 * already installed version, hide it. It will be scanned later
9530                 * and re-added like an update.
9531                 */
9532                if (pkg.mVersionCode <= ps.versionCode) {
9533                    shouldHideSystemApp = true;
9534                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9535                            + " but new version " + pkg.mVersionCode + " better than installed "
9536                            + ps.versionCode + "; hiding system");
9537                } else {
9538                    /*
9539                     * The newly found system app is a newer version that the
9540                     * one previously installed. Simply remove the
9541                     * already-installed application and replace it with our own
9542                     * while keeping the application data.
9543                     */
9544                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9545                            + " reverting from " + ps.codePathString + ": new version "
9546                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
9547                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9548                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9549                    synchronized (mInstallLock) {
9550                        args.cleanUpResourcesLI();
9551                    }
9552                }
9553            }
9554        }
9555
9556        // The apk is forward locked (not public) if its code and resources
9557        // are kept in different files. (except for app in either system or
9558        // vendor path).
9559        // TODO grab this value from PackageSettings
9560        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9561            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9562                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9563            }
9564        }
9565
9566        final int userId = ((user == null) ? 0 : user.getIdentifier());
9567        if (ps != null && ps.getInstantApp(userId)) {
9568            scanFlags |= SCAN_AS_INSTANT_APP;
9569        }
9570        if (ps != null && ps.getVirtulalPreload(userId)) {
9571            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
9572        }
9573
9574        // Note that we invoke the following method only if we are about to unpack an application
9575        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9576                | SCAN_UPDATE_SIGNATURE, currentTime, user);
9577
9578        /*
9579         * If the system app should be overridden by a previously installed
9580         * data, hide the system app now and let the /data/app scan pick it up
9581         * again.
9582         */
9583        if (shouldHideSystemApp) {
9584            synchronized (mPackages) {
9585                mSettings.disableSystemPackageLPw(pkg.packageName, true);
9586            }
9587        }
9588
9589        return scannedPkg;
9590    }
9591
9592    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9593        // Derive the new package synthetic package name
9594        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9595                + pkg.staticSharedLibVersion);
9596    }
9597
9598    private static String fixProcessName(String defProcessName,
9599            String processName) {
9600        if (processName == null) {
9601            return defProcessName;
9602        }
9603        return processName;
9604    }
9605
9606    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9607            throws PackageManagerException {
9608        if (pkgSetting.signatures.mSignatures != null) {
9609            // Already existing package. Make sure signatures match
9610            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9611                    == PackageManager.SIGNATURE_MATCH;
9612            if (!match) {
9613                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9614                        == PackageManager.SIGNATURE_MATCH;
9615            }
9616            if (!match) {
9617                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9618                        == PackageManager.SIGNATURE_MATCH;
9619            }
9620            if (!match) {
9621                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9622                        + pkg.packageName + " signatures do not match the "
9623                        + "previously installed version; ignoring!");
9624            }
9625        }
9626
9627        // Check for shared user signatures
9628        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9629            // Already existing package. Make sure signatures match
9630            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9631                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9632            if (!match) {
9633                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9634                        == PackageManager.SIGNATURE_MATCH;
9635            }
9636            if (!match) {
9637                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9638                        == PackageManager.SIGNATURE_MATCH;
9639            }
9640            if (!match) {
9641                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9642                        "Package " + pkg.packageName
9643                        + " has no signatures that match those in shared user "
9644                        + pkgSetting.sharedUser.name + "; ignoring!");
9645            }
9646        }
9647    }
9648
9649    /**
9650     * Enforces that only the system UID or root's UID can call a method exposed
9651     * via Binder.
9652     *
9653     * @param message used as message if SecurityException is thrown
9654     * @throws SecurityException if the caller is not system or root
9655     */
9656    private static final void enforceSystemOrRoot(String message) {
9657        final int uid = Binder.getCallingUid();
9658        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9659            throw new SecurityException(message);
9660        }
9661    }
9662
9663    @Override
9664    public void performFstrimIfNeeded() {
9665        enforceSystemOrRoot("Only the system can request fstrim");
9666
9667        // Before everything else, see whether we need to fstrim.
9668        try {
9669            IStorageManager sm = PackageHelper.getStorageManager();
9670            if (sm != null) {
9671                boolean doTrim = false;
9672                final long interval = android.provider.Settings.Global.getLong(
9673                        mContext.getContentResolver(),
9674                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9675                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9676                if (interval > 0) {
9677                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9678                    if (timeSinceLast > interval) {
9679                        doTrim = true;
9680                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9681                                + "; running immediately");
9682                    }
9683                }
9684                if (doTrim) {
9685                    final boolean dexOptDialogShown;
9686                    synchronized (mPackages) {
9687                        dexOptDialogShown = mDexOptDialogShown;
9688                    }
9689                    if (!isFirstBoot() && dexOptDialogShown) {
9690                        try {
9691                            ActivityManager.getService().showBootMessage(
9692                                    mContext.getResources().getString(
9693                                            R.string.android_upgrading_fstrim), true);
9694                        } catch (RemoteException e) {
9695                        }
9696                    }
9697                    sm.runMaintenance();
9698                }
9699            } else {
9700                Slog.e(TAG, "storageManager service unavailable!");
9701            }
9702        } catch (RemoteException e) {
9703            // Can't happen; StorageManagerService is local
9704        }
9705    }
9706
9707    @Override
9708    public void updatePackagesIfNeeded() {
9709        enforceSystemOrRoot("Only the system can request package update");
9710
9711        // We need to re-extract after an OTA.
9712        boolean causeUpgrade = isUpgrade();
9713
9714        // First boot or factory reset.
9715        // Note: we also handle devices that are upgrading to N right now as if it is their
9716        //       first boot, as they do not have profile data.
9717        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9718
9719        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9720        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9721
9722        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9723            return;
9724        }
9725
9726        List<PackageParser.Package> pkgs;
9727        synchronized (mPackages) {
9728            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9729        }
9730
9731        final long startTime = System.nanoTime();
9732        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9733                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
9734                    false /* bootComplete */);
9735
9736        final int elapsedTimeSeconds =
9737                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9738
9739        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9740        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9741        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9742        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9743        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9744    }
9745
9746    /*
9747     * Return the prebuilt profile path given a package base code path.
9748     */
9749    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
9750        return pkg.baseCodePath + ".prof";
9751    }
9752
9753    /**
9754     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9755     * containing statistics about the invocation. The array consists of three elements,
9756     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9757     * and {@code numberOfPackagesFailed}.
9758     */
9759    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9760            final String compilerFilter, boolean bootComplete) {
9761
9762        int numberOfPackagesVisited = 0;
9763        int numberOfPackagesOptimized = 0;
9764        int numberOfPackagesSkipped = 0;
9765        int numberOfPackagesFailed = 0;
9766        final int numberOfPackagesToDexopt = pkgs.size();
9767
9768        for (PackageParser.Package pkg : pkgs) {
9769            numberOfPackagesVisited++;
9770
9771            boolean useProfileForDexopt = false;
9772
9773            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9774                // Copy over initial preopt profiles since we won't get any JIT samples for methods
9775                // that are already compiled.
9776                File profileFile = new File(getPrebuildProfilePath(pkg));
9777                // Copy profile if it exists.
9778                if (profileFile.exists()) {
9779                    try {
9780                        // We could also do this lazily before calling dexopt in
9781                        // PackageDexOptimizer to prevent this happening on first boot. The issue
9782                        // is that we don't have a good way to say "do this only once".
9783                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9784                                pkg.applicationInfo.uid, pkg.packageName)) {
9785                            Log.e(TAG, "Installer failed to copy system profile!");
9786                        } else {
9787                            // Disabled as this causes speed-profile compilation during first boot
9788                            // even if things are already compiled.
9789                            // useProfileForDexopt = true;
9790                        }
9791                    } catch (Exception e) {
9792                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9793                                e);
9794                    }
9795                } else {
9796                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9797                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
9798                    // minimize the number off apps being speed-profile compiled during first boot.
9799                    // The other paths will not change the filter.
9800                    if (disabledPs != null && disabledPs.pkg.isStub) {
9801                        // The package is the stub one, remove the stub suffix to get the normal
9802                        // package and APK names.
9803                        String systemProfilePath =
9804                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
9805                        File systemProfile = new File(systemProfilePath);
9806                        // Use the profile for compilation if there exists one for the same package
9807                        // in the system partition.
9808                        useProfileForDexopt = systemProfile.exists();
9809                    }
9810                }
9811            }
9812
9813            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9814                if (DEBUG_DEXOPT) {
9815                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9816                }
9817                numberOfPackagesSkipped++;
9818                continue;
9819            }
9820
9821            if (DEBUG_DEXOPT) {
9822                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9823                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9824            }
9825
9826            if (showDialog) {
9827                try {
9828                    ActivityManager.getService().showBootMessage(
9829                            mContext.getResources().getString(R.string.android_upgrading_apk,
9830                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9831                } catch (RemoteException e) {
9832                }
9833                synchronized (mPackages) {
9834                    mDexOptDialogShown = true;
9835                }
9836            }
9837
9838            String pkgCompilerFilter = compilerFilter;
9839            if (useProfileForDexopt) {
9840                // Use background dexopt mode to try and use the profile. Note that this does not
9841                // guarantee usage of the profile.
9842                pkgCompilerFilter =
9843                        PackageManagerServiceCompilerMapping.getCompilerFilterForReason(
9844                                PackageManagerService.REASON_BACKGROUND_DEXOPT);
9845            }
9846
9847            // checkProfiles is false to avoid merging profiles during boot which
9848            // might interfere with background compilation (b/28612421).
9849            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9850            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9851            // trade-off worth doing to save boot time work.
9852            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9853            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9854                    pkg.packageName,
9855                    pkgCompilerFilter,
9856                    dexoptFlags));
9857
9858            switch (primaryDexOptStaus) {
9859                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9860                    numberOfPackagesOptimized++;
9861                    break;
9862                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9863                    numberOfPackagesSkipped++;
9864                    break;
9865                case PackageDexOptimizer.DEX_OPT_FAILED:
9866                    numberOfPackagesFailed++;
9867                    break;
9868                default:
9869                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9870                    break;
9871            }
9872        }
9873
9874        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9875                numberOfPackagesFailed };
9876    }
9877
9878    @Override
9879    public void notifyPackageUse(String packageName, int reason) {
9880        synchronized (mPackages) {
9881            final int callingUid = Binder.getCallingUid();
9882            final int callingUserId = UserHandle.getUserId(callingUid);
9883            if (getInstantAppPackageName(callingUid) != null) {
9884                if (!isCallerSameApp(packageName, callingUid)) {
9885                    return;
9886                }
9887            } else {
9888                if (isInstantApp(packageName, callingUserId)) {
9889                    return;
9890                }
9891            }
9892            notifyPackageUseLocked(packageName, reason);
9893        }
9894    }
9895
9896    private void notifyPackageUseLocked(String packageName, int reason) {
9897        final PackageParser.Package p = mPackages.get(packageName);
9898        if (p == null) {
9899            return;
9900        }
9901        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9902    }
9903
9904    @Override
9905    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9906            List<String> classPaths, String loaderIsa) {
9907        int userId = UserHandle.getCallingUserId();
9908        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9909        if (ai == null) {
9910            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9911                + loadingPackageName + ", user=" + userId);
9912            return;
9913        }
9914        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9915    }
9916
9917    @Override
9918    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9919            IDexModuleRegisterCallback callback) {
9920        int userId = UserHandle.getCallingUserId();
9921        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9922        DexManager.RegisterDexModuleResult result;
9923        if (ai == null) {
9924            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9925                     " calling user. package=" + packageName + ", user=" + userId);
9926            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9927        } else {
9928            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9929        }
9930
9931        if (callback != null) {
9932            mHandler.post(() -> {
9933                try {
9934                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9935                } catch (RemoteException e) {
9936                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9937                }
9938            });
9939        }
9940    }
9941
9942    /**
9943     * Ask the package manager to perform a dex-opt with the given compiler filter.
9944     *
9945     * Note: exposed only for the shell command to allow moving packages explicitly to a
9946     *       definite state.
9947     */
9948    @Override
9949    public boolean performDexOptMode(String packageName,
9950            boolean checkProfiles, String targetCompilerFilter, boolean force,
9951            boolean bootComplete, String splitName) {
9952        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9953                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9954                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9955        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
9956                splitName, flags));
9957    }
9958
9959    /**
9960     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9961     * secondary dex files belonging to the given package.
9962     *
9963     * Note: exposed only for the shell command to allow moving packages explicitly to a
9964     *       definite state.
9965     */
9966    @Override
9967    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9968            boolean force) {
9969        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9970                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9971                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9972                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9973        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9974    }
9975
9976    /*package*/ boolean performDexOpt(DexoptOptions options) {
9977        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9978            return false;
9979        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9980            return false;
9981        }
9982
9983        if (options.isDexoptOnlySecondaryDex()) {
9984            return mDexManager.dexoptSecondaryDex(options);
9985        } else {
9986            int dexoptStatus = performDexOptWithStatus(options);
9987            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9988        }
9989    }
9990
9991    /**
9992     * Perform dexopt on the given package and return one of following result:
9993     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9994     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9995     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9996     */
9997    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9998        return performDexOptTraced(options);
9999    }
10000
10001    private int performDexOptTraced(DexoptOptions options) {
10002        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
10003        try {
10004            return performDexOptInternal(options);
10005        } finally {
10006            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10007        }
10008    }
10009
10010    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
10011    // if the package can now be considered up to date for the given filter.
10012    private int performDexOptInternal(DexoptOptions options) {
10013        PackageParser.Package p;
10014        synchronized (mPackages) {
10015            p = mPackages.get(options.getPackageName());
10016            if (p == null) {
10017                // Package could not be found. Report failure.
10018                return PackageDexOptimizer.DEX_OPT_FAILED;
10019            }
10020            mPackageUsage.maybeWriteAsync(mPackages);
10021            mCompilerStats.maybeWriteAsync();
10022        }
10023        long callingId = Binder.clearCallingIdentity();
10024        try {
10025            synchronized (mInstallLock) {
10026                return performDexOptInternalWithDependenciesLI(p, options);
10027            }
10028        } finally {
10029            Binder.restoreCallingIdentity(callingId);
10030        }
10031    }
10032
10033    public ArraySet<String> getOptimizablePackages() {
10034        ArraySet<String> pkgs = new ArraySet<String>();
10035        synchronized (mPackages) {
10036            for (PackageParser.Package p : mPackages.values()) {
10037                if (PackageDexOptimizer.canOptimizePackage(p)) {
10038                    pkgs.add(p.packageName);
10039                }
10040            }
10041        }
10042        return pkgs;
10043    }
10044
10045    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
10046            DexoptOptions options) {
10047        // Select the dex optimizer based on the force parameter.
10048        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
10049        //       allocate an object here.
10050        PackageDexOptimizer pdo = options.isForce()
10051                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
10052                : mPackageDexOptimizer;
10053
10054        // Dexopt all dependencies first. Note: we ignore the return value and march on
10055        // on errors.
10056        // Note that we are going to call performDexOpt on those libraries as many times as
10057        // they are referenced in packages. When we do a batch of performDexOpt (for example
10058        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
10059        // and the first package that uses the library will dexopt it. The
10060        // others will see that the compiled code for the library is up to date.
10061        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
10062        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
10063        if (!deps.isEmpty()) {
10064            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
10065                    options.getCompilerFilter(), options.getSplitName(),
10066                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
10067            for (PackageParser.Package depPackage : deps) {
10068                // TODO: Analyze and investigate if we (should) profile libraries.
10069                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
10070                        getOrCreateCompilerPackageStats(depPackage),
10071                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
10072            }
10073        }
10074        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
10075                getOrCreateCompilerPackageStats(p),
10076                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
10077    }
10078
10079    /**
10080     * Reconcile the information we have about the secondary dex files belonging to
10081     * {@code packagName} and the actual dex files. For all dex files that were
10082     * deleted, update the internal records and delete the generated oat files.
10083     */
10084    @Override
10085    public void reconcileSecondaryDexFiles(String packageName) {
10086        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
10087            return;
10088        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
10089            return;
10090        }
10091        mDexManager.reconcileSecondaryDexFiles(packageName);
10092    }
10093
10094    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
10095    // a reference there.
10096    /*package*/ DexManager getDexManager() {
10097        return mDexManager;
10098    }
10099
10100    /**
10101     * Execute the background dexopt job immediately.
10102     */
10103    @Override
10104    public boolean runBackgroundDexoptJob() {
10105        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
10106            return false;
10107        }
10108        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
10109    }
10110
10111    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
10112        if (p.usesLibraries != null || p.usesOptionalLibraries != null
10113                || p.usesStaticLibraries != null) {
10114            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
10115            Set<String> collectedNames = new HashSet<>();
10116            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
10117
10118            retValue.remove(p);
10119
10120            return retValue;
10121        } else {
10122            return Collections.emptyList();
10123        }
10124    }
10125
10126    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
10127            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
10128        if (!collectedNames.contains(p.packageName)) {
10129            collectedNames.add(p.packageName);
10130            collected.add(p);
10131
10132            if (p.usesLibraries != null) {
10133                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
10134                        null, collected, collectedNames);
10135            }
10136            if (p.usesOptionalLibraries != null) {
10137                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
10138                        null, collected, collectedNames);
10139            }
10140            if (p.usesStaticLibraries != null) {
10141                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
10142                        p.usesStaticLibrariesVersions, collected, collectedNames);
10143            }
10144        }
10145    }
10146
10147    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
10148            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
10149        final int libNameCount = libs.size();
10150        for (int i = 0; i < libNameCount; i++) {
10151            String libName = libs.get(i);
10152            int version = (versions != null && versions.length == libNameCount)
10153                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
10154            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
10155            if (libPkg != null) {
10156                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
10157            }
10158        }
10159    }
10160
10161    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
10162        synchronized (mPackages) {
10163            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
10164            if (libEntry != null) {
10165                return mPackages.get(libEntry.apk);
10166            }
10167            return null;
10168        }
10169    }
10170
10171    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
10172        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10173        if (versionedLib == null) {
10174            return null;
10175        }
10176        return versionedLib.get(version);
10177    }
10178
10179    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
10180        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10181                pkg.staticSharedLibName);
10182        if (versionedLib == null) {
10183            return null;
10184        }
10185        int previousLibVersion = -1;
10186        final int versionCount = versionedLib.size();
10187        for (int i = 0; i < versionCount; i++) {
10188            final int libVersion = versionedLib.keyAt(i);
10189            if (libVersion < pkg.staticSharedLibVersion) {
10190                previousLibVersion = Math.max(previousLibVersion, libVersion);
10191            }
10192        }
10193        if (previousLibVersion >= 0) {
10194            return versionedLib.get(previousLibVersion);
10195        }
10196        return null;
10197    }
10198
10199    public void shutdown() {
10200        mPackageUsage.writeNow(mPackages);
10201        mCompilerStats.writeNow();
10202        mDexManager.writePackageDexUsageNow();
10203    }
10204
10205    @Override
10206    public void dumpProfiles(String packageName) {
10207        PackageParser.Package pkg;
10208        synchronized (mPackages) {
10209            pkg = mPackages.get(packageName);
10210            if (pkg == null) {
10211                throw new IllegalArgumentException("Unknown package: " + packageName);
10212            }
10213        }
10214        /* Only the shell, root, or the app user should be able to dump profiles. */
10215        int callingUid = Binder.getCallingUid();
10216        if (callingUid != Process.SHELL_UID &&
10217            callingUid != Process.ROOT_UID &&
10218            callingUid != pkg.applicationInfo.uid) {
10219            throw new SecurityException("dumpProfiles");
10220        }
10221
10222        synchronized (mInstallLock) {
10223            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
10224            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
10225            try {
10226                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
10227                String codePaths = TextUtils.join(";", allCodePaths);
10228                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
10229            } catch (InstallerException e) {
10230                Slog.w(TAG, "Failed to dump profiles", e);
10231            }
10232            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10233        }
10234    }
10235
10236    @Override
10237    public void forceDexOpt(String packageName) {
10238        enforceSystemOrRoot("forceDexOpt");
10239
10240        PackageParser.Package pkg;
10241        synchronized (mPackages) {
10242            pkg = mPackages.get(packageName);
10243            if (pkg == null) {
10244                throw new IllegalArgumentException("Unknown package: " + packageName);
10245            }
10246        }
10247
10248        synchronized (mInstallLock) {
10249            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
10250
10251            // Whoever is calling forceDexOpt wants a compiled package.
10252            // Don't use profiles since that may cause compilation to be skipped.
10253            final int res = performDexOptInternalWithDependenciesLI(
10254                    pkg,
10255                    new DexoptOptions(packageName,
10256                            getDefaultCompilerFilter(),
10257                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
10258
10259            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10260            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
10261                throw new IllegalStateException("Failed to dexopt: " + res);
10262            }
10263        }
10264    }
10265
10266    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
10267        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
10268            Slog.w(TAG, "Unable to update from " + oldPkg.name
10269                    + " to " + newPkg.packageName
10270                    + ": old package not in system partition");
10271            return false;
10272        } else if (mPackages.get(oldPkg.name) != null) {
10273            Slog.w(TAG, "Unable to update from " + oldPkg.name
10274                    + " to " + newPkg.packageName
10275                    + ": old package still exists");
10276            return false;
10277        }
10278        return true;
10279    }
10280
10281    void removeCodePathLI(File codePath) {
10282        if (codePath.isDirectory()) {
10283            try {
10284                mInstaller.rmPackageDir(codePath.getAbsolutePath());
10285            } catch (InstallerException e) {
10286                Slog.w(TAG, "Failed to remove code path", e);
10287            }
10288        } else {
10289            codePath.delete();
10290        }
10291    }
10292
10293    private int[] resolveUserIds(int userId) {
10294        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
10295    }
10296
10297    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10298        if (pkg == null) {
10299            Slog.wtf(TAG, "Package was null!", new Throwable());
10300            return;
10301        }
10302        clearAppDataLeafLIF(pkg, userId, flags);
10303        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10304        for (int i = 0; i < childCount; i++) {
10305            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10306        }
10307    }
10308
10309    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10310        final PackageSetting ps;
10311        synchronized (mPackages) {
10312            ps = mSettings.mPackages.get(pkg.packageName);
10313        }
10314        for (int realUserId : resolveUserIds(userId)) {
10315            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10316            try {
10317                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10318                        ceDataInode);
10319            } catch (InstallerException e) {
10320                Slog.w(TAG, String.valueOf(e));
10321            }
10322        }
10323    }
10324
10325    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10326        if (pkg == null) {
10327            Slog.wtf(TAG, "Package was null!", new Throwable());
10328            return;
10329        }
10330        destroyAppDataLeafLIF(pkg, userId, flags);
10331        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10332        for (int i = 0; i < childCount; i++) {
10333            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10334        }
10335    }
10336
10337    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10338        final PackageSetting ps;
10339        synchronized (mPackages) {
10340            ps = mSettings.mPackages.get(pkg.packageName);
10341        }
10342        for (int realUserId : resolveUserIds(userId)) {
10343            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10344            try {
10345                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10346                        ceDataInode);
10347            } catch (InstallerException e) {
10348                Slog.w(TAG, String.valueOf(e));
10349            }
10350            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
10351        }
10352    }
10353
10354    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
10355        if (pkg == null) {
10356            Slog.wtf(TAG, "Package was null!", new Throwable());
10357            return;
10358        }
10359        destroyAppProfilesLeafLIF(pkg);
10360        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10361        for (int i = 0; i < childCount; i++) {
10362            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
10363        }
10364    }
10365
10366    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
10367        try {
10368            mInstaller.destroyAppProfiles(pkg.packageName);
10369        } catch (InstallerException e) {
10370            Slog.w(TAG, String.valueOf(e));
10371        }
10372    }
10373
10374    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
10375        if (pkg == null) {
10376            Slog.wtf(TAG, "Package was null!", new Throwable());
10377            return;
10378        }
10379        clearAppProfilesLeafLIF(pkg);
10380        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10381        for (int i = 0; i < childCount; i++) {
10382            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
10383        }
10384    }
10385
10386    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
10387        try {
10388            mInstaller.clearAppProfiles(pkg.packageName);
10389        } catch (InstallerException e) {
10390            Slog.w(TAG, String.valueOf(e));
10391        }
10392    }
10393
10394    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
10395            long lastUpdateTime) {
10396        // Set parent install/update time
10397        PackageSetting ps = (PackageSetting) pkg.mExtras;
10398        if (ps != null) {
10399            ps.firstInstallTime = firstInstallTime;
10400            ps.lastUpdateTime = lastUpdateTime;
10401        }
10402        // Set children install/update time
10403        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10404        for (int i = 0; i < childCount; i++) {
10405            PackageParser.Package childPkg = pkg.childPackages.get(i);
10406            ps = (PackageSetting) childPkg.mExtras;
10407            if (ps != null) {
10408                ps.firstInstallTime = firstInstallTime;
10409                ps.lastUpdateTime = lastUpdateTime;
10410            }
10411        }
10412    }
10413
10414    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
10415            PackageParser.Package changingLib) {
10416        if (file.path != null) {
10417            usesLibraryFiles.add(file.path);
10418            return;
10419        }
10420        PackageParser.Package p = mPackages.get(file.apk);
10421        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
10422            // If we are doing this while in the middle of updating a library apk,
10423            // then we need to make sure to use that new apk for determining the
10424            // dependencies here.  (We haven't yet finished committing the new apk
10425            // to the package manager state.)
10426            if (p == null || p.packageName.equals(changingLib.packageName)) {
10427                p = changingLib;
10428            }
10429        }
10430        if (p != null) {
10431            usesLibraryFiles.addAll(p.getAllCodePaths());
10432            if (p.usesLibraryFiles != null) {
10433                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
10434            }
10435        }
10436    }
10437
10438    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
10439            PackageParser.Package changingLib) throws PackageManagerException {
10440        if (pkg == null) {
10441            return;
10442        }
10443        ArraySet<String> usesLibraryFiles = null;
10444        if (pkg.usesLibraries != null) {
10445            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
10446                    null, null, pkg.packageName, changingLib, true,
10447                    pkg.applicationInfo.targetSdkVersion, null);
10448        }
10449        if (pkg.usesStaticLibraries != null) {
10450            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
10451                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
10452                    pkg.packageName, changingLib, true,
10453                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
10454        }
10455        if (pkg.usesOptionalLibraries != null) {
10456            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
10457                    null, null, pkg.packageName, changingLib, false,
10458                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
10459        }
10460        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
10461            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
10462        } else {
10463            pkg.usesLibraryFiles = null;
10464        }
10465    }
10466
10467    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
10468            @Nullable int[] requiredVersions, @Nullable String[][] requiredCertDigests,
10469            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
10470            boolean required, int targetSdk, @Nullable ArraySet<String> outUsedLibraries)
10471            throws PackageManagerException {
10472        final int libCount = requestedLibraries.size();
10473        for (int i = 0; i < libCount; i++) {
10474            final String libName = requestedLibraries.get(i);
10475            final int libVersion = requiredVersions != null ? requiredVersions[i]
10476                    : SharedLibraryInfo.VERSION_UNDEFINED;
10477            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
10478            if (libEntry == null) {
10479                if (required) {
10480                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10481                            "Package " + packageName + " requires unavailable shared library "
10482                                    + libName + "; failing!");
10483                } else if (DEBUG_SHARED_LIBRARIES) {
10484                    Slog.i(TAG, "Package " + packageName
10485                            + " desires unavailable shared library "
10486                            + libName + "; ignoring!");
10487                }
10488            } else {
10489                if (requiredVersions != null && requiredCertDigests != null) {
10490                    if (libEntry.info.getVersion() != requiredVersions[i]) {
10491                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10492                            "Package " + packageName + " requires unavailable static shared"
10493                                    + " library " + libName + " version "
10494                                    + libEntry.info.getVersion() + "; failing!");
10495                    }
10496
10497                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
10498                    if (libPkg == null) {
10499                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10500                                "Package " + packageName + " requires unavailable static shared"
10501                                        + " library; failing!");
10502                    }
10503
10504                    final String[] expectedCertDigests = requiredCertDigests[i];
10505                    // For apps targeting O MR1 we require explicit enumeration of all certs.
10506                    final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
10507                            ? PackageUtils.computeSignaturesSha256Digests(libPkg.mSignatures)
10508                            : PackageUtils.computeSignaturesSha256Digests(
10509                                    new Signature[]{libPkg.mSignatures[0]});
10510
10511                    // Take a shortcut if sizes don't match. Note that if an app doesn't
10512                    // target O we don't parse the "additional-certificate" tags similarly
10513                    // how we only consider all certs only for apps targeting O (see above).
10514                    // Therefore, the size check is safe to make.
10515                    if (expectedCertDigests.length != libCertDigests.length) {
10516                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10517                                "Package " + packageName + " requires differently signed" +
10518                                        " static sDexLoadReporter.java:45.19hared library; failing!");
10519                    }
10520
10521                    // Use a predictable order as signature order may vary
10522                    Arrays.sort(libCertDigests);
10523                    Arrays.sort(expectedCertDigests);
10524
10525                    final int certCount = libCertDigests.length;
10526                    for (int j = 0; j < certCount; j++) {
10527                        if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
10528                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10529                                    "Package " + packageName + " requires differently signed" +
10530                                            " static shared library; failing!");
10531                        }
10532                    }
10533                }
10534
10535                if (outUsedLibraries == null) {
10536                    outUsedLibraries = new ArraySet<>();
10537                }
10538                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
10539            }
10540        }
10541        return outUsedLibraries;
10542    }
10543
10544    private static boolean hasString(List<String> list, List<String> which) {
10545        if (list == null) {
10546            return false;
10547        }
10548        for (int i=list.size()-1; i>=0; i--) {
10549            for (int j=which.size()-1; j>=0; j--) {
10550                if (which.get(j).equals(list.get(i))) {
10551                    return true;
10552                }
10553            }
10554        }
10555        return false;
10556    }
10557
10558    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
10559            PackageParser.Package changingPkg) {
10560        ArrayList<PackageParser.Package> res = null;
10561        for (PackageParser.Package pkg : mPackages.values()) {
10562            if (changingPkg != null
10563                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
10564                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
10565                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
10566                            changingPkg.staticSharedLibName)) {
10567                return null;
10568            }
10569            if (res == null) {
10570                res = new ArrayList<>();
10571            }
10572            res.add(pkg);
10573            try {
10574                updateSharedLibrariesLPr(pkg, changingPkg);
10575            } catch (PackageManagerException e) {
10576                // If a system app update or an app and a required lib missing we
10577                // delete the package and for updated system apps keep the data as
10578                // it is better for the user to reinstall than to be in an limbo
10579                // state. Also libs disappearing under an app should never happen
10580                // - just in case.
10581                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
10582                    final int flags = pkg.isUpdatedSystemApp()
10583                            ? PackageManager.DELETE_KEEP_DATA : 0;
10584                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
10585                            flags , null, true, null);
10586                }
10587                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
10588            }
10589        }
10590        return res;
10591    }
10592
10593    /**
10594     * Derive the value of the {@code cpuAbiOverride} based on the provided
10595     * value and an optional stored value from the package settings.
10596     */
10597    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
10598        String cpuAbiOverride = null;
10599
10600        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10601            cpuAbiOverride = null;
10602        } else if (abiOverride != null) {
10603            cpuAbiOverride = abiOverride;
10604        } else if (settings != null) {
10605            cpuAbiOverride = settings.cpuAbiOverrideString;
10606        }
10607
10608        return cpuAbiOverride;
10609    }
10610
10611    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10612            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10613                    throws PackageManagerException {
10614        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10615        // If the package has children and this is the first dive in the function
10616        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10617        // whether all packages (parent and children) would be successfully scanned
10618        // before the actual scan since scanning mutates internal state and we want
10619        // to atomically install the package and its children.
10620        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10621            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10622                scanFlags |= SCAN_CHECK_ONLY;
10623            }
10624        } else {
10625            scanFlags &= ~SCAN_CHECK_ONLY;
10626        }
10627
10628        final PackageParser.Package scannedPkg;
10629        try {
10630            // Scan the parent
10631            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10632            // Scan the children
10633            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10634            for (int i = 0; i < childCount; i++) {
10635                PackageParser.Package childPkg = pkg.childPackages.get(i);
10636                scanPackageLI(childPkg, policyFlags,
10637                        scanFlags, currentTime, user);
10638            }
10639        } finally {
10640            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10641        }
10642
10643        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10644            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10645        }
10646
10647        return scannedPkg;
10648    }
10649
10650    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10651            int scanFlags, long currentTime, @Nullable UserHandle user)
10652                    throws PackageManagerException {
10653        boolean success = false;
10654        try {
10655            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10656                    currentTime, user);
10657            success = true;
10658            return res;
10659        } finally {
10660            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10661                // DELETE_DATA_ON_FAILURES is only used by frozen paths
10662                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10663                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10664                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10665            }
10666        }
10667    }
10668
10669    /**
10670     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10671     */
10672    private static boolean apkHasCode(String fileName) {
10673        StrictJarFile jarFile = null;
10674        try {
10675            jarFile = new StrictJarFile(fileName,
10676                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10677            return jarFile.findEntry("classes.dex") != null;
10678        } catch (IOException ignore) {
10679        } finally {
10680            try {
10681                if (jarFile != null) {
10682                    jarFile.close();
10683                }
10684            } catch (IOException ignore) {}
10685        }
10686        return false;
10687    }
10688
10689    /**
10690     * Enforces code policy for the package. This ensures that if an APK has
10691     * declared hasCode="true" in its manifest that the APK actually contains
10692     * code.
10693     *
10694     * @throws PackageManagerException If bytecode could not be found when it should exist
10695     */
10696    private static void assertCodePolicy(PackageParser.Package pkg)
10697            throws PackageManagerException {
10698        final boolean shouldHaveCode =
10699                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10700        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10701            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10702                    "Package " + pkg.baseCodePath + " code is missing");
10703        }
10704
10705        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10706            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10707                final boolean splitShouldHaveCode =
10708                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10709                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10710                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10711                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10712                }
10713            }
10714        }
10715    }
10716
10717    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10718            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10719                    throws PackageManagerException {
10720        if (DEBUG_PACKAGE_SCANNING) {
10721            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10722                Log.d(TAG, "Scanning package " + pkg.packageName);
10723        }
10724
10725        applyPolicy(pkg, policyFlags);
10726
10727        assertPackageIsValid(pkg, policyFlags, scanFlags);
10728
10729        if (Build.IS_DEBUGGABLE &&
10730                pkg.isPrivilegedApp() &&
10731                !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) {
10732            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10733        }
10734
10735        // Initialize package source and resource directories
10736        final File scanFile = new File(pkg.codePath);
10737        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10738        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10739
10740        SharedUserSetting suid = null;
10741        PackageSetting pkgSetting = null;
10742
10743        // Getting the package setting may have a side-effect, so if we
10744        // are only checking if scan would succeed, stash a copy of the
10745        // old setting to restore at the end.
10746        PackageSetting nonMutatedPs = null;
10747
10748        // We keep references to the derived CPU Abis from settings in oder to reuse
10749        // them in the case where we're not upgrading or booting for the first time.
10750        String primaryCpuAbiFromSettings = null;
10751        String secondaryCpuAbiFromSettings = null;
10752
10753        // writer
10754        synchronized (mPackages) {
10755            if (pkg.mSharedUserId != null) {
10756                // SIDE EFFECTS; may potentially allocate a new shared user
10757                suid = mSettings.getSharedUserLPw(
10758                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10759                if (DEBUG_PACKAGE_SCANNING) {
10760                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10761                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10762                                + "): packages=" + suid.packages);
10763                }
10764            }
10765
10766            // Check if we are renaming from an original package name.
10767            PackageSetting origPackage = null;
10768            String realName = null;
10769            if (pkg.mOriginalPackages != null) {
10770                // This package may need to be renamed to a previously
10771                // installed name.  Let's check on that...
10772                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10773                if (pkg.mOriginalPackages.contains(renamed)) {
10774                    // This package had originally been installed as the
10775                    // original name, and we have already taken care of
10776                    // transitioning to the new one.  Just update the new
10777                    // one to continue using the old name.
10778                    realName = pkg.mRealPackage;
10779                    if (!pkg.packageName.equals(renamed)) {
10780                        // Callers into this function may have already taken
10781                        // care of renaming the package; only do it here if
10782                        // it is not already done.
10783                        pkg.setPackageName(renamed);
10784                    }
10785                } else {
10786                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10787                        if ((origPackage = mSettings.getPackageLPr(
10788                                pkg.mOriginalPackages.get(i))) != null) {
10789                            // We do have the package already installed under its
10790                            // original name...  should we use it?
10791                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10792                                // New package is not compatible with original.
10793                                origPackage = null;
10794                                continue;
10795                            } else if (origPackage.sharedUser != null) {
10796                                // Make sure uid is compatible between packages.
10797                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10798                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10799                                            + " to " + pkg.packageName + ": old uid "
10800                                            + origPackage.sharedUser.name
10801                                            + " differs from " + pkg.mSharedUserId);
10802                                    origPackage = null;
10803                                    continue;
10804                                }
10805                                // TODO: Add case when shared user id is added [b/28144775]
10806                            } else {
10807                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10808                                        + pkg.packageName + " to old name " + origPackage.name);
10809                            }
10810                            break;
10811                        }
10812                    }
10813                }
10814            }
10815
10816            if (mTransferedPackages.contains(pkg.packageName)) {
10817                Slog.w(TAG, "Package " + pkg.packageName
10818                        + " was transferred to another, but its .apk remains");
10819            }
10820
10821            // See comments in nonMutatedPs declaration
10822            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10823                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10824                if (foundPs != null) {
10825                    nonMutatedPs = new PackageSetting(foundPs);
10826                }
10827            }
10828
10829            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10830                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10831                if (foundPs != null) {
10832                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10833                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10834                }
10835            }
10836
10837            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10838            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10839                PackageManagerService.reportSettingsProblem(Log.WARN,
10840                        "Package " + pkg.packageName + " shared user changed from "
10841                                + (pkgSetting.sharedUser != null
10842                                        ? pkgSetting.sharedUser.name : "<nothing>")
10843                                + " to "
10844                                + (suid != null ? suid.name : "<nothing>")
10845                                + "; replacing with new");
10846                pkgSetting = null;
10847            }
10848            final PackageSetting oldPkgSetting =
10849                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10850            final PackageSetting disabledPkgSetting =
10851                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10852
10853            String[] usesStaticLibraries = null;
10854            if (pkg.usesStaticLibraries != null) {
10855                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10856                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10857            }
10858
10859            if (pkgSetting == null) {
10860                final String parentPackageName = (pkg.parentPackage != null)
10861                        ? pkg.parentPackage.packageName : null;
10862                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10863                final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10864                // REMOVE SharedUserSetting from method; update in a separate call
10865                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10866                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10867                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10868                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10869                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10870                        true /*allowInstall*/, instantApp, virtualPreload,
10871                        parentPackageName, pkg.getChildPackageNames(),
10872                        UserManagerService.getInstance(), usesStaticLibraries,
10873                        pkg.usesStaticLibrariesVersions);
10874                // SIDE EFFECTS; updates system state; move elsewhere
10875                if (origPackage != null) {
10876                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10877                }
10878                mSettings.addUserToSettingLPw(pkgSetting);
10879            } else {
10880                // REMOVE SharedUserSetting from method; update in a separate call.
10881                //
10882                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10883                // secondaryCpuAbi are not known at this point so we always update them
10884                // to null here, only to reset them at a later point.
10885                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10886                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10887                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10888                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10889                        UserManagerService.getInstance(), usesStaticLibraries,
10890                        pkg.usesStaticLibrariesVersions);
10891            }
10892            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10893            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10894
10895            // SIDE EFFECTS; modifies system state; move elsewhere
10896            if (pkgSetting.origPackage != null) {
10897                // If we are first transitioning from an original package,
10898                // fix up the new package's name now.  We need to do this after
10899                // looking up the package under its new name, so getPackageLP
10900                // can take care of fiddling things correctly.
10901                pkg.setPackageName(origPackage.name);
10902
10903                // File a report about this.
10904                String msg = "New package " + pkgSetting.realName
10905                        + " renamed to replace old package " + pkgSetting.name;
10906                reportSettingsProblem(Log.WARN, msg);
10907
10908                // Make a note of it.
10909                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10910                    mTransferedPackages.add(origPackage.name);
10911                }
10912
10913                // No longer need to retain this.
10914                pkgSetting.origPackage = null;
10915            }
10916
10917            // SIDE EFFECTS; modifies system state; move elsewhere
10918            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10919                // Make a note of it.
10920                mTransferedPackages.add(pkg.packageName);
10921            }
10922
10923            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10924                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10925            }
10926
10927            if ((scanFlags & SCAN_BOOTING) == 0
10928                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10929                // Check all shared libraries and map to their actual file path.
10930                // We only do this here for apps not on a system dir, because those
10931                // are the only ones that can fail an install due to this.  We
10932                // will take care of the system apps by updating all of their
10933                // library paths after the scan is done. Also during the initial
10934                // scan don't update any libs as we do this wholesale after all
10935                // apps are scanned to avoid dependency based scanning.
10936                updateSharedLibrariesLPr(pkg, null);
10937            }
10938
10939            if (mFoundPolicyFile) {
10940                SELinuxMMAC.assignSeInfoValue(pkg);
10941            }
10942            pkg.applicationInfo.uid = pkgSetting.appId;
10943            pkg.mExtras = pkgSetting;
10944
10945
10946            // Static shared libs have same package with different versions where
10947            // we internally use a synthetic package name to allow multiple versions
10948            // of the same package, therefore we need to compare signatures against
10949            // the package setting for the latest library version.
10950            PackageSetting signatureCheckPs = pkgSetting;
10951            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10952                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10953                if (libraryEntry != null) {
10954                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10955                }
10956            }
10957
10958            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10959                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10960                    // We just determined the app is signed correctly, so bring
10961                    // over the latest parsed certs.
10962                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10963                } else {
10964                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10965                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10966                                "Package " + pkg.packageName + " upgrade keys do not match the "
10967                                + "previously installed version");
10968                    } else {
10969                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10970                        String msg = "System package " + pkg.packageName
10971                                + " signature changed; retaining data.";
10972                        reportSettingsProblem(Log.WARN, msg);
10973                    }
10974                }
10975            } else {
10976                try {
10977                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10978                    verifySignaturesLP(signatureCheckPs, pkg);
10979                    // We just determined the app is signed correctly, so bring
10980                    // over the latest parsed certs.
10981                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10982                } catch (PackageManagerException e) {
10983                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10984                        throw e;
10985                    }
10986                    // The signature has changed, but this package is in the system
10987                    // image...  let's recover!
10988                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10989                    // However...  if this package is part of a shared user, but it
10990                    // doesn't match the signature of the shared user, let's fail.
10991                    // What this means is that you can't change the signatures
10992                    // associated with an overall shared user, which doesn't seem all
10993                    // that unreasonable.
10994                    if (signatureCheckPs.sharedUser != null) {
10995                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10996                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10997                            throw new PackageManagerException(
10998                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10999                                    "Signature mismatch for shared user: "
11000                                            + pkgSetting.sharedUser);
11001                        }
11002                    }
11003                    // File a report about this.
11004                    String msg = "System package " + pkg.packageName
11005                            + " signature changed; retaining data.";
11006                    reportSettingsProblem(Log.WARN, msg);
11007                }
11008            }
11009
11010            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
11011                // This package wants to adopt ownership of permissions from
11012                // another package.
11013                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
11014                    final String origName = pkg.mAdoptPermissions.get(i);
11015                    final PackageSetting orig = mSettings.getPackageLPr(origName);
11016                    if (orig != null) {
11017                        if (verifyPackageUpdateLPr(orig, pkg)) {
11018                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
11019                                    + pkg.packageName);
11020                            // SIDE EFFECTS; updates permissions system state; move elsewhere
11021                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
11022                        }
11023                    }
11024                }
11025            }
11026        }
11027
11028        pkg.applicationInfo.processName = fixProcessName(
11029                pkg.applicationInfo.packageName,
11030                pkg.applicationInfo.processName);
11031
11032        if (pkg != mPlatformPackage) {
11033            // Get all of our default paths setup
11034            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
11035        }
11036
11037        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
11038
11039        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
11040            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
11041                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
11042                final boolean extractNativeLibs = !pkg.isLibrary();
11043                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
11044                        mAppLib32InstallDir);
11045                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11046
11047                // Some system apps still use directory structure for native libraries
11048                // in which case we might end up not detecting abi solely based on apk
11049                // structure. Try to detect abi based on directory structure.
11050                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
11051                        pkg.applicationInfo.primaryCpuAbi == null) {
11052                    setBundledAppAbisAndRoots(pkg, pkgSetting);
11053                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
11054                }
11055            } else {
11056                // This is not a first boot or an upgrade, don't bother deriving the
11057                // ABI during the scan. Instead, trust the value that was stored in the
11058                // package setting.
11059                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
11060                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
11061
11062                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
11063
11064                if (DEBUG_ABI_SELECTION) {
11065                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
11066                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
11067                        pkg.applicationInfo.secondaryCpuAbi);
11068                }
11069            }
11070        } else {
11071            if ((scanFlags & SCAN_MOVE) != 0) {
11072                // We haven't run dex-opt for this move (since we've moved the compiled output too)
11073                // but we already have this packages package info in the PackageSetting. We just
11074                // use that and derive the native library path based on the new codepath.
11075                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
11076                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
11077            }
11078
11079            // Set native library paths again. For moves, the path will be updated based on the
11080            // ABIs we've determined above. For non-moves, the path will be updated based on the
11081            // ABIs we determined during compilation, but the path will depend on the final
11082            // package path (after the rename away from the stage path).
11083            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
11084        }
11085
11086        // This is a special case for the "system" package, where the ABI is
11087        // dictated by the zygote configuration (and init.rc). We should keep track
11088        // of this ABI so that we can deal with "normal" applications that run under
11089        // the same UID correctly.
11090        if (mPlatformPackage == pkg) {
11091            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
11092                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
11093        }
11094
11095        // If there's a mismatch between the abi-override in the package setting
11096        // and the abiOverride specified for the install. Warn about this because we
11097        // would've already compiled the app without taking the package setting into
11098        // account.
11099        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
11100            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
11101                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
11102                        " for package " + pkg.packageName);
11103            }
11104        }
11105
11106        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11107        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11108        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
11109
11110        // Copy the derived override back to the parsed package, so that we can
11111        // update the package settings accordingly.
11112        pkg.cpuAbiOverride = cpuAbiOverride;
11113
11114        if (DEBUG_ABI_SELECTION) {
11115            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
11116                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
11117                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
11118        }
11119
11120        // Push the derived path down into PackageSettings so we know what to
11121        // clean up at uninstall time.
11122        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
11123
11124        if (DEBUG_ABI_SELECTION) {
11125            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
11126                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
11127                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
11128        }
11129
11130        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
11131        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
11132            // We don't do this here during boot because we can do it all
11133            // at once after scanning all existing packages.
11134            //
11135            // We also do this *before* we perform dexopt on this package, so that
11136            // we can avoid redundant dexopts, and also to make sure we've got the
11137            // code and package path correct.
11138            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
11139        }
11140
11141        if (mFactoryTest && pkg.requestedPermissions.contains(
11142                android.Manifest.permission.FACTORY_TEST)) {
11143            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
11144        }
11145
11146        if (isSystemApp(pkg)) {
11147            pkgSetting.isOrphaned = true;
11148        }
11149
11150        // Take care of first install / last update times.
11151        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
11152        if (currentTime != 0) {
11153            if (pkgSetting.firstInstallTime == 0) {
11154                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
11155            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
11156                pkgSetting.lastUpdateTime = currentTime;
11157            }
11158        } else if (pkgSetting.firstInstallTime == 0) {
11159            // We need *something*.  Take time time stamp of the file.
11160            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
11161        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
11162            if (scanFileTime != pkgSetting.timeStamp) {
11163                // A package on the system image has changed; consider this
11164                // to be an update.
11165                pkgSetting.lastUpdateTime = scanFileTime;
11166            }
11167        }
11168        pkgSetting.setTimeStamp(scanFileTime);
11169
11170        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
11171            if (nonMutatedPs != null) {
11172                synchronized (mPackages) {
11173                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
11174                }
11175            }
11176        } else {
11177            final int userId = user == null ? 0 : user.getIdentifier();
11178            // Modify state for the given package setting
11179            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
11180                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
11181            if (pkgSetting.getInstantApp(userId)) {
11182                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
11183            }
11184        }
11185        return pkg;
11186    }
11187
11188    /**
11189     * Applies policy to the parsed package based upon the given policy flags.
11190     * Ensures the package is in a good state.
11191     * <p>
11192     * Implementation detail: This method must NOT have any side effect. It would
11193     * ideally be static, but, it requires locks to read system state.
11194     */
11195    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
11196        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
11197            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
11198            if (pkg.applicationInfo.isDirectBootAware()) {
11199                // we're direct boot aware; set for all components
11200                for (PackageParser.Service s : pkg.services) {
11201                    s.info.encryptionAware = s.info.directBootAware = true;
11202                }
11203                for (PackageParser.Provider p : pkg.providers) {
11204                    p.info.encryptionAware = p.info.directBootAware = true;
11205                }
11206                for (PackageParser.Activity a : pkg.activities) {
11207                    a.info.encryptionAware = a.info.directBootAware = true;
11208                }
11209                for (PackageParser.Activity r : pkg.receivers) {
11210                    r.info.encryptionAware = r.info.directBootAware = true;
11211                }
11212            }
11213            if (compressedFileExists(pkg.codePath)) {
11214                pkg.isStub = true;
11215            }
11216        } else {
11217            // Only allow system apps to be flagged as core apps.
11218            pkg.coreApp = false;
11219            // clear flags not applicable to regular apps
11220            pkg.applicationInfo.privateFlags &=
11221                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
11222            pkg.applicationInfo.privateFlags &=
11223                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
11224        }
11225        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
11226
11227        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
11228            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
11229        }
11230
11231        if ((policyFlags&PackageParser.PARSE_IS_OEM) != 0) {
11232            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
11233        }
11234
11235        if (!isSystemApp(pkg)) {
11236            // Only system apps can use these features.
11237            pkg.mOriginalPackages = null;
11238            pkg.mRealPackage = null;
11239            pkg.mAdoptPermissions = null;
11240        }
11241    }
11242
11243    /**
11244     * Asserts the parsed package is valid according to the given policy. If the
11245     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
11246     * <p>
11247     * Implementation detail: This method must NOT have any side effects. It would
11248     * ideally be static, but, it requires locks to read system state.
11249     *
11250     * @throws PackageManagerException If the package fails any of the validation checks
11251     */
11252    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
11253            throws PackageManagerException {
11254        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
11255            assertCodePolicy(pkg);
11256        }
11257
11258        if (pkg.applicationInfo.getCodePath() == null ||
11259                pkg.applicationInfo.getResourcePath() == null) {
11260            // Bail out. The resource and code paths haven't been set.
11261            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
11262                    "Code and resource paths haven't been set correctly");
11263        }
11264
11265        // Make sure we're not adding any bogus keyset info
11266        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11267        ksms.assertScannedPackageValid(pkg);
11268
11269        synchronized (mPackages) {
11270            // The special "android" package can only be defined once
11271            if (pkg.packageName.equals("android")) {
11272                if (mAndroidApplication != null) {
11273                    Slog.w(TAG, "*************************************************");
11274                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
11275                    Slog.w(TAG, " codePath=" + pkg.codePath);
11276                    Slog.w(TAG, "*************************************************");
11277                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11278                            "Core android package being redefined.  Skipping.");
11279                }
11280            }
11281
11282            // A package name must be unique; don't allow duplicates
11283            if (mPackages.containsKey(pkg.packageName)) {
11284                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11285                        "Application package " + pkg.packageName
11286                        + " already installed.  Skipping duplicate.");
11287            }
11288
11289            if (pkg.applicationInfo.isStaticSharedLibrary()) {
11290                // Static libs have a synthetic package name containing the version
11291                // but we still want the base name to be unique.
11292                if (mPackages.containsKey(pkg.manifestPackageName)) {
11293                    throw new PackageManagerException(
11294                            "Duplicate static shared lib provider package");
11295                }
11296
11297                // Static shared libraries should have at least O target SDK
11298                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
11299                    throw new PackageManagerException(
11300                            "Packages declaring static-shared libs must target O SDK or higher");
11301                }
11302
11303                // Package declaring static a shared lib cannot be instant apps
11304                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11305                    throw new PackageManagerException(
11306                            "Packages declaring static-shared libs cannot be instant apps");
11307                }
11308
11309                // Package declaring static a shared lib cannot be renamed since the package
11310                // name is synthetic and apps can't code around package manager internals.
11311                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
11312                    throw new PackageManagerException(
11313                            "Packages declaring static-shared libs cannot be renamed");
11314                }
11315
11316                // Package declaring static a shared lib cannot declare child packages
11317                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
11318                    throw new PackageManagerException(
11319                            "Packages declaring static-shared libs cannot have child packages");
11320                }
11321
11322                // Package declaring static a shared lib cannot declare dynamic libs
11323                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
11324                    throw new PackageManagerException(
11325                            "Packages declaring static-shared libs cannot declare dynamic libs");
11326                }
11327
11328                // Package declaring static a shared lib cannot declare shared users
11329                if (pkg.mSharedUserId != null) {
11330                    throw new PackageManagerException(
11331                            "Packages declaring static-shared libs cannot declare shared users");
11332                }
11333
11334                // Static shared libs cannot declare activities
11335                if (!pkg.activities.isEmpty()) {
11336                    throw new PackageManagerException(
11337                            "Static shared libs cannot declare activities");
11338                }
11339
11340                // Static shared libs cannot declare services
11341                if (!pkg.services.isEmpty()) {
11342                    throw new PackageManagerException(
11343                            "Static shared libs cannot declare services");
11344                }
11345
11346                // Static shared libs cannot declare providers
11347                if (!pkg.providers.isEmpty()) {
11348                    throw new PackageManagerException(
11349                            "Static shared libs cannot declare content providers");
11350                }
11351
11352                // Static shared libs cannot declare receivers
11353                if (!pkg.receivers.isEmpty()) {
11354                    throw new PackageManagerException(
11355                            "Static shared libs cannot declare broadcast receivers");
11356                }
11357
11358                // Static shared libs cannot declare permission groups
11359                if (!pkg.permissionGroups.isEmpty()) {
11360                    throw new PackageManagerException(
11361                            "Static shared libs cannot declare permission groups");
11362                }
11363
11364                // Static shared libs cannot declare permissions
11365                if (!pkg.permissions.isEmpty()) {
11366                    throw new PackageManagerException(
11367                            "Static shared libs cannot declare permissions");
11368                }
11369
11370                // Static shared libs cannot declare protected broadcasts
11371                if (pkg.protectedBroadcasts != null) {
11372                    throw new PackageManagerException(
11373                            "Static shared libs cannot declare protected broadcasts");
11374                }
11375
11376                // Static shared libs cannot be overlay targets
11377                if (pkg.mOverlayTarget != null) {
11378                    throw new PackageManagerException(
11379                            "Static shared libs cannot be overlay targets");
11380                }
11381
11382                // The version codes must be ordered as lib versions
11383                int minVersionCode = Integer.MIN_VALUE;
11384                int maxVersionCode = Integer.MAX_VALUE;
11385
11386                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
11387                        pkg.staticSharedLibName);
11388                if (versionedLib != null) {
11389                    final int versionCount = versionedLib.size();
11390                    for (int i = 0; i < versionCount; i++) {
11391                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
11392                        final int libVersionCode = libInfo.getDeclaringPackage()
11393                                .getVersionCode();
11394                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
11395                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
11396                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
11397                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
11398                        } else {
11399                            minVersionCode = maxVersionCode = libVersionCode;
11400                            break;
11401                        }
11402                    }
11403                }
11404                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
11405                    throw new PackageManagerException("Static shared"
11406                            + " lib version codes must be ordered as lib versions");
11407                }
11408            }
11409
11410            // Only privileged apps and updated privileged apps can add child packages.
11411            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
11412                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
11413                    throw new PackageManagerException("Only privileged apps can add child "
11414                            + "packages. Ignoring package " + pkg.packageName);
11415                }
11416                final int childCount = pkg.childPackages.size();
11417                for (int i = 0; i < childCount; i++) {
11418                    PackageParser.Package childPkg = pkg.childPackages.get(i);
11419                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
11420                            childPkg.packageName)) {
11421                        throw new PackageManagerException("Can't override child of "
11422                                + "another disabled app. Ignoring package " + pkg.packageName);
11423                    }
11424                }
11425            }
11426
11427            // If we're only installing presumed-existing packages, require that the
11428            // scanned APK is both already known and at the path previously established
11429            // for it.  Previously unknown packages we pick up normally, but if we have an
11430            // a priori expectation about this package's install presence, enforce it.
11431            // With a singular exception for new system packages. When an OTA contains
11432            // a new system package, we allow the codepath to change from a system location
11433            // to the user-installed location. If we don't allow this change, any newer,
11434            // user-installed version of the application will be ignored.
11435            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
11436                if (mExpectingBetter.containsKey(pkg.packageName)) {
11437                    logCriticalInfo(Log.WARN,
11438                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
11439                } else {
11440                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
11441                    if (known != null) {
11442                        if (DEBUG_PACKAGE_SCANNING) {
11443                            Log.d(TAG, "Examining " + pkg.codePath
11444                                    + " and requiring known paths " + known.codePathString
11445                                    + " & " + known.resourcePathString);
11446                        }
11447                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
11448                                || !pkg.applicationInfo.getResourcePath().equals(
11449                                        known.resourcePathString)) {
11450                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
11451                                    "Application package " + pkg.packageName
11452                                    + " found at " + pkg.applicationInfo.getCodePath()
11453                                    + " but expected at " + known.codePathString
11454                                    + "; ignoring.");
11455                        }
11456                    } else {
11457                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11458                                "Application package " + pkg.packageName
11459                                + " not found; ignoring.");
11460                    }
11461                }
11462            }
11463
11464            // Verify that this new package doesn't have any content providers
11465            // that conflict with existing packages.  Only do this if the
11466            // package isn't already installed, since we don't want to break
11467            // things that are installed.
11468            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
11469                final int N = pkg.providers.size();
11470                int i;
11471                for (i=0; i<N; i++) {
11472                    PackageParser.Provider p = pkg.providers.get(i);
11473                    if (p.info.authority != null) {
11474                        String names[] = p.info.authority.split(";");
11475                        for (int j = 0; j < names.length; j++) {
11476                            if (mProvidersByAuthority.containsKey(names[j])) {
11477                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11478                                final String otherPackageName =
11479                                        ((other != null && other.getComponentName() != null) ?
11480                                                other.getComponentName().getPackageName() : "?");
11481                                throw new PackageManagerException(
11482                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11483                                        "Can't install because provider name " + names[j]
11484                                                + " (in package " + pkg.applicationInfo.packageName
11485                                                + ") is already used by " + otherPackageName);
11486                            }
11487                        }
11488                    }
11489                }
11490            }
11491        }
11492    }
11493
11494    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
11495            int type, String declaringPackageName, int declaringVersionCode) {
11496        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11497        if (versionedLib == null) {
11498            versionedLib = new SparseArray<>();
11499            mSharedLibraries.put(name, versionedLib);
11500            if (type == SharedLibraryInfo.TYPE_STATIC) {
11501                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11502            }
11503        } else if (versionedLib.indexOfKey(version) >= 0) {
11504            return false;
11505        }
11506        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11507                version, type, declaringPackageName, declaringVersionCode);
11508        versionedLib.put(version, libEntry);
11509        return true;
11510    }
11511
11512    private boolean removeSharedLibraryLPw(String name, int version) {
11513        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11514        if (versionedLib == null) {
11515            return false;
11516        }
11517        final int libIdx = versionedLib.indexOfKey(version);
11518        if (libIdx < 0) {
11519            return false;
11520        }
11521        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11522        versionedLib.remove(version);
11523        if (versionedLib.size() <= 0) {
11524            mSharedLibraries.remove(name);
11525            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11526                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11527                        .getPackageName());
11528            }
11529        }
11530        return true;
11531    }
11532
11533    /**
11534     * Adds a scanned package to the system. When this method is finished, the package will
11535     * be available for query, resolution, etc...
11536     */
11537    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11538            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
11539        final String pkgName = pkg.packageName;
11540        if (mCustomResolverComponentName != null &&
11541                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11542            setUpCustomResolverActivity(pkg);
11543        }
11544
11545        if (pkg.packageName.equals("android")) {
11546            synchronized (mPackages) {
11547                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11548                    // Set up information for our fall-back user intent resolution activity.
11549                    mPlatformPackage = pkg;
11550                    pkg.mVersionCode = mSdkVersion;
11551                    mAndroidApplication = pkg.applicationInfo;
11552                    if (!mResolverReplaced) {
11553                        mResolveActivity.applicationInfo = mAndroidApplication;
11554                        mResolveActivity.name = ResolverActivity.class.getName();
11555                        mResolveActivity.packageName = mAndroidApplication.packageName;
11556                        mResolveActivity.processName = "system:ui";
11557                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11558                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11559                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11560                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11561                        mResolveActivity.exported = true;
11562                        mResolveActivity.enabled = true;
11563                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11564                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11565                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11566                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11567                                | ActivityInfo.CONFIG_ORIENTATION
11568                                | ActivityInfo.CONFIG_KEYBOARD
11569                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11570                        mResolveInfo.activityInfo = mResolveActivity;
11571                        mResolveInfo.priority = 0;
11572                        mResolveInfo.preferredOrder = 0;
11573                        mResolveInfo.match = 0;
11574                        mResolveComponentName = new ComponentName(
11575                                mAndroidApplication.packageName, mResolveActivity.name);
11576                    }
11577                }
11578            }
11579        }
11580
11581        ArrayList<PackageParser.Package> clientLibPkgs = null;
11582        // writer
11583        synchronized (mPackages) {
11584            boolean hasStaticSharedLibs = false;
11585
11586            // Any app can add new static shared libraries
11587            if (pkg.staticSharedLibName != null) {
11588                // Static shared libs don't allow renaming as they have synthetic package
11589                // names to allow install of multiple versions, so use name from manifest.
11590                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11591                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11592                        pkg.manifestPackageName, pkg.mVersionCode)) {
11593                    hasStaticSharedLibs = true;
11594                } else {
11595                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11596                                + pkg.staticSharedLibName + " already exists; skipping");
11597                }
11598                // Static shared libs cannot be updated once installed since they
11599                // use synthetic package name which includes the version code, so
11600                // not need to update other packages's shared lib dependencies.
11601            }
11602
11603            if (!hasStaticSharedLibs
11604                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11605                // Only system apps can add new dynamic shared libraries.
11606                if (pkg.libraryNames != null) {
11607                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11608                        String name = pkg.libraryNames.get(i);
11609                        boolean allowed = false;
11610                        if (pkg.isUpdatedSystemApp()) {
11611                            // New library entries can only be added through the
11612                            // system image.  This is important to get rid of a lot
11613                            // of nasty edge cases: for example if we allowed a non-
11614                            // system update of the app to add a library, then uninstalling
11615                            // the update would make the library go away, and assumptions
11616                            // we made such as through app install filtering would now
11617                            // have allowed apps on the device which aren't compatible
11618                            // with it.  Better to just have the restriction here, be
11619                            // conservative, and create many fewer cases that can negatively
11620                            // impact the user experience.
11621                            final PackageSetting sysPs = mSettings
11622                                    .getDisabledSystemPkgLPr(pkg.packageName);
11623                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11624                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11625                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11626                                        allowed = true;
11627                                        break;
11628                                    }
11629                                }
11630                            }
11631                        } else {
11632                            allowed = true;
11633                        }
11634                        if (allowed) {
11635                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11636                                    SharedLibraryInfo.VERSION_UNDEFINED,
11637                                    SharedLibraryInfo.TYPE_DYNAMIC,
11638                                    pkg.packageName, pkg.mVersionCode)) {
11639                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11640                                        + name + " already exists; skipping");
11641                            }
11642                        } else {
11643                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11644                                    + name + " that is not declared on system image; skipping");
11645                        }
11646                    }
11647
11648                    if ((scanFlags & SCAN_BOOTING) == 0) {
11649                        // If we are not booting, we need to update any applications
11650                        // that are clients of our shared library.  If we are booting,
11651                        // this will all be done once the scan is complete.
11652                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11653                    }
11654                }
11655            }
11656        }
11657
11658        if ((scanFlags & SCAN_BOOTING) != 0) {
11659            // No apps can run during boot scan, so they don't need to be frozen
11660        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11661            // Caller asked to not kill app, so it's probably not frozen
11662        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11663            // Caller asked us to ignore frozen check for some reason; they
11664            // probably didn't know the package name
11665        } else {
11666            // We're doing major surgery on this package, so it better be frozen
11667            // right now to keep it from launching
11668            checkPackageFrozen(pkgName);
11669        }
11670
11671        // Also need to kill any apps that are dependent on the library.
11672        if (clientLibPkgs != null) {
11673            for (int i=0; i<clientLibPkgs.size(); i++) {
11674                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11675                killApplication(clientPkg.applicationInfo.packageName,
11676                        clientPkg.applicationInfo.uid, "update lib");
11677            }
11678        }
11679
11680        // writer
11681        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11682
11683        synchronized (mPackages) {
11684            // We don't expect installation to fail beyond this point
11685
11686            // Add the new setting to mSettings
11687            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11688            // Add the new setting to mPackages
11689            mPackages.put(pkg.applicationInfo.packageName, pkg);
11690            // Make sure we don't accidentally delete its data.
11691            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11692            while (iter.hasNext()) {
11693                PackageCleanItem item = iter.next();
11694                if (pkgName.equals(item.packageName)) {
11695                    iter.remove();
11696                }
11697            }
11698
11699            // Add the package's KeySets to the global KeySetManagerService
11700            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11701            ksms.addScannedPackageLPw(pkg);
11702
11703            int N = pkg.providers.size();
11704            StringBuilder r = null;
11705            int i;
11706            for (i=0; i<N; i++) {
11707                PackageParser.Provider p = pkg.providers.get(i);
11708                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11709                        p.info.processName);
11710                mProviders.addProvider(p);
11711                p.syncable = p.info.isSyncable;
11712                if (p.info.authority != null) {
11713                    String names[] = p.info.authority.split(";");
11714                    p.info.authority = null;
11715                    for (int j = 0; j < names.length; j++) {
11716                        if (j == 1 && p.syncable) {
11717                            // We only want the first authority for a provider to possibly be
11718                            // syncable, so if we already added this provider using a different
11719                            // authority clear the syncable flag. We copy the provider before
11720                            // changing it because the mProviders object contains a reference
11721                            // to a provider that we don't want to change.
11722                            // Only do this for the second authority since the resulting provider
11723                            // object can be the same for all future authorities for this provider.
11724                            p = new PackageParser.Provider(p);
11725                            p.syncable = false;
11726                        }
11727                        if (!mProvidersByAuthority.containsKey(names[j])) {
11728                            mProvidersByAuthority.put(names[j], p);
11729                            if (p.info.authority == null) {
11730                                p.info.authority = names[j];
11731                            } else {
11732                                p.info.authority = p.info.authority + ";" + names[j];
11733                            }
11734                            if (DEBUG_PACKAGE_SCANNING) {
11735                                if (chatty)
11736                                    Log.d(TAG, "Registered content provider: " + names[j]
11737                                            + ", className = " + p.info.name + ", isSyncable = "
11738                                            + p.info.isSyncable);
11739                            }
11740                        } else {
11741                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11742                            Slog.w(TAG, "Skipping provider name " + names[j] +
11743                                    " (in package " + pkg.applicationInfo.packageName +
11744                                    "): name already used by "
11745                                    + ((other != null && other.getComponentName() != null)
11746                                            ? other.getComponentName().getPackageName() : "?"));
11747                        }
11748                    }
11749                }
11750                if (chatty) {
11751                    if (r == null) {
11752                        r = new StringBuilder(256);
11753                    } else {
11754                        r.append(' ');
11755                    }
11756                    r.append(p.info.name);
11757                }
11758            }
11759            if (r != null) {
11760                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11761            }
11762
11763            N = pkg.services.size();
11764            r = null;
11765            for (i=0; i<N; i++) {
11766                PackageParser.Service s = pkg.services.get(i);
11767                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11768                        s.info.processName);
11769                mServices.addService(s);
11770                if (chatty) {
11771                    if (r == null) {
11772                        r = new StringBuilder(256);
11773                    } else {
11774                        r.append(' ');
11775                    }
11776                    r.append(s.info.name);
11777                }
11778            }
11779            if (r != null) {
11780                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11781            }
11782
11783            N = pkg.receivers.size();
11784            r = null;
11785            for (i=0; i<N; i++) {
11786                PackageParser.Activity a = pkg.receivers.get(i);
11787                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11788                        a.info.processName);
11789                mReceivers.addActivity(a, "receiver");
11790                if (chatty) {
11791                    if (r == null) {
11792                        r = new StringBuilder(256);
11793                    } else {
11794                        r.append(' ');
11795                    }
11796                    r.append(a.info.name);
11797                }
11798            }
11799            if (r != null) {
11800                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11801            }
11802
11803            N = pkg.activities.size();
11804            r = null;
11805            for (i=0; i<N; i++) {
11806                PackageParser.Activity a = pkg.activities.get(i);
11807                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11808                        a.info.processName);
11809                mActivities.addActivity(a, "activity");
11810                if (chatty) {
11811                    if (r == null) {
11812                        r = new StringBuilder(256);
11813                    } else {
11814                        r.append(' ');
11815                    }
11816                    r.append(a.info.name);
11817                }
11818            }
11819            if (r != null) {
11820                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11821            }
11822
11823            N = pkg.permissionGroups.size();
11824            r = null;
11825            for (i=0; i<N; i++) {
11826                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11827                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11828                final String curPackageName = cur == null ? null : cur.info.packageName;
11829                // Dont allow ephemeral apps to define new permission groups.
11830                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11831                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11832                            + pg.info.packageName
11833                            + " ignored: instant apps cannot define new permission groups.");
11834                    continue;
11835                }
11836                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11837                if (cur == null || isPackageUpdate) {
11838                    mPermissionGroups.put(pg.info.name, pg);
11839                    if (chatty) {
11840                        if (r == null) {
11841                            r = new StringBuilder(256);
11842                        } else {
11843                            r.append(' ');
11844                        }
11845                        if (isPackageUpdate) {
11846                            r.append("UPD:");
11847                        }
11848                        r.append(pg.info.name);
11849                    }
11850                } else {
11851                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11852                            + pg.info.packageName + " ignored: original from "
11853                            + cur.info.packageName);
11854                    if (chatty) {
11855                        if (r == null) {
11856                            r = new StringBuilder(256);
11857                        } else {
11858                            r.append(' ');
11859                        }
11860                        r.append("DUP:");
11861                        r.append(pg.info.name);
11862                    }
11863                }
11864            }
11865            if (r != null) {
11866                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11867            }
11868
11869            N = pkg.permissions.size();
11870            r = null;
11871            for (i=0; i<N; i++) {
11872                PackageParser.Permission p = pkg.permissions.get(i);
11873
11874                // Dont allow ephemeral apps to define new permissions.
11875                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11876                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11877                            + p.info.packageName
11878                            + " ignored: instant apps cannot define new permissions.");
11879                    continue;
11880                }
11881
11882                // Assume by default that we did not install this permission into the system.
11883                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11884
11885                // Now that permission groups have a special meaning, we ignore permission
11886                // groups for legacy apps to prevent unexpected behavior. In particular,
11887                // permissions for one app being granted to someone just because they happen
11888                // to be in a group defined by another app (before this had no implications).
11889                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11890                    p.group = mPermissionGroups.get(p.info.group);
11891                    // Warn for a permission in an unknown group.
11892                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11893                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11894                                + p.info.packageName + " in an unknown group " + p.info.group);
11895                    }
11896                }
11897
11898                ArrayMap<String, BasePermission> permissionMap =
11899                        p.tree ? mSettings.mPermissionTrees
11900                                : mSettings.mPermissions;
11901                BasePermission bp = permissionMap.get(p.info.name);
11902
11903                // Allow system apps to redefine non-system permissions
11904                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11905                    final boolean currentOwnerIsSystem = (bp.perm != null
11906                            && isSystemApp(bp.perm.owner));
11907                    if (isSystemApp(p.owner)) {
11908                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11909                            // It's a built-in permission and no owner, take ownership now
11910                            bp.packageSetting = pkgSetting;
11911                            bp.perm = p;
11912                            bp.uid = pkg.applicationInfo.uid;
11913                            bp.sourcePackage = p.info.packageName;
11914                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11915                        } else if (!currentOwnerIsSystem) {
11916                            String msg = "New decl " + p.owner + " of permission  "
11917                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
11918                            reportSettingsProblem(Log.WARN, msg);
11919                            bp = null;
11920                        }
11921                    }
11922                }
11923
11924                if (bp == null) {
11925                    bp = new BasePermission(p.info.name, p.info.packageName,
11926                            BasePermission.TYPE_NORMAL);
11927                    permissionMap.put(p.info.name, bp);
11928                }
11929
11930                if (bp.perm == null) {
11931                    if (bp.sourcePackage == null
11932                            || bp.sourcePackage.equals(p.info.packageName)) {
11933                        BasePermission tree = findPermissionTreeLP(p.info.name);
11934                        if (tree == null
11935                                || tree.sourcePackage.equals(p.info.packageName)) {
11936                            bp.packageSetting = pkgSetting;
11937                            bp.perm = p;
11938                            bp.uid = pkg.applicationInfo.uid;
11939                            bp.sourcePackage = p.info.packageName;
11940                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11941                            if (chatty) {
11942                                if (r == null) {
11943                                    r = new StringBuilder(256);
11944                                } else {
11945                                    r.append(' ');
11946                                }
11947                                r.append(p.info.name);
11948                            }
11949                        } else {
11950                            Slog.w(TAG, "Permission " + p.info.name + " from package "
11951                                    + p.info.packageName + " ignored: base tree "
11952                                    + tree.name + " is from package "
11953                                    + tree.sourcePackage);
11954                        }
11955                    } else {
11956                        Slog.w(TAG, "Permission " + p.info.name + " from package "
11957                                + p.info.packageName + " ignored: original from "
11958                                + bp.sourcePackage);
11959                    }
11960                } else if (chatty) {
11961                    if (r == null) {
11962                        r = new StringBuilder(256);
11963                    } else {
11964                        r.append(' ');
11965                    }
11966                    r.append("DUP:");
11967                    r.append(p.info.name);
11968                }
11969                if (bp.perm == p) {
11970                    bp.protectionLevel = p.info.protectionLevel;
11971                }
11972            }
11973
11974            if (r != null) {
11975                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
11976            }
11977
11978            N = pkg.instrumentation.size();
11979            r = null;
11980            for (i=0; i<N; i++) {
11981                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11982                a.info.packageName = pkg.applicationInfo.packageName;
11983                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11984                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11985                a.info.splitNames = pkg.splitNames;
11986                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11987                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11988                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11989                a.info.dataDir = pkg.applicationInfo.dataDir;
11990                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11991                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11992                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11993                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11994                mInstrumentation.put(a.getComponentName(), a);
11995                if (chatty) {
11996                    if (r == null) {
11997                        r = new StringBuilder(256);
11998                    } else {
11999                        r.append(' ');
12000                    }
12001                    r.append(a.info.name);
12002                }
12003            }
12004            if (r != null) {
12005                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
12006            }
12007
12008            if (pkg.protectedBroadcasts != null) {
12009                N = pkg.protectedBroadcasts.size();
12010                synchronized (mProtectedBroadcasts) {
12011                    for (i = 0; i < N; i++) {
12012                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
12013                    }
12014                }
12015            }
12016        }
12017
12018        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12019    }
12020
12021    /**
12022     * Derive the ABI of a non-system package located at {@code scanFile}. This information
12023     * is derived purely on the basis of the contents of {@code scanFile} and
12024     * {@code cpuAbiOverride}.
12025     *
12026     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
12027     */
12028    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
12029                                 String cpuAbiOverride, boolean extractLibs,
12030                                 File appLib32InstallDir)
12031            throws PackageManagerException {
12032        // Give ourselves some initial paths; we'll come back for another
12033        // pass once we've determined ABI below.
12034        setNativeLibraryPaths(pkg, appLib32InstallDir);
12035
12036        // We would never need to extract libs for forward-locked and external packages,
12037        // since the container service will do it for us. We shouldn't attempt to
12038        // extract libs from system app when it was not updated.
12039        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
12040                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
12041            extractLibs = false;
12042        }
12043
12044        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
12045        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
12046
12047        NativeLibraryHelper.Handle handle = null;
12048        try {
12049            handle = NativeLibraryHelper.Handle.create(pkg);
12050            // TODO(multiArch): This can be null for apps that didn't go through the
12051            // usual installation process. We can calculate it again, like we
12052            // do during install time.
12053            //
12054            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
12055            // unnecessary.
12056            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
12057
12058            // Null out the abis so that they can be recalculated.
12059            pkg.applicationInfo.primaryCpuAbi = null;
12060            pkg.applicationInfo.secondaryCpuAbi = null;
12061            if (isMultiArch(pkg.applicationInfo)) {
12062                // Warn if we've set an abiOverride for multi-lib packages..
12063                // By definition, we need to copy both 32 and 64 bit libraries for
12064                // such packages.
12065                if (pkg.cpuAbiOverride != null
12066                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
12067                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
12068                }
12069
12070                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
12071                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
12072                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
12073                    if (extractLibs) {
12074                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
12075                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
12076                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
12077                                useIsaSpecificSubdirs);
12078                    } else {
12079                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
12080                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
12081                    }
12082                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12083                }
12084
12085                // Shared library native code should be in the APK zip aligned
12086                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
12087                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12088                            "Shared library native lib extraction not supported");
12089                }
12090
12091                maybeThrowExceptionForMultiArchCopy(
12092                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
12093
12094                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
12095                    if (extractLibs) {
12096                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
12097                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
12098                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
12099                                useIsaSpecificSubdirs);
12100                    } else {
12101                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
12102                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
12103                    }
12104                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12105                }
12106
12107                maybeThrowExceptionForMultiArchCopy(
12108                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
12109
12110                if (abi64 >= 0) {
12111                    // Shared library native libs should be in the APK zip aligned
12112                    if (extractLibs && pkg.isLibrary()) {
12113                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12114                                "Shared library native lib extraction not supported");
12115                    }
12116                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
12117                }
12118
12119                if (abi32 >= 0) {
12120                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
12121                    if (abi64 >= 0) {
12122                        if (pkg.use32bitAbi) {
12123                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
12124                            pkg.applicationInfo.primaryCpuAbi = abi;
12125                        } else {
12126                            pkg.applicationInfo.secondaryCpuAbi = abi;
12127                        }
12128                    } else {
12129                        pkg.applicationInfo.primaryCpuAbi = abi;
12130                    }
12131                }
12132            } else {
12133                String[] abiList = (cpuAbiOverride != null) ?
12134                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
12135
12136                // Enable gross and lame hacks for apps that are built with old
12137                // SDK tools. We must scan their APKs for renderscript bitcode and
12138                // not launch them if it's present. Don't bother checking on devices
12139                // that don't have 64 bit support.
12140                boolean needsRenderScriptOverride = false;
12141                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
12142                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
12143                    abiList = Build.SUPPORTED_32_BIT_ABIS;
12144                    needsRenderScriptOverride = true;
12145                }
12146
12147                final int copyRet;
12148                if (extractLibs) {
12149                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
12150                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
12151                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
12152                } else {
12153                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
12154                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
12155                }
12156                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12157
12158                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
12159                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12160                            "Error unpackaging native libs for app, errorCode=" + copyRet);
12161                }
12162
12163                if (copyRet >= 0) {
12164                    // Shared libraries that have native libs must be multi-architecture
12165                    if (pkg.isLibrary()) {
12166                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12167                                "Shared library with native libs must be multiarch");
12168                    }
12169                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
12170                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
12171                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
12172                } else if (needsRenderScriptOverride) {
12173                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
12174                }
12175            }
12176        } catch (IOException ioe) {
12177            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
12178        } finally {
12179            IoUtils.closeQuietly(handle);
12180        }
12181
12182        // Now that we've calculated the ABIs and determined if it's an internal app,
12183        // we will go ahead and populate the nativeLibraryPath.
12184        setNativeLibraryPaths(pkg, appLib32InstallDir);
12185    }
12186
12187    /**
12188     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
12189     * i.e, so that all packages can be run inside a single process if required.
12190     *
12191     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
12192     * this function will either try and make the ABI for all packages in {@code packagesForUser}
12193     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
12194     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
12195     * updating a package that belongs to a shared user.
12196     *
12197     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
12198     * adds unnecessary complexity.
12199     */
12200    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
12201            PackageParser.Package scannedPackage) {
12202        String requiredInstructionSet = null;
12203        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
12204            requiredInstructionSet = VMRuntime.getInstructionSet(
12205                     scannedPackage.applicationInfo.primaryCpuAbi);
12206        }
12207
12208        PackageSetting requirer = null;
12209        for (PackageSetting ps : packagesForUser) {
12210            // If packagesForUser contains scannedPackage, we skip it. This will happen
12211            // when scannedPackage is an update of an existing package. Without this check,
12212            // we will never be able to change the ABI of any package belonging to a shared
12213            // user, even if it's compatible with other packages.
12214            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
12215                if (ps.primaryCpuAbiString == null) {
12216                    continue;
12217                }
12218
12219                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
12220                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
12221                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
12222                    // this but there's not much we can do.
12223                    String errorMessage = "Instruction set mismatch, "
12224                            + ((requirer == null) ? "[caller]" : requirer)
12225                            + " requires " + requiredInstructionSet + " whereas " + ps
12226                            + " requires " + instructionSet;
12227                    Slog.w(TAG, errorMessage);
12228                }
12229
12230                if (requiredInstructionSet == null) {
12231                    requiredInstructionSet = instructionSet;
12232                    requirer = ps;
12233                }
12234            }
12235        }
12236
12237        if (requiredInstructionSet != null) {
12238            String adjustedAbi;
12239            if (requirer != null) {
12240                // requirer != null implies that either scannedPackage was null or that scannedPackage
12241                // did not require an ABI, in which case we have to adjust scannedPackage to match
12242                // the ABI of the set (which is the same as requirer's ABI)
12243                adjustedAbi = requirer.primaryCpuAbiString;
12244                if (scannedPackage != null) {
12245                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
12246                }
12247            } else {
12248                // requirer == null implies that we're updating all ABIs in the set to
12249                // match scannedPackage.
12250                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
12251            }
12252
12253            for (PackageSetting ps : packagesForUser) {
12254                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
12255                    if (ps.primaryCpuAbiString != null) {
12256                        continue;
12257                    }
12258
12259                    ps.primaryCpuAbiString = adjustedAbi;
12260                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
12261                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
12262                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
12263                        if (DEBUG_ABI_SELECTION) {
12264                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
12265                                    + " (requirer="
12266                                    + (requirer != null ? requirer.pkg : "null")
12267                                    + ", scannedPackage="
12268                                    + (scannedPackage != null ? scannedPackage : "null")
12269                                    + ")");
12270                        }
12271                        try {
12272                            mInstaller.rmdex(ps.codePathString,
12273                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
12274                        } catch (InstallerException ignored) {
12275                        }
12276                    }
12277                }
12278            }
12279        }
12280    }
12281
12282    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
12283        synchronized (mPackages) {
12284            mResolverReplaced = true;
12285            // Set up information for custom user intent resolution activity.
12286            mResolveActivity.applicationInfo = pkg.applicationInfo;
12287            mResolveActivity.name = mCustomResolverComponentName.getClassName();
12288            mResolveActivity.packageName = pkg.applicationInfo.packageName;
12289            mResolveActivity.processName = pkg.applicationInfo.packageName;
12290            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
12291            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
12292                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12293            mResolveActivity.theme = 0;
12294            mResolveActivity.exported = true;
12295            mResolveActivity.enabled = true;
12296            mResolveInfo.activityInfo = mResolveActivity;
12297            mResolveInfo.priority = 0;
12298            mResolveInfo.preferredOrder = 0;
12299            mResolveInfo.match = 0;
12300            mResolveComponentName = mCustomResolverComponentName;
12301            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
12302                    mResolveComponentName);
12303        }
12304    }
12305
12306    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
12307        if (installerActivity == null) {
12308            if (DEBUG_EPHEMERAL) {
12309                Slog.d(TAG, "Clear ephemeral installer activity");
12310            }
12311            mInstantAppInstallerActivity = null;
12312            return;
12313        }
12314
12315        if (DEBUG_EPHEMERAL) {
12316            Slog.d(TAG, "Set ephemeral installer activity: "
12317                    + installerActivity.getComponentName());
12318        }
12319        // Set up information for ephemeral installer activity
12320        mInstantAppInstallerActivity = installerActivity;
12321        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
12322                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12323        mInstantAppInstallerActivity.exported = true;
12324        mInstantAppInstallerActivity.enabled = true;
12325        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
12326        mInstantAppInstallerInfo.priority = 0;
12327        mInstantAppInstallerInfo.preferredOrder = 1;
12328        mInstantAppInstallerInfo.isDefault = true;
12329        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
12330                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
12331    }
12332
12333    private static String calculateBundledApkRoot(final String codePathString) {
12334        final File codePath = new File(codePathString);
12335        final File codeRoot;
12336        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
12337            codeRoot = Environment.getRootDirectory();
12338        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
12339            codeRoot = Environment.getOemDirectory();
12340        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
12341            codeRoot = Environment.getVendorDirectory();
12342        } else {
12343            // Unrecognized code path; take its top real segment as the apk root:
12344            // e.g. /something/app/blah.apk => /something
12345            try {
12346                File f = codePath.getCanonicalFile();
12347                File parent = f.getParentFile();    // non-null because codePath is a file
12348                File tmp;
12349                while ((tmp = parent.getParentFile()) != null) {
12350                    f = parent;
12351                    parent = tmp;
12352                }
12353                codeRoot = f;
12354                Slog.w(TAG, "Unrecognized code path "
12355                        + codePath + " - using " + codeRoot);
12356            } catch (IOException e) {
12357                // Can't canonicalize the code path -- shenanigans?
12358                Slog.w(TAG, "Can't canonicalize code path " + codePath);
12359                return Environment.getRootDirectory().getPath();
12360            }
12361        }
12362        return codeRoot.getPath();
12363    }
12364
12365    /**
12366     * Derive and set the location of native libraries for the given package,
12367     * which varies depending on where and how the package was installed.
12368     */
12369    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
12370        final ApplicationInfo info = pkg.applicationInfo;
12371        final String codePath = pkg.codePath;
12372        final File codeFile = new File(codePath);
12373        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
12374        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
12375
12376        info.nativeLibraryRootDir = null;
12377        info.nativeLibraryRootRequiresIsa = false;
12378        info.nativeLibraryDir = null;
12379        info.secondaryNativeLibraryDir = null;
12380
12381        if (isApkFile(codeFile)) {
12382            // Monolithic install
12383            if (bundledApp) {
12384                // If "/system/lib64/apkname" exists, assume that is the per-package
12385                // native library directory to use; otherwise use "/system/lib/apkname".
12386                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
12387                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
12388                        getPrimaryInstructionSet(info));
12389
12390                // This is a bundled system app so choose the path based on the ABI.
12391                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
12392                // is just the default path.
12393                final String apkName = deriveCodePathName(codePath);
12394                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
12395                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
12396                        apkName).getAbsolutePath();
12397
12398                if (info.secondaryCpuAbi != null) {
12399                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
12400                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
12401                            secondaryLibDir, apkName).getAbsolutePath();
12402                }
12403            } else if (asecApp) {
12404                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
12405                        .getAbsolutePath();
12406            } else {
12407                final String apkName = deriveCodePathName(codePath);
12408                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
12409                        .getAbsolutePath();
12410            }
12411
12412            info.nativeLibraryRootRequiresIsa = false;
12413            info.nativeLibraryDir = info.nativeLibraryRootDir;
12414        } else {
12415            // Cluster install
12416            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
12417            info.nativeLibraryRootRequiresIsa = true;
12418
12419            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
12420                    getPrimaryInstructionSet(info)).getAbsolutePath();
12421
12422            if (info.secondaryCpuAbi != null) {
12423                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
12424                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
12425            }
12426        }
12427    }
12428
12429    /**
12430     * Calculate the abis and roots for a bundled app. These can uniquely
12431     * be determined from the contents of the system partition, i.e whether
12432     * it contains 64 or 32 bit shared libraries etc. We do not validate any
12433     * of this information, and instead assume that the system was built
12434     * sensibly.
12435     */
12436    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
12437                                           PackageSetting pkgSetting) {
12438        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
12439
12440        // If "/system/lib64/apkname" exists, assume that is the per-package
12441        // native library directory to use; otherwise use "/system/lib/apkname".
12442        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
12443        setBundledAppAbi(pkg, apkRoot, apkName);
12444        // pkgSetting might be null during rescan following uninstall of updates
12445        // to a bundled app, so accommodate that possibility.  The settings in
12446        // that case will be established later from the parsed package.
12447        //
12448        // If the settings aren't null, sync them up with what we've just derived.
12449        // note that apkRoot isn't stored in the package settings.
12450        if (pkgSetting != null) {
12451            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
12452            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
12453        }
12454    }
12455
12456    /**
12457     * Deduces the ABI of a bundled app and sets the relevant fields on the
12458     * parsed pkg object.
12459     *
12460     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
12461     *        under which system libraries are installed.
12462     * @param apkName the name of the installed package.
12463     */
12464    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
12465        final File codeFile = new File(pkg.codePath);
12466
12467        final boolean has64BitLibs;
12468        final boolean has32BitLibs;
12469        if (isApkFile(codeFile)) {
12470            // Monolithic install
12471            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
12472            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
12473        } else {
12474            // Cluster install
12475            final File rootDir = new File(codeFile, LIB_DIR_NAME);
12476            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
12477                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
12478                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
12479                has64BitLibs = (new File(rootDir, isa)).exists();
12480            } else {
12481                has64BitLibs = false;
12482            }
12483            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
12484                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
12485                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
12486                has32BitLibs = (new File(rootDir, isa)).exists();
12487            } else {
12488                has32BitLibs = false;
12489            }
12490        }
12491
12492        if (has64BitLibs && !has32BitLibs) {
12493            // The package has 64 bit libs, but not 32 bit libs. Its primary
12494            // ABI should be 64 bit. We can safely assume here that the bundled
12495            // native libraries correspond to the most preferred ABI in the list.
12496
12497            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12498            pkg.applicationInfo.secondaryCpuAbi = null;
12499        } else if (has32BitLibs && !has64BitLibs) {
12500            // The package has 32 bit libs but not 64 bit libs. Its primary
12501            // ABI should be 32 bit.
12502
12503            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12504            pkg.applicationInfo.secondaryCpuAbi = null;
12505        } else if (has32BitLibs && has64BitLibs) {
12506            // The application has both 64 and 32 bit bundled libraries. We check
12507            // here that the app declares multiArch support, and warn if it doesn't.
12508            //
12509            // We will be lenient here and record both ABIs. The primary will be the
12510            // ABI that's higher on the list, i.e, a device that's configured to prefer
12511            // 64 bit apps will see a 64 bit primary ABI,
12512
12513            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
12514                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12515            }
12516
12517            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12518                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12519                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12520            } else {
12521                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12522                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12523            }
12524        } else {
12525            pkg.applicationInfo.primaryCpuAbi = null;
12526            pkg.applicationInfo.secondaryCpuAbi = null;
12527        }
12528    }
12529
12530    private void killApplication(String pkgName, int appId, String reason) {
12531        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12532    }
12533
12534    private void killApplication(String pkgName, int appId, int userId, String reason) {
12535        // Request the ActivityManager to kill the process(only for existing packages)
12536        // so that we do not end up in a confused state while the user is still using the older
12537        // version of the application while the new one gets installed.
12538        final long token = Binder.clearCallingIdentity();
12539        try {
12540            IActivityManager am = ActivityManager.getService();
12541            if (am != null) {
12542                try {
12543                    am.killApplication(pkgName, appId, userId, reason);
12544                } catch (RemoteException e) {
12545                }
12546            }
12547        } finally {
12548            Binder.restoreCallingIdentity(token);
12549        }
12550    }
12551
12552    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12553        // Remove the parent package setting
12554        PackageSetting ps = (PackageSetting) pkg.mExtras;
12555        if (ps != null) {
12556            removePackageLI(ps, chatty);
12557        }
12558        // Remove the child package setting
12559        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12560        for (int i = 0; i < childCount; i++) {
12561            PackageParser.Package childPkg = pkg.childPackages.get(i);
12562            ps = (PackageSetting) childPkg.mExtras;
12563            if (ps != null) {
12564                removePackageLI(ps, chatty);
12565            }
12566        }
12567    }
12568
12569    void removePackageLI(PackageSetting ps, boolean chatty) {
12570        if (DEBUG_INSTALL) {
12571            if (chatty)
12572                Log.d(TAG, "Removing package " + ps.name);
12573        }
12574
12575        // writer
12576        synchronized (mPackages) {
12577            mPackages.remove(ps.name);
12578            final PackageParser.Package pkg = ps.pkg;
12579            if (pkg != null) {
12580                cleanPackageDataStructuresLILPw(pkg, chatty);
12581            }
12582        }
12583    }
12584
12585    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12586        if (DEBUG_INSTALL) {
12587            if (chatty)
12588                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12589        }
12590
12591        // writer
12592        synchronized (mPackages) {
12593            // Remove the parent package
12594            mPackages.remove(pkg.applicationInfo.packageName);
12595            cleanPackageDataStructuresLILPw(pkg, chatty);
12596
12597            // Remove the child packages
12598            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12599            for (int i = 0; i < childCount; i++) {
12600                PackageParser.Package childPkg = pkg.childPackages.get(i);
12601                mPackages.remove(childPkg.applicationInfo.packageName);
12602                cleanPackageDataStructuresLILPw(childPkg, chatty);
12603            }
12604        }
12605    }
12606
12607    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12608        int N = pkg.providers.size();
12609        StringBuilder r = null;
12610        int i;
12611        for (i=0; i<N; i++) {
12612            PackageParser.Provider p = pkg.providers.get(i);
12613            mProviders.removeProvider(p);
12614            if (p.info.authority == null) {
12615
12616                /* There was another ContentProvider with this authority when
12617                 * this app was installed so this authority is null,
12618                 * Ignore it as we don't have to unregister the provider.
12619                 */
12620                continue;
12621            }
12622            String names[] = p.info.authority.split(";");
12623            for (int j = 0; j < names.length; j++) {
12624                if (mProvidersByAuthority.get(names[j]) == p) {
12625                    mProvidersByAuthority.remove(names[j]);
12626                    if (DEBUG_REMOVE) {
12627                        if (chatty)
12628                            Log.d(TAG, "Unregistered content provider: " + names[j]
12629                                    + ", className = " + p.info.name + ", isSyncable = "
12630                                    + p.info.isSyncable);
12631                    }
12632                }
12633            }
12634            if (DEBUG_REMOVE && chatty) {
12635                if (r == null) {
12636                    r = new StringBuilder(256);
12637                } else {
12638                    r.append(' ');
12639                }
12640                r.append(p.info.name);
12641            }
12642        }
12643        if (r != null) {
12644            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12645        }
12646
12647        N = pkg.services.size();
12648        r = null;
12649        for (i=0; i<N; i++) {
12650            PackageParser.Service s = pkg.services.get(i);
12651            mServices.removeService(s);
12652            if (chatty) {
12653                if (r == null) {
12654                    r = new StringBuilder(256);
12655                } else {
12656                    r.append(' ');
12657                }
12658                r.append(s.info.name);
12659            }
12660        }
12661        if (r != null) {
12662            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12663        }
12664
12665        N = pkg.receivers.size();
12666        r = null;
12667        for (i=0; i<N; i++) {
12668            PackageParser.Activity a = pkg.receivers.get(i);
12669            mReceivers.removeActivity(a, "receiver");
12670            if (DEBUG_REMOVE && chatty) {
12671                if (r == null) {
12672                    r = new StringBuilder(256);
12673                } else {
12674                    r.append(' ');
12675                }
12676                r.append(a.info.name);
12677            }
12678        }
12679        if (r != null) {
12680            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12681        }
12682
12683        N = pkg.activities.size();
12684        r = null;
12685        for (i=0; i<N; i++) {
12686            PackageParser.Activity a = pkg.activities.get(i);
12687            mActivities.removeActivity(a, "activity");
12688            if (DEBUG_REMOVE && chatty) {
12689                if (r == null) {
12690                    r = new StringBuilder(256);
12691                } else {
12692                    r.append(' ');
12693                }
12694                r.append(a.info.name);
12695            }
12696        }
12697        if (r != null) {
12698            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12699        }
12700
12701        N = pkg.permissions.size();
12702        r = null;
12703        for (i=0; i<N; i++) {
12704            PackageParser.Permission p = pkg.permissions.get(i);
12705            BasePermission bp = mSettings.mPermissions.get(p.info.name);
12706            if (bp == null) {
12707                bp = mSettings.mPermissionTrees.get(p.info.name);
12708            }
12709            if (bp != null && bp.perm == p) {
12710                bp.perm = null;
12711                if (DEBUG_REMOVE && chatty) {
12712                    if (r == null) {
12713                        r = new StringBuilder(256);
12714                    } else {
12715                        r.append(' ');
12716                    }
12717                    r.append(p.info.name);
12718                }
12719            }
12720            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12721                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12722                if (appOpPkgs != null) {
12723                    appOpPkgs.remove(pkg.packageName);
12724                }
12725            }
12726        }
12727        if (r != null) {
12728            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12729        }
12730
12731        N = pkg.requestedPermissions.size();
12732        r = null;
12733        for (i=0; i<N; i++) {
12734            String perm = pkg.requestedPermissions.get(i);
12735            BasePermission bp = mSettings.mPermissions.get(perm);
12736            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12737                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12738                if (appOpPkgs != null) {
12739                    appOpPkgs.remove(pkg.packageName);
12740                    if (appOpPkgs.isEmpty()) {
12741                        mAppOpPermissionPackages.remove(perm);
12742                    }
12743                }
12744            }
12745        }
12746        if (r != null) {
12747            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12748        }
12749
12750        N = pkg.instrumentation.size();
12751        r = null;
12752        for (i=0; i<N; i++) {
12753            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12754            mInstrumentation.remove(a.getComponentName());
12755            if (DEBUG_REMOVE && chatty) {
12756                if (r == null) {
12757                    r = new StringBuilder(256);
12758                } else {
12759                    r.append(' ');
12760                }
12761                r.append(a.info.name);
12762            }
12763        }
12764        if (r != null) {
12765            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12766        }
12767
12768        r = null;
12769        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12770            // Only system apps can hold shared libraries.
12771            if (pkg.libraryNames != null) {
12772                for (i = 0; i < pkg.libraryNames.size(); i++) {
12773                    String name = pkg.libraryNames.get(i);
12774                    if (removeSharedLibraryLPw(name, 0)) {
12775                        if (DEBUG_REMOVE && chatty) {
12776                            if (r == null) {
12777                                r = new StringBuilder(256);
12778                            } else {
12779                                r.append(' ');
12780                            }
12781                            r.append(name);
12782                        }
12783                    }
12784                }
12785            }
12786        }
12787
12788        r = null;
12789
12790        // Any package can hold static shared libraries.
12791        if (pkg.staticSharedLibName != null) {
12792            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12793                if (DEBUG_REMOVE && chatty) {
12794                    if (r == null) {
12795                        r = new StringBuilder(256);
12796                    } else {
12797                        r.append(' ');
12798                    }
12799                    r.append(pkg.staticSharedLibName);
12800                }
12801            }
12802        }
12803
12804        if (r != null) {
12805            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12806        }
12807    }
12808
12809    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12810        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12811            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12812                return true;
12813            }
12814        }
12815        return false;
12816    }
12817
12818    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12819    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12820    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12821
12822    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12823        // Update the parent permissions
12824        updatePermissionsLPw(pkg.packageName, pkg, flags);
12825        // Update the child permissions
12826        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12827        for (int i = 0; i < childCount; i++) {
12828            PackageParser.Package childPkg = pkg.childPackages.get(i);
12829            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12830        }
12831    }
12832
12833    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12834            int flags) {
12835        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12836        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12837    }
12838
12839    private void updatePermissionsLPw(String changingPkg,
12840            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12841        // Make sure there are no dangling permission trees.
12842        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12843        while (it.hasNext()) {
12844            final BasePermission bp = it.next();
12845            if (bp.packageSetting == null) {
12846                // We may not yet have parsed the package, so just see if
12847                // we still know about its settings.
12848                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12849            }
12850            if (bp.packageSetting == null) {
12851                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12852                        + " from package " + bp.sourcePackage);
12853                it.remove();
12854            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12855                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12856                    Slog.i(TAG, "Removing old permission tree: " + bp.name
12857                            + " from package " + bp.sourcePackage);
12858                    flags |= UPDATE_PERMISSIONS_ALL;
12859                    it.remove();
12860                }
12861            }
12862        }
12863
12864        // Make sure all dynamic permissions have been assigned to a package,
12865        // and make sure there are no dangling permissions.
12866        it = mSettings.mPermissions.values().iterator();
12867        while (it.hasNext()) {
12868            final BasePermission bp = it.next();
12869            if (bp.type == BasePermission.TYPE_DYNAMIC) {
12870                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12871                        + bp.name + " pkg=" + bp.sourcePackage
12872                        + " info=" + bp.pendingInfo);
12873                if (bp.packageSetting == null && bp.pendingInfo != null) {
12874                    final BasePermission tree = findPermissionTreeLP(bp.name);
12875                    if (tree != null && tree.perm != null) {
12876                        bp.packageSetting = tree.packageSetting;
12877                        bp.perm = new PackageParser.Permission(tree.perm.owner,
12878                                new PermissionInfo(bp.pendingInfo));
12879                        bp.perm.info.packageName = tree.perm.info.packageName;
12880                        bp.perm.info.name = bp.name;
12881                        bp.uid = tree.uid;
12882                    }
12883                }
12884            }
12885            if (bp.packageSetting == null) {
12886                // We may not yet have parsed the package, so just see if
12887                // we still know about its settings.
12888                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12889            }
12890            if (bp.packageSetting == null) {
12891                Slog.w(TAG, "Removing dangling permission: " + bp.name
12892                        + " from package " + bp.sourcePackage);
12893                it.remove();
12894            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12895                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12896                    Slog.i(TAG, "Removing old permission: " + bp.name
12897                            + " from package " + bp.sourcePackage);
12898                    flags |= UPDATE_PERMISSIONS_ALL;
12899                    it.remove();
12900                }
12901            }
12902        }
12903
12904        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12905        // Now update the permissions for all packages, in particular
12906        // replace the granted permissions of the system packages.
12907        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12908            for (PackageParser.Package pkg : mPackages.values()) {
12909                if (pkg != pkgInfo) {
12910                    // Only replace for packages on requested volume
12911                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12912                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12913                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12914                    grantPermissionsLPw(pkg, replace, changingPkg);
12915                }
12916            }
12917        }
12918
12919        if (pkgInfo != null) {
12920            // Only replace for packages on requested volume
12921            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12922            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12923                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12924            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12925        }
12926        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12927    }
12928
12929    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12930            String packageOfInterest) {
12931        // IMPORTANT: There are two types of permissions: install and runtime.
12932        // Install time permissions are granted when the app is installed to
12933        // all device users and users added in the future. Runtime permissions
12934        // are granted at runtime explicitly to specific users. Normal and signature
12935        // protected permissions are install time permissions. Dangerous permissions
12936        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12937        // otherwise they are runtime permissions. This function does not manage
12938        // runtime permissions except for the case an app targeting Lollipop MR1
12939        // being upgraded to target a newer SDK, in which case dangerous permissions
12940        // are transformed from install time to runtime ones.
12941
12942        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12943        if (ps == null) {
12944            return;
12945        }
12946
12947        PermissionsState permissionsState = ps.getPermissionsState();
12948        PermissionsState origPermissions = permissionsState;
12949
12950        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12951
12952        boolean runtimePermissionsRevoked = false;
12953        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12954
12955        boolean changedInstallPermission = false;
12956
12957        if (replace) {
12958            ps.installPermissionsFixed = false;
12959            if (!ps.isSharedUser()) {
12960                origPermissions = new PermissionsState(permissionsState);
12961                permissionsState.reset();
12962            } else {
12963                // We need to know only about runtime permission changes since the
12964                // calling code always writes the install permissions state but
12965                // the runtime ones are written only if changed. The only cases of
12966                // changed runtime permissions here are promotion of an install to
12967                // runtime and revocation of a runtime from a shared user.
12968                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12969                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
12970                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12971                    runtimePermissionsRevoked = true;
12972                }
12973            }
12974        }
12975
12976        permissionsState.setGlobalGids(mGlobalGids);
12977
12978        final int N = pkg.requestedPermissions.size();
12979        for (int i=0; i<N; i++) {
12980            final String name = pkg.requestedPermissions.get(i);
12981            final BasePermission bp = mSettings.mPermissions.get(name);
12982            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12983                    >= Build.VERSION_CODES.M;
12984
12985            if (DEBUG_INSTALL) {
12986                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12987            }
12988
12989            if (bp == null || bp.packageSetting == null) {
12990                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12991                    if (DEBUG_PERMISSIONS) {
12992                        Slog.i(TAG, "Unknown permission " + name
12993                                + " in package " + pkg.packageName);
12994                    }
12995                }
12996                continue;
12997            }
12998
12999
13000            // Limit ephemeral apps to ephemeral allowed permissions.
13001            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
13002                if (DEBUG_PERMISSIONS) {
13003                    Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
13004                            + pkg.packageName);
13005                }
13006                continue;
13007            }
13008
13009            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
13010                if (DEBUG_PERMISSIONS) {
13011                    Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
13012                            + pkg.packageName);
13013                }
13014                continue;
13015            }
13016
13017            final String perm = bp.name;
13018            boolean allowedSig = false;
13019            int grant = GRANT_DENIED;
13020
13021            // Keep track of app op permissions.
13022            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
13023                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
13024                if (pkgs == null) {
13025                    pkgs = new ArraySet<>();
13026                    mAppOpPermissionPackages.put(bp.name, pkgs);
13027                }
13028                pkgs.add(pkg.packageName);
13029            }
13030
13031            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
13032            switch (level) {
13033                case PermissionInfo.PROTECTION_NORMAL: {
13034                    // For all apps normal permissions are install time ones.
13035                    grant = GRANT_INSTALL;
13036                } break;
13037
13038                case PermissionInfo.PROTECTION_DANGEROUS: {
13039                    // If a permission review is required for legacy apps we represent
13040                    // their permissions as always granted runtime ones since we need
13041                    // to keep the review required permission flag per user while an
13042                    // install permission's state is shared across all users.
13043                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
13044                        // For legacy apps dangerous permissions are install time ones.
13045                        grant = GRANT_INSTALL;
13046                    } else if (origPermissions.hasInstallPermission(bp.name)) {
13047                        // For legacy apps that became modern, install becomes runtime.
13048                        grant = GRANT_UPGRADE;
13049                    } else if (mPromoteSystemApps
13050                            && isSystemApp(ps)
13051                            && mExistingSystemPackages.contains(ps.name)) {
13052                        // For legacy system apps, install becomes runtime.
13053                        // We cannot check hasInstallPermission() for system apps since those
13054                        // permissions were granted implicitly and not persisted pre-M.
13055                        grant = GRANT_UPGRADE;
13056                    } else {
13057                        // For modern apps keep runtime permissions unchanged.
13058                        grant = GRANT_RUNTIME;
13059                    }
13060                } break;
13061
13062                case PermissionInfo.PROTECTION_SIGNATURE: {
13063                    // For all apps signature permissions are install time ones.
13064                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
13065                    if (allowedSig) {
13066                        grant = GRANT_INSTALL;
13067                    }
13068                } break;
13069            }
13070
13071            if (DEBUG_PERMISSIONS) {
13072                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
13073            }
13074
13075            if (grant != GRANT_DENIED) {
13076                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
13077                    // If this is an existing, non-system package, then
13078                    // we can't add any new permissions to it.
13079                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
13080                        // Except...  if this is a permission that was added
13081                        // to the platform (note: need to only do this when
13082                        // updating the platform).
13083                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
13084                            grant = GRANT_DENIED;
13085                        }
13086                    }
13087                }
13088
13089                switch (grant) {
13090                    case GRANT_INSTALL: {
13091                        // Revoke this as runtime permission to handle the case of
13092                        // a runtime permission being downgraded to an install one.
13093                        // Also in permission review mode we keep dangerous permissions
13094                        // for legacy apps
13095                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13096                            if (origPermissions.getRuntimePermissionState(
13097                                    bp.name, userId) != null) {
13098                                // Revoke the runtime permission and clear the flags.
13099                                origPermissions.revokeRuntimePermission(bp, userId);
13100                                origPermissions.updatePermissionFlags(bp, userId,
13101                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
13102                                // If we revoked a permission permission, we have to write.
13103                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13104                                        changedRuntimePermissionUserIds, userId);
13105                            }
13106                        }
13107                        // Grant an install permission.
13108                        if (permissionsState.grantInstallPermission(bp) !=
13109                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
13110                            changedInstallPermission = true;
13111                        }
13112                    } break;
13113
13114                    case GRANT_RUNTIME: {
13115                        // Grant previously granted runtime permissions.
13116                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13117                            PermissionState permissionState = origPermissions
13118                                    .getRuntimePermissionState(bp.name, userId);
13119                            int flags = permissionState != null
13120                                    ? permissionState.getFlags() : 0;
13121                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
13122                                // Don't propagate the permission in a permission review mode if
13123                                // the former was revoked, i.e. marked to not propagate on upgrade.
13124                                // Note that in a permission review mode install permissions are
13125                                // represented as constantly granted runtime ones since we need to
13126                                // keep a per user state associated with the permission. Also the
13127                                // revoke on upgrade flag is no longer applicable and is reset.
13128                                final boolean revokeOnUpgrade = (flags & PackageManager
13129                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
13130                                if (revokeOnUpgrade) {
13131                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13132                                    // Since we changed the flags, we have to write.
13133                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13134                                            changedRuntimePermissionUserIds, userId);
13135                                }
13136                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
13137                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
13138                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
13139                                        // If we cannot put the permission as it was,
13140                                        // we have to write.
13141                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13142                                                changedRuntimePermissionUserIds, userId);
13143                                    }
13144                                }
13145
13146                                // If the app supports runtime permissions no need for a review.
13147                                if (mPermissionReviewRequired
13148                                        && appSupportsRuntimePermissions
13149                                        && (flags & PackageManager
13150                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
13151                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
13152                                    // Since we changed the flags, we have to write.
13153                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13154                                            changedRuntimePermissionUserIds, userId);
13155                                }
13156                            } else if (mPermissionReviewRequired
13157                                    && !appSupportsRuntimePermissions) {
13158                                // For legacy apps that need a permission review, every new
13159                                // runtime permission is granted but it is pending a review.
13160                                // We also need to review only platform defined runtime
13161                                // permissions as these are the only ones the platform knows
13162                                // how to disable the API to simulate revocation as legacy
13163                                // apps don't expect to run with revoked permissions.
13164                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
13165                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
13166                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
13167                                        // We changed the flags, hence have to write.
13168                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13169                                                changedRuntimePermissionUserIds, userId);
13170                                    }
13171                                }
13172                                if (permissionsState.grantRuntimePermission(bp, userId)
13173                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
13174                                    // We changed the permission, hence have to write.
13175                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13176                                            changedRuntimePermissionUserIds, userId);
13177                                }
13178                            }
13179                            // Propagate the permission flags.
13180                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
13181                        }
13182                    } break;
13183
13184                    case GRANT_UPGRADE: {
13185                        // Grant runtime permissions for a previously held install permission.
13186                        PermissionState permissionState = origPermissions
13187                                .getInstallPermissionState(bp.name);
13188                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
13189
13190                        if (origPermissions.revokeInstallPermission(bp)
13191                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
13192                            // We will be transferring the permission flags, so clear them.
13193                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
13194                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
13195                            changedInstallPermission = true;
13196                        }
13197
13198                        // If the permission is not to be promoted to runtime we ignore it and
13199                        // also its other flags as they are not applicable to install permissions.
13200                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
13201                            for (int userId : currentUserIds) {
13202                                if (permissionsState.grantRuntimePermission(bp, userId) !=
13203                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
13204                                    // Transfer the permission flags.
13205                                    permissionsState.updatePermissionFlags(bp, userId,
13206                                            flags, flags);
13207                                    // If we granted the permission, we have to write.
13208                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13209                                            changedRuntimePermissionUserIds, userId);
13210                                }
13211                            }
13212                        }
13213                    } break;
13214
13215                    default: {
13216                        if (packageOfInterest == null
13217                                || packageOfInterest.equals(pkg.packageName)) {
13218                            if (DEBUG_PERMISSIONS) {
13219                                Slog.i(TAG, "Not granting permission " + perm
13220                                        + " to package " + pkg.packageName
13221                                        + " because it was previously installed without");
13222                            }
13223                        }
13224                    } break;
13225                }
13226            } else {
13227                if (permissionsState.revokeInstallPermission(bp) !=
13228                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
13229                    // Also drop the permission flags.
13230                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
13231                            PackageManager.MASK_PERMISSION_FLAGS, 0);
13232                    changedInstallPermission = true;
13233                    Slog.i(TAG, "Un-granting permission " + perm
13234                            + " from package " + pkg.packageName
13235                            + " (protectionLevel=" + bp.protectionLevel
13236                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
13237                            + ")");
13238                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
13239                    // Don't print warning for app op permissions, since it is fine for them
13240                    // not to be granted, there is a UI for the user to decide.
13241                    if (DEBUG_PERMISSIONS
13242                            && (packageOfInterest == null
13243                                    || packageOfInterest.equals(pkg.packageName))) {
13244                        Slog.i(TAG, "Not granting permission " + perm
13245                                + " to package " + pkg.packageName
13246                                + " (protectionLevel=" + bp.protectionLevel
13247                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
13248                                + ")");
13249                    }
13250                }
13251            }
13252        }
13253
13254        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
13255                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
13256            // This is the first that we have heard about this package, so the
13257            // permissions we have now selected are fixed until explicitly
13258            // changed.
13259            ps.installPermissionsFixed = true;
13260        }
13261
13262        // Persist the runtime permissions state for users with changes. If permissions
13263        // were revoked because no app in the shared user declares them we have to
13264        // write synchronously to avoid losing runtime permissions state.
13265        for (int userId : changedRuntimePermissionUserIds) {
13266            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
13267        }
13268    }
13269
13270    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
13271        boolean allowed = false;
13272        final int NP = PackageParser.NEW_PERMISSIONS.length;
13273        for (int ip=0; ip<NP; ip++) {
13274            final PackageParser.NewPermissionInfo npi
13275                    = PackageParser.NEW_PERMISSIONS[ip];
13276            if (npi.name.equals(perm)
13277                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
13278                allowed = true;
13279                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
13280                        + pkg.packageName);
13281                break;
13282            }
13283        }
13284        return allowed;
13285    }
13286
13287    /**
13288     * Determines whether a package is whitelisted for a particular privapp permission.
13289     *
13290     * <p>Does NOT check whether the package is a privapp, just whether it's whitelisted.
13291     *
13292     * <p>This handles parent/child apps.
13293     */
13294    private boolean hasPrivappWhitelistEntry(String perm, PackageParser.Package pkg) {
13295        ArraySet<String> wlPermissions = SystemConfig.getInstance()
13296                .getPrivAppPermissions(pkg.packageName);
13297        // Let's check if this package is whitelisted...
13298        boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
13299        // If it's not, we'll also tail-recurse to the parent.
13300        return whitelisted ||
13301                pkg.parentPackage != null && hasPrivappWhitelistEntry(perm, pkg.parentPackage);
13302    }
13303
13304    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
13305            BasePermission bp, PermissionsState origPermissions) {
13306        boolean oemPermission = (bp.protectionLevel
13307                & PermissionInfo.PROTECTION_FLAG_OEM) != 0;
13308        boolean privilegedPermission = (bp.protectionLevel
13309                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
13310        boolean privappPermissionsDisable =
13311                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
13312        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
13313        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
13314        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
13315                && !platformPackage && platformPermission) {
13316            if (!hasPrivappWhitelistEntry(perm, pkg)) {
13317                Slog.w(TAG, "Privileged permission " + perm + " for package "
13318                        + pkg.packageName + " - not in privapp-permissions whitelist");
13319                // Only report violations for apps on system image
13320                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
13321                    // it's only a reportable violation if the permission isn't explicitly denied
13322                    final ArraySet<String> deniedPermissions = SystemConfig.getInstance()
13323                            .getPrivAppDenyPermissions(pkg.packageName);
13324                    final boolean permissionViolation =
13325                            deniedPermissions == null || !deniedPermissions.contains(perm);
13326                    if (permissionViolation) {
13327                        if (mPrivappPermissionsViolations == null) {
13328                            mPrivappPermissionsViolations = new ArraySet<>();
13329                        }
13330                        mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
13331                    } else {
13332                        return false;
13333                    }
13334                }
13335                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
13336                    return false;
13337                }
13338            }
13339        }
13340        boolean allowed = (compareSignatures(
13341                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
13342                        == PackageManager.SIGNATURE_MATCH)
13343                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
13344                        == PackageManager.SIGNATURE_MATCH);
13345        if (!allowed && (privilegedPermission || oemPermission)) {
13346            if (isSystemApp(pkg)) {
13347                // For updated system applications, a privileged/oem permission
13348                // is granted only if it had been defined by the original application.
13349                if (pkg.isUpdatedSystemApp()) {
13350                    final PackageSetting sysPs = mSettings
13351                            .getDisabledSystemPkgLPr(pkg.packageName);
13352                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
13353                        // If the original was granted this permission, we take
13354                        // that grant decision as read and propagate it to the
13355                        // update.
13356                        if ((privilegedPermission && sysPs.isPrivileged())
13357                                || (oemPermission && sysPs.isOem()
13358                                        && canGrantOemPermission(sysPs, perm))) {
13359                            allowed = true;
13360                        }
13361                    } else {
13362                        // The system apk may have been updated with an older
13363                        // version of the one on the data partition, but which
13364                        // granted a new system permission that it didn't have
13365                        // before.  In this case we do want to allow the app to
13366                        // now get the new permission if the ancestral apk is
13367                        // privileged to get it.
13368                        if (sysPs != null && sysPs.pkg != null
13369                                && isPackageRequestingPermission(sysPs.pkg, perm)
13370                                && ((privilegedPermission && sysPs.isPrivileged())
13371                                        || (oemPermission && sysPs.isOem()
13372                                                && canGrantOemPermission(sysPs, perm)))) {
13373                            allowed = true;
13374                        }
13375                        // Also if a privileged parent package on the system image or any of
13376                        // its children requested a privileged/oem permission, the updated child
13377                        // packages can also get the permission.
13378                        if (pkg.parentPackage != null) {
13379                            final PackageSetting disabledSysParentPs = mSettings
13380                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
13381                            final PackageParser.Package disabledSysParentPkg =
13382                                    (disabledSysParentPs == null || disabledSysParentPs.pkg == null)
13383                                    ? null : disabledSysParentPs.pkg;
13384                            if (disabledSysParentPkg != null
13385                                    && ((privilegedPermission && disabledSysParentPs.isPrivileged())
13386                                            || (oemPermission && disabledSysParentPs.isOem()))) {
13387                                if (isPackageRequestingPermission(disabledSysParentPkg, perm)
13388                                        && canGrantOemPermission(disabledSysParentPs, perm)) {
13389                                    allowed = true;
13390                                } else if (disabledSysParentPkg.childPackages != null) {
13391                                    final int count = disabledSysParentPkg.childPackages.size();
13392                                    for (int i = 0; i < count; i++) {
13393                                        final PackageParser.Package disabledSysChildPkg =
13394                                                disabledSysParentPkg.childPackages.get(i);
13395                                        final PackageSetting disabledSysChildPs =
13396                                                mSettings.getDisabledSystemPkgLPr(
13397                                                        disabledSysChildPkg.packageName);
13398                                        if (isPackageRequestingPermission(disabledSysChildPkg, perm)
13399                                                && canGrantOemPermission(
13400                                                        disabledSysChildPs, perm)) {
13401                                            allowed = true;
13402                                            break;
13403                                        }
13404                                    }
13405                                }
13406                            }
13407                        }
13408                    }
13409                } else {
13410                    allowed = (privilegedPermission && isPrivilegedApp(pkg))
13411                            || (oemPermission && isOemApp(pkg)
13412                                    && canGrantOemPermission(
13413                                            mSettings.getPackageLPr(pkg.packageName), perm));
13414                }
13415            }
13416        }
13417        if (!allowed) {
13418            if (!allowed && (bp.protectionLevel
13419                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
13420                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
13421                // If this was a previously normal/dangerous permission that got moved
13422                // to a system permission as part of the runtime permission redesign, then
13423                // we still want to blindly grant it to old apps.
13424                allowed = true;
13425            }
13426            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
13427                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
13428                // If this permission is to be granted to the system installer and
13429                // this app is an installer, then it gets the permission.
13430                allowed = true;
13431            }
13432            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
13433                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
13434                // If this permission is to be granted to the system verifier and
13435                // this app is a verifier, then it gets the permission.
13436                allowed = true;
13437            }
13438            if (!allowed && (bp.protectionLevel
13439                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
13440                    && isSystemApp(pkg)) {
13441                // Any pre-installed system app is allowed to get this permission.
13442                allowed = true;
13443            }
13444            if (!allowed && (bp.protectionLevel
13445                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
13446                // For development permissions, a development permission
13447                // is granted only if it was already granted.
13448                allowed = origPermissions.hasInstallPermission(perm);
13449            }
13450            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
13451                    && pkg.packageName.equals(mSetupWizardPackage)) {
13452                // If this permission is to be granted to the system setup wizard and
13453                // this app is a setup wizard, then it gets the permission.
13454                allowed = true;
13455            }
13456        }
13457        return allowed;
13458    }
13459
13460    private static boolean canGrantOemPermission(PackageSetting ps, String permission) {
13461        if (!ps.isOem()) {
13462            return false;
13463        }
13464        // all oem permissions must explicitly be granted or denied
13465        final Boolean granted =
13466                SystemConfig.getInstance().getOemPermissions(ps.name).get(permission);
13467        if (granted == null) {
13468            throw new IllegalStateException("OEM permission" + permission + " requested by package "
13469                    + ps.name + " must be explicitly declared granted or not");
13470        }
13471        return Boolean.TRUE == granted;
13472    }
13473
13474    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
13475        final int permCount = pkg.requestedPermissions.size();
13476        for (int j = 0; j < permCount; j++) {
13477            String requestedPermission = pkg.requestedPermissions.get(j);
13478            if (permission.equals(requestedPermission)) {
13479                return true;
13480            }
13481        }
13482        return false;
13483    }
13484
13485    final class ActivityIntentResolver
13486            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
13487        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13488                boolean defaultOnly, int userId) {
13489            if (!sUserManager.exists(userId)) return null;
13490            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
13491            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13492        }
13493
13494        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13495                int userId) {
13496            if (!sUserManager.exists(userId)) return null;
13497            mFlags = flags;
13498            return super.queryIntent(intent, resolvedType,
13499                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13500                    userId);
13501        }
13502
13503        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13504                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
13505            if (!sUserManager.exists(userId)) return null;
13506            if (packageActivities == null) {
13507                return null;
13508            }
13509            mFlags = flags;
13510            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13511            final int N = packageActivities.size();
13512            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
13513                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
13514
13515            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
13516            for (int i = 0; i < N; ++i) {
13517                intentFilters = packageActivities.get(i).intents;
13518                if (intentFilters != null && intentFilters.size() > 0) {
13519                    PackageParser.ActivityIntentInfo[] array =
13520                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
13521                    intentFilters.toArray(array);
13522                    listCut.add(array);
13523                }
13524            }
13525            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13526        }
13527
13528        /**
13529         * Finds a privileged activity that matches the specified activity names.
13530         */
13531        private PackageParser.Activity findMatchingActivity(
13532                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
13533            for (PackageParser.Activity sysActivity : activityList) {
13534                if (sysActivity.info.name.equals(activityInfo.name)) {
13535                    return sysActivity;
13536                }
13537                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
13538                    return sysActivity;
13539                }
13540                if (sysActivity.info.targetActivity != null) {
13541                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
13542                        return sysActivity;
13543                    }
13544                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
13545                        return sysActivity;
13546                    }
13547                }
13548            }
13549            return null;
13550        }
13551
13552        public class IterGenerator<E> {
13553            public Iterator<E> generate(ActivityIntentInfo info) {
13554                return null;
13555            }
13556        }
13557
13558        public class ActionIterGenerator extends IterGenerator<String> {
13559            @Override
13560            public Iterator<String> generate(ActivityIntentInfo info) {
13561                return info.actionsIterator();
13562            }
13563        }
13564
13565        public class CategoriesIterGenerator extends IterGenerator<String> {
13566            @Override
13567            public Iterator<String> generate(ActivityIntentInfo info) {
13568                return info.categoriesIterator();
13569            }
13570        }
13571
13572        public class SchemesIterGenerator extends IterGenerator<String> {
13573            @Override
13574            public Iterator<String> generate(ActivityIntentInfo info) {
13575                return info.schemesIterator();
13576            }
13577        }
13578
13579        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
13580            @Override
13581            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
13582                return info.authoritiesIterator();
13583            }
13584        }
13585
13586        /**
13587         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
13588         * MODIFIED. Do not pass in a list that should not be changed.
13589         */
13590        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
13591                IterGenerator<T> generator, Iterator<T> searchIterator) {
13592            // loop through the set of actions; every one must be found in the intent filter
13593            while (searchIterator.hasNext()) {
13594                // we must have at least one filter in the list to consider a match
13595                if (intentList.size() == 0) {
13596                    break;
13597                }
13598
13599                final T searchAction = searchIterator.next();
13600
13601                // loop through the set of intent filters
13602                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
13603                while (intentIter.hasNext()) {
13604                    final ActivityIntentInfo intentInfo = intentIter.next();
13605                    boolean selectionFound = false;
13606
13607                    // loop through the intent filter's selection criteria; at least one
13608                    // of them must match the searched criteria
13609                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
13610                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
13611                        final T intentSelection = intentSelectionIter.next();
13612                        if (intentSelection != null && intentSelection.equals(searchAction)) {
13613                            selectionFound = true;
13614                            break;
13615                        }
13616                    }
13617
13618                    // the selection criteria wasn't found in this filter's set; this filter
13619                    // is not a potential match
13620                    if (!selectionFound) {
13621                        intentIter.remove();
13622                    }
13623                }
13624            }
13625        }
13626
13627        private boolean isProtectedAction(ActivityIntentInfo filter) {
13628            final Iterator<String> actionsIter = filter.actionsIterator();
13629            while (actionsIter != null && actionsIter.hasNext()) {
13630                final String filterAction = actionsIter.next();
13631                if (PROTECTED_ACTIONS.contains(filterAction)) {
13632                    return true;
13633                }
13634            }
13635            return false;
13636        }
13637
13638        /**
13639         * Adjusts the priority of the given intent filter according to policy.
13640         * <p>
13641         * <ul>
13642         * <li>The priority for non privileged applications is capped to '0'</li>
13643         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
13644         * <li>The priority for unbundled updates to privileged applications is capped to the
13645         *      priority defined on the system partition</li>
13646         * </ul>
13647         * <p>
13648         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
13649         * allowed to obtain any priority on any action.
13650         */
13651        private void adjustPriority(
13652                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
13653            // nothing to do; priority is fine as-is
13654            if (intent.getPriority() <= 0) {
13655                return;
13656            }
13657
13658            final ActivityInfo activityInfo = intent.activity.info;
13659            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
13660
13661            final boolean privilegedApp =
13662                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
13663            if (!privilegedApp) {
13664                // non-privileged applications can never define a priority >0
13665                if (DEBUG_FILTERS) {
13666                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
13667                            + " package: " + applicationInfo.packageName
13668                            + " activity: " + intent.activity.className
13669                            + " origPrio: " + intent.getPriority());
13670                }
13671                intent.setPriority(0);
13672                return;
13673            }
13674
13675            if (systemActivities == null) {
13676                // the system package is not disabled; we're parsing the system partition
13677                if (isProtectedAction(intent)) {
13678                    if (mDeferProtectedFilters) {
13679                        // We can't deal with these just yet. No component should ever obtain a
13680                        // >0 priority for a protected actions, with ONE exception -- the setup
13681                        // wizard. The setup wizard, however, cannot be known until we're able to
13682                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
13683                        // until all intent filters have been processed. Chicken, meet egg.
13684                        // Let the filter temporarily have a high priority and rectify the
13685                        // priorities after all system packages have been scanned.
13686                        mProtectedFilters.add(intent);
13687                        if (DEBUG_FILTERS) {
13688                            Slog.i(TAG, "Protected action; save for later;"
13689                                    + " package: " + applicationInfo.packageName
13690                                    + " activity: " + intent.activity.className
13691                                    + " origPrio: " + intent.getPriority());
13692                        }
13693                        return;
13694                    } else {
13695                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13696                            Slog.i(TAG, "No setup wizard;"
13697                                + " All protected intents capped to priority 0");
13698                        }
13699                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13700                            if (DEBUG_FILTERS) {
13701                                Slog.i(TAG, "Found setup wizard;"
13702                                    + " allow priority " + intent.getPriority() + ";"
13703                                    + " package: " + intent.activity.info.packageName
13704                                    + " activity: " + intent.activity.className
13705                                    + " priority: " + intent.getPriority());
13706                            }
13707                            // setup wizard gets whatever it wants
13708                            return;
13709                        }
13710                        if (DEBUG_FILTERS) {
13711                            Slog.i(TAG, "Protected action; cap priority to 0;"
13712                                    + " package: " + intent.activity.info.packageName
13713                                    + " activity: " + intent.activity.className
13714                                    + " origPrio: " + intent.getPriority());
13715                        }
13716                        intent.setPriority(0);
13717                        return;
13718                    }
13719                }
13720                // privileged apps on the system image get whatever priority they request
13721                return;
13722            }
13723
13724            // privileged app unbundled update ... try to find the same activity
13725            final PackageParser.Activity foundActivity =
13726                    findMatchingActivity(systemActivities, activityInfo);
13727            if (foundActivity == null) {
13728                // this is a new activity; it cannot obtain >0 priority
13729                if (DEBUG_FILTERS) {
13730                    Slog.i(TAG, "New activity; cap priority to 0;"
13731                            + " package: " + applicationInfo.packageName
13732                            + " activity: " + intent.activity.className
13733                            + " origPrio: " + intent.getPriority());
13734                }
13735                intent.setPriority(0);
13736                return;
13737            }
13738
13739            // found activity, now check for filter equivalence
13740
13741            // a shallow copy is enough; we modify the list, not its contents
13742            final List<ActivityIntentInfo> intentListCopy =
13743                    new ArrayList<>(foundActivity.intents);
13744            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13745
13746            // find matching action subsets
13747            final Iterator<String> actionsIterator = intent.actionsIterator();
13748            if (actionsIterator != null) {
13749                getIntentListSubset(
13750                        intentListCopy, new ActionIterGenerator(), actionsIterator);
13751                if (intentListCopy.size() == 0) {
13752                    // no more intents to match; we're not equivalent
13753                    if (DEBUG_FILTERS) {
13754                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
13755                                + " package: " + applicationInfo.packageName
13756                                + " activity: " + intent.activity.className
13757                                + " origPrio: " + intent.getPriority());
13758                    }
13759                    intent.setPriority(0);
13760                    return;
13761                }
13762            }
13763
13764            // find matching category subsets
13765            final Iterator<String> categoriesIterator = intent.categoriesIterator();
13766            if (categoriesIterator != null) {
13767                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13768                        categoriesIterator);
13769                if (intentListCopy.size() == 0) {
13770                    // no more intents to match; we're not equivalent
13771                    if (DEBUG_FILTERS) {
13772                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
13773                                + " package: " + applicationInfo.packageName
13774                                + " activity: " + intent.activity.className
13775                                + " origPrio: " + intent.getPriority());
13776                    }
13777                    intent.setPriority(0);
13778                    return;
13779                }
13780            }
13781
13782            // find matching schemes subsets
13783            final Iterator<String> schemesIterator = intent.schemesIterator();
13784            if (schemesIterator != null) {
13785                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13786                        schemesIterator);
13787                if (intentListCopy.size() == 0) {
13788                    // no more intents to match; we're not equivalent
13789                    if (DEBUG_FILTERS) {
13790                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
13791                                + " package: " + applicationInfo.packageName
13792                                + " activity: " + intent.activity.className
13793                                + " origPrio: " + intent.getPriority());
13794                    }
13795                    intent.setPriority(0);
13796                    return;
13797                }
13798            }
13799
13800            // find matching authorities subsets
13801            final Iterator<IntentFilter.AuthorityEntry>
13802                    authoritiesIterator = intent.authoritiesIterator();
13803            if (authoritiesIterator != null) {
13804                getIntentListSubset(intentListCopy,
13805                        new AuthoritiesIterGenerator(),
13806                        authoritiesIterator);
13807                if (intentListCopy.size() == 0) {
13808                    // no more intents to match; we're not equivalent
13809                    if (DEBUG_FILTERS) {
13810                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13811                                + " package: " + applicationInfo.packageName
13812                                + " activity: " + intent.activity.className
13813                                + " origPrio: " + intent.getPriority());
13814                    }
13815                    intent.setPriority(0);
13816                    return;
13817                }
13818            }
13819
13820            // we found matching filter(s); app gets the max priority of all intents
13821            int cappedPriority = 0;
13822            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13823                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13824            }
13825            if (intent.getPriority() > cappedPriority) {
13826                if (DEBUG_FILTERS) {
13827                    Slog.i(TAG, "Found matching filter(s);"
13828                            + " cap priority to " + cappedPriority + ";"
13829                            + " package: " + applicationInfo.packageName
13830                            + " activity: " + intent.activity.className
13831                            + " origPrio: " + intent.getPriority());
13832                }
13833                intent.setPriority(cappedPriority);
13834                return;
13835            }
13836            // all this for nothing; the requested priority was <= what was on the system
13837        }
13838
13839        public final void addActivity(PackageParser.Activity a, String type) {
13840            mActivities.put(a.getComponentName(), a);
13841            if (DEBUG_SHOW_INFO)
13842                Log.v(
13843                TAG, "  " + type + " " +
13844                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13845            if (DEBUG_SHOW_INFO)
13846                Log.v(TAG, "    Class=" + a.info.name);
13847            final int NI = a.intents.size();
13848            for (int j=0; j<NI; j++) {
13849                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13850                if ("activity".equals(type)) {
13851                    final PackageSetting ps =
13852                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13853                    final List<PackageParser.Activity> systemActivities =
13854                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
13855                    adjustPriority(systemActivities, intent);
13856                }
13857                if (DEBUG_SHOW_INFO) {
13858                    Log.v(TAG, "    IntentFilter:");
13859                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13860                }
13861                if (!intent.debugCheck()) {
13862                    Log.w(TAG, "==> For Activity " + a.info.name);
13863                }
13864                addFilter(intent);
13865            }
13866        }
13867
13868        public final void removeActivity(PackageParser.Activity a, String type) {
13869            mActivities.remove(a.getComponentName());
13870            if (DEBUG_SHOW_INFO) {
13871                Log.v(TAG, "  " + type + " "
13872                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13873                                : a.info.name) + ":");
13874                Log.v(TAG, "    Class=" + a.info.name);
13875            }
13876            final int NI = a.intents.size();
13877            for (int j=0; j<NI; j++) {
13878                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13879                if (DEBUG_SHOW_INFO) {
13880                    Log.v(TAG, "    IntentFilter:");
13881                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13882                }
13883                removeFilter(intent);
13884            }
13885        }
13886
13887        @Override
13888        protected boolean allowFilterResult(
13889                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13890            ActivityInfo filterAi = filter.activity.info;
13891            for (int i=dest.size()-1; i>=0; i--) {
13892                ActivityInfo destAi = dest.get(i).activityInfo;
13893                if (destAi.name == filterAi.name
13894                        && destAi.packageName == filterAi.packageName) {
13895                    return false;
13896                }
13897            }
13898            return true;
13899        }
13900
13901        @Override
13902        protected ActivityIntentInfo[] newArray(int size) {
13903            return new ActivityIntentInfo[size];
13904        }
13905
13906        @Override
13907        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13908            if (!sUserManager.exists(userId)) return true;
13909            PackageParser.Package p = filter.activity.owner;
13910            if (p != null) {
13911                PackageSetting ps = (PackageSetting)p.mExtras;
13912                if (ps != null) {
13913                    // System apps are never considered stopped for purposes of
13914                    // filtering, because there may be no way for the user to
13915                    // actually re-launch them.
13916                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13917                            && ps.getStopped(userId);
13918                }
13919            }
13920            return false;
13921        }
13922
13923        @Override
13924        protected boolean isPackageForFilter(String packageName,
13925                PackageParser.ActivityIntentInfo info) {
13926            return packageName.equals(info.activity.owner.packageName);
13927        }
13928
13929        @Override
13930        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13931                int match, int userId) {
13932            if (!sUserManager.exists(userId)) return null;
13933            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13934                return null;
13935            }
13936            final PackageParser.Activity activity = info.activity;
13937            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13938            if (ps == null) {
13939                return null;
13940            }
13941            final PackageUserState userState = ps.readUserState(userId);
13942            ActivityInfo ai =
13943                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13944            if (ai == null) {
13945                return null;
13946            }
13947            final boolean matchExplicitlyVisibleOnly =
13948                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13949            final boolean matchVisibleToInstantApp =
13950                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13951            final boolean componentVisible =
13952                    matchVisibleToInstantApp
13953                    && info.isVisibleToInstantApp()
13954                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13955            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13956            // throw out filters that aren't visible to ephemeral apps
13957            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13958                return null;
13959            }
13960            // throw out instant app filters if we're not explicitly requesting them
13961            if (!matchInstantApp && userState.instantApp) {
13962                return null;
13963            }
13964            // throw out instant app filters if updates are available; will trigger
13965            // instant app resolution
13966            if (userState.instantApp && ps.isUpdateAvailable()) {
13967                return null;
13968            }
13969            final ResolveInfo res = new ResolveInfo();
13970            res.activityInfo = ai;
13971            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13972                res.filter = info;
13973            }
13974            if (info != null) {
13975                res.handleAllWebDataURI = info.handleAllWebDataURI();
13976            }
13977            res.priority = info.getPriority();
13978            res.preferredOrder = activity.owner.mPreferredOrder;
13979            //System.out.println("Result: " + res.activityInfo.className +
13980            //                   " = " + res.priority);
13981            res.match = match;
13982            res.isDefault = info.hasDefault;
13983            res.labelRes = info.labelRes;
13984            res.nonLocalizedLabel = info.nonLocalizedLabel;
13985            if (userNeedsBadging(userId)) {
13986                res.noResourceId = true;
13987            } else {
13988                res.icon = info.icon;
13989            }
13990            res.iconResourceId = info.icon;
13991            res.system = res.activityInfo.applicationInfo.isSystemApp();
13992            res.isInstantAppAvailable = userState.instantApp;
13993            return res;
13994        }
13995
13996        @Override
13997        protected void sortResults(List<ResolveInfo> results) {
13998            Collections.sort(results, mResolvePrioritySorter);
13999        }
14000
14001        @Override
14002        protected void dumpFilter(PrintWriter out, String prefix,
14003                PackageParser.ActivityIntentInfo filter) {
14004            out.print(prefix); out.print(
14005                    Integer.toHexString(System.identityHashCode(filter.activity)));
14006                    out.print(' ');
14007                    filter.activity.printComponentShortName(out);
14008                    out.print(" filter ");
14009                    out.println(Integer.toHexString(System.identityHashCode(filter)));
14010        }
14011
14012        @Override
14013        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
14014            return filter.activity;
14015        }
14016
14017        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
14018            PackageParser.Activity activity = (PackageParser.Activity)label;
14019            out.print(prefix); out.print(
14020                    Integer.toHexString(System.identityHashCode(activity)));
14021                    out.print(' ');
14022                    activity.printComponentShortName(out);
14023            if (count > 1) {
14024                out.print(" ("); out.print(count); out.print(" filters)");
14025            }
14026            out.println();
14027        }
14028
14029        // Keys are String (activity class name), values are Activity.
14030        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
14031                = new ArrayMap<ComponentName, PackageParser.Activity>();
14032        private int mFlags;
14033    }
14034
14035    private final class ServiceIntentResolver
14036            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
14037        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
14038                boolean defaultOnly, int userId) {
14039            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
14040            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
14041        }
14042
14043        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
14044                int userId) {
14045            if (!sUserManager.exists(userId)) return null;
14046            mFlags = flags;
14047            return super.queryIntent(intent, resolvedType,
14048                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
14049                    userId);
14050        }
14051
14052        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
14053                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
14054            if (!sUserManager.exists(userId)) return null;
14055            if (packageServices == null) {
14056                return null;
14057            }
14058            mFlags = flags;
14059            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
14060            final int N = packageServices.size();
14061            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
14062                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
14063
14064            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
14065            for (int i = 0; i < N; ++i) {
14066                intentFilters = packageServices.get(i).intents;
14067                if (intentFilters != null && intentFilters.size() > 0) {
14068                    PackageParser.ServiceIntentInfo[] array =
14069                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
14070                    intentFilters.toArray(array);
14071                    listCut.add(array);
14072                }
14073            }
14074            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
14075        }
14076
14077        public final void addService(PackageParser.Service s) {
14078            mServices.put(s.getComponentName(), s);
14079            if (DEBUG_SHOW_INFO) {
14080                Log.v(TAG, "  "
14081                        + (s.info.nonLocalizedLabel != null
14082                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
14083                Log.v(TAG, "    Class=" + s.info.name);
14084            }
14085            final int NI = s.intents.size();
14086            int j;
14087            for (j=0; j<NI; j++) {
14088                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
14089                if (DEBUG_SHOW_INFO) {
14090                    Log.v(TAG, "    IntentFilter:");
14091                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14092                }
14093                if (!intent.debugCheck()) {
14094                    Log.w(TAG, "==> For Service " + s.info.name);
14095                }
14096                addFilter(intent);
14097            }
14098        }
14099
14100        public final void removeService(PackageParser.Service s) {
14101            mServices.remove(s.getComponentName());
14102            if (DEBUG_SHOW_INFO) {
14103                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
14104                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
14105                Log.v(TAG, "    Class=" + s.info.name);
14106            }
14107            final int NI = s.intents.size();
14108            int j;
14109            for (j=0; j<NI; j++) {
14110                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
14111                if (DEBUG_SHOW_INFO) {
14112                    Log.v(TAG, "    IntentFilter:");
14113                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14114                }
14115                removeFilter(intent);
14116            }
14117        }
14118
14119        @Override
14120        protected boolean allowFilterResult(
14121                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
14122            ServiceInfo filterSi = filter.service.info;
14123            for (int i=dest.size()-1; i>=0; i--) {
14124                ServiceInfo destAi = dest.get(i).serviceInfo;
14125                if (destAi.name == filterSi.name
14126                        && destAi.packageName == filterSi.packageName) {
14127                    return false;
14128                }
14129            }
14130            return true;
14131        }
14132
14133        @Override
14134        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
14135            return new PackageParser.ServiceIntentInfo[size];
14136        }
14137
14138        @Override
14139        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
14140            if (!sUserManager.exists(userId)) return true;
14141            PackageParser.Package p = filter.service.owner;
14142            if (p != null) {
14143                PackageSetting ps = (PackageSetting)p.mExtras;
14144                if (ps != null) {
14145                    // System apps are never considered stopped for purposes of
14146                    // filtering, because there may be no way for the user to
14147                    // actually re-launch them.
14148                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
14149                            && ps.getStopped(userId);
14150                }
14151            }
14152            return false;
14153        }
14154
14155        @Override
14156        protected boolean isPackageForFilter(String packageName,
14157                PackageParser.ServiceIntentInfo info) {
14158            return packageName.equals(info.service.owner.packageName);
14159        }
14160
14161        @Override
14162        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
14163                int match, int userId) {
14164            if (!sUserManager.exists(userId)) return null;
14165            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
14166            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
14167                return null;
14168            }
14169            final PackageParser.Service service = info.service;
14170            PackageSetting ps = (PackageSetting) service.owner.mExtras;
14171            if (ps == null) {
14172                return null;
14173            }
14174            final PackageUserState userState = ps.readUserState(userId);
14175            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
14176                    userState, userId);
14177            if (si == null) {
14178                return null;
14179            }
14180            final boolean matchVisibleToInstantApp =
14181                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
14182            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
14183            // throw out filters that aren't visible to ephemeral apps
14184            if (matchVisibleToInstantApp
14185                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
14186                return null;
14187            }
14188            // throw out ephemeral filters if we're not explicitly requesting them
14189            if (!isInstantApp && userState.instantApp) {
14190                return null;
14191            }
14192            // throw out instant app filters if updates are available; will trigger
14193            // instant app resolution
14194            if (userState.instantApp && ps.isUpdateAvailable()) {
14195                return null;
14196            }
14197            final ResolveInfo res = new ResolveInfo();
14198            res.serviceInfo = si;
14199            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
14200                res.filter = filter;
14201            }
14202            res.priority = info.getPriority();
14203            res.preferredOrder = service.owner.mPreferredOrder;
14204            res.match = match;
14205            res.isDefault = info.hasDefault;
14206            res.labelRes = info.labelRes;
14207            res.nonLocalizedLabel = info.nonLocalizedLabel;
14208            res.icon = info.icon;
14209            res.system = res.serviceInfo.applicationInfo.isSystemApp();
14210            return res;
14211        }
14212
14213        @Override
14214        protected void sortResults(List<ResolveInfo> results) {
14215            Collections.sort(results, mResolvePrioritySorter);
14216        }
14217
14218        @Override
14219        protected void dumpFilter(PrintWriter out, String prefix,
14220                PackageParser.ServiceIntentInfo filter) {
14221            out.print(prefix); out.print(
14222                    Integer.toHexString(System.identityHashCode(filter.service)));
14223                    out.print(' ');
14224                    filter.service.printComponentShortName(out);
14225                    out.print(" filter ");
14226                    out.println(Integer.toHexString(System.identityHashCode(filter)));
14227        }
14228
14229        @Override
14230        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
14231            return filter.service;
14232        }
14233
14234        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
14235            PackageParser.Service service = (PackageParser.Service)label;
14236            out.print(prefix); out.print(
14237                    Integer.toHexString(System.identityHashCode(service)));
14238                    out.print(' ');
14239                    service.printComponentShortName(out);
14240            if (count > 1) {
14241                out.print(" ("); out.print(count); out.print(" filters)");
14242            }
14243            out.println();
14244        }
14245
14246//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
14247//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
14248//            final List<ResolveInfo> retList = Lists.newArrayList();
14249//            while (i.hasNext()) {
14250//                final ResolveInfo resolveInfo = (ResolveInfo) i;
14251//                if (isEnabledLP(resolveInfo.serviceInfo)) {
14252//                    retList.add(resolveInfo);
14253//                }
14254//            }
14255//            return retList;
14256//        }
14257
14258        // Keys are String (activity class name), values are Activity.
14259        private final ArrayMap<ComponentName, PackageParser.Service> mServices
14260                = new ArrayMap<ComponentName, PackageParser.Service>();
14261        private int mFlags;
14262    }
14263
14264    private final class ProviderIntentResolver
14265            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
14266        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
14267                boolean defaultOnly, int userId) {
14268            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
14269            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
14270        }
14271
14272        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
14273                int userId) {
14274            if (!sUserManager.exists(userId))
14275                return null;
14276            mFlags = flags;
14277            return super.queryIntent(intent, resolvedType,
14278                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
14279                    userId);
14280        }
14281
14282        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
14283                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
14284            if (!sUserManager.exists(userId))
14285                return null;
14286            if (packageProviders == null) {
14287                return null;
14288            }
14289            mFlags = flags;
14290            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
14291            final int N = packageProviders.size();
14292            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
14293                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
14294
14295            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
14296            for (int i = 0; i < N; ++i) {
14297                intentFilters = packageProviders.get(i).intents;
14298                if (intentFilters != null && intentFilters.size() > 0) {
14299                    PackageParser.ProviderIntentInfo[] array =
14300                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
14301                    intentFilters.toArray(array);
14302                    listCut.add(array);
14303                }
14304            }
14305            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
14306        }
14307
14308        public final void addProvider(PackageParser.Provider p) {
14309            if (mProviders.containsKey(p.getComponentName())) {
14310                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
14311                return;
14312            }
14313
14314            mProviders.put(p.getComponentName(), p);
14315            if (DEBUG_SHOW_INFO) {
14316                Log.v(TAG, "  "
14317                        + (p.info.nonLocalizedLabel != null
14318                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
14319                Log.v(TAG, "    Class=" + p.info.name);
14320            }
14321            final int NI = p.intents.size();
14322            int j;
14323            for (j = 0; j < NI; j++) {
14324                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
14325                if (DEBUG_SHOW_INFO) {
14326                    Log.v(TAG, "    IntentFilter:");
14327                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14328                }
14329                if (!intent.debugCheck()) {
14330                    Log.w(TAG, "==> For Provider " + p.info.name);
14331                }
14332                addFilter(intent);
14333            }
14334        }
14335
14336        public final void removeProvider(PackageParser.Provider p) {
14337            mProviders.remove(p.getComponentName());
14338            if (DEBUG_SHOW_INFO) {
14339                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
14340                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
14341                Log.v(TAG, "    Class=" + p.info.name);
14342            }
14343            final int NI = p.intents.size();
14344            int j;
14345            for (j = 0; j < NI; j++) {
14346                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
14347                if (DEBUG_SHOW_INFO) {
14348                    Log.v(TAG, "    IntentFilter:");
14349                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14350                }
14351                removeFilter(intent);
14352            }
14353        }
14354
14355        @Override
14356        protected boolean allowFilterResult(
14357                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
14358            ProviderInfo filterPi = filter.provider.info;
14359            for (int i = dest.size() - 1; i >= 0; i--) {
14360                ProviderInfo destPi = dest.get(i).providerInfo;
14361                if (destPi.name == filterPi.name
14362                        && destPi.packageName == filterPi.packageName) {
14363                    return false;
14364                }
14365            }
14366            return true;
14367        }
14368
14369        @Override
14370        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
14371            return new PackageParser.ProviderIntentInfo[size];
14372        }
14373
14374        @Override
14375        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
14376            if (!sUserManager.exists(userId))
14377                return true;
14378            PackageParser.Package p = filter.provider.owner;
14379            if (p != null) {
14380                PackageSetting ps = (PackageSetting) p.mExtras;
14381                if (ps != null) {
14382                    // System apps are never considered stopped for purposes of
14383                    // filtering, because there may be no way for the user to
14384                    // actually re-launch them.
14385                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
14386                            && ps.getStopped(userId);
14387                }
14388            }
14389            return false;
14390        }
14391
14392        @Override
14393        protected boolean isPackageForFilter(String packageName,
14394                PackageParser.ProviderIntentInfo info) {
14395            return packageName.equals(info.provider.owner.packageName);
14396        }
14397
14398        @Override
14399        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
14400                int match, int userId) {
14401            if (!sUserManager.exists(userId))
14402                return null;
14403            final PackageParser.ProviderIntentInfo info = filter;
14404            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
14405                return null;
14406            }
14407            final PackageParser.Provider provider = info.provider;
14408            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
14409            if (ps == null) {
14410                return null;
14411            }
14412            final PackageUserState userState = ps.readUserState(userId);
14413            final boolean matchVisibleToInstantApp =
14414                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
14415            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
14416            // throw out filters that aren't visible to instant applications
14417            if (matchVisibleToInstantApp
14418                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
14419                return null;
14420            }
14421            // throw out instant application filters if we're not explicitly requesting them
14422            if (!isInstantApp && userState.instantApp) {
14423                return null;
14424            }
14425            // throw out instant application filters if updates are available; will trigger
14426            // instant application resolution
14427            if (userState.instantApp && ps.isUpdateAvailable()) {
14428                return null;
14429            }
14430            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
14431                    userState, userId);
14432            if (pi == null) {
14433                return null;
14434            }
14435            final ResolveInfo res = new ResolveInfo();
14436            res.providerInfo = pi;
14437            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
14438                res.filter = filter;
14439            }
14440            res.priority = info.getPriority();
14441            res.preferredOrder = provider.owner.mPreferredOrder;
14442            res.match = match;
14443            res.isDefault = info.hasDefault;
14444            res.labelRes = info.labelRes;
14445            res.nonLocalizedLabel = info.nonLocalizedLabel;
14446            res.icon = info.icon;
14447            res.system = res.providerInfo.applicationInfo.isSystemApp();
14448            return res;
14449        }
14450
14451        @Override
14452        protected void sortResults(List<ResolveInfo> results) {
14453            Collections.sort(results, mResolvePrioritySorter);
14454        }
14455
14456        @Override
14457        protected void dumpFilter(PrintWriter out, String prefix,
14458                PackageParser.ProviderIntentInfo filter) {
14459            out.print(prefix);
14460            out.print(
14461                    Integer.toHexString(System.identityHashCode(filter.provider)));
14462            out.print(' ');
14463            filter.provider.printComponentShortName(out);
14464            out.print(" filter ");
14465            out.println(Integer.toHexString(System.identityHashCode(filter)));
14466        }
14467
14468        @Override
14469        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
14470            return filter.provider;
14471        }
14472
14473        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
14474            PackageParser.Provider provider = (PackageParser.Provider)label;
14475            out.print(prefix); out.print(
14476                    Integer.toHexString(System.identityHashCode(provider)));
14477                    out.print(' ');
14478                    provider.printComponentShortName(out);
14479            if (count > 1) {
14480                out.print(" ("); out.print(count); out.print(" filters)");
14481            }
14482            out.println();
14483        }
14484
14485        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
14486                = new ArrayMap<ComponentName, PackageParser.Provider>();
14487        private int mFlags;
14488    }
14489
14490    static final class EphemeralIntentResolver
14491            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
14492        /**
14493         * The result that has the highest defined order. Ordering applies on a
14494         * per-package basis. Mapping is from package name to Pair of order and
14495         * EphemeralResolveInfo.
14496         * <p>
14497         * NOTE: This is implemented as a field variable for convenience and efficiency.
14498         * By having a field variable, we're able to track filter ordering as soon as
14499         * a non-zero order is defined. Otherwise, multiple loops across the result set
14500         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
14501         * this needs to be contained entirely within {@link #filterResults}.
14502         */
14503        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
14504
14505        @Override
14506        protected AuxiliaryResolveInfo[] newArray(int size) {
14507            return new AuxiliaryResolveInfo[size];
14508        }
14509
14510        @Override
14511        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
14512            return true;
14513        }
14514
14515        @Override
14516        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
14517                int userId) {
14518            if (!sUserManager.exists(userId)) {
14519                return null;
14520            }
14521            final String packageName = responseObj.resolveInfo.getPackageName();
14522            final Integer order = responseObj.getOrder();
14523            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
14524                    mOrderResult.get(packageName);
14525            // ordering is enabled and this item's order isn't high enough
14526            if (lastOrderResult != null && lastOrderResult.first >= order) {
14527                return null;
14528            }
14529            final InstantAppResolveInfo res = responseObj.resolveInfo;
14530            if (order > 0) {
14531                // non-zero order, enable ordering
14532                mOrderResult.put(packageName, new Pair<>(order, res));
14533            }
14534            return responseObj;
14535        }
14536
14537        @Override
14538        protected void filterResults(List<AuxiliaryResolveInfo> results) {
14539            // only do work if ordering is enabled [most of the time it won't be]
14540            if (mOrderResult.size() == 0) {
14541                return;
14542            }
14543            int resultSize = results.size();
14544            for (int i = 0; i < resultSize; i++) {
14545                final InstantAppResolveInfo info = results.get(i).resolveInfo;
14546                final String packageName = info.getPackageName();
14547                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
14548                if (savedInfo == null) {
14549                    // package doesn't having ordering
14550                    continue;
14551                }
14552                if (savedInfo.second == info) {
14553                    // circled back to the highest ordered item; remove from order list
14554                    mOrderResult.remove(packageName);
14555                    if (mOrderResult.size() == 0) {
14556                        // no more ordered items
14557                        break;
14558                    }
14559                    continue;
14560                }
14561                // item has a worse order, remove it from the result list
14562                results.remove(i);
14563                resultSize--;
14564                i--;
14565            }
14566        }
14567    }
14568
14569    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
14570            new Comparator<ResolveInfo>() {
14571        public int compare(ResolveInfo r1, ResolveInfo r2) {
14572            int v1 = r1.priority;
14573            int v2 = r2.priority;
14574            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
14575            if (v1 != v2) {
14576                return (v1 > v2) ? -1 : 1;
14577            }
14578            v1 = r1.preferredOrder;
14579            v2 = r2.preferredOrder;
14580            if (v1 != v2) {
14581                return (v1 > v2) ? -1 : 1;
14582            }
14583            if (r1.isDefault != r2.isDefault) {
14584                return r1.isDefault ? -1 : 1;
14585            }
14586            v1 = r1.match;
14587            v2 = r2.match;
14588            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
14589            if (v1 != v2) {
14590                return (v1 > v2) ? -1 : 1;
14591            }
14592            if (r1.system != r2.system) {
14593                return r1.system ? -1 : 1;
14594            }
14595            if (r1.activityInfo != null) {
14596                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
14597            }
14598            if (r1.serviceInfo != null) {
14599                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
14600            }
14601            if (r1.providerInfo != null) {
14602                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
14603            }
14604            return 0;
14605        }
14606    };
14607
14608    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
14609            new Comparator<ProviderInfo>() {
14610        public int compare(ProviderInfo p1, ProviderInfo p2) {
14611            final int v1 = p1.initOrder;
14612            final int v2 = p2.initOrder;
14613            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
14614        }
14615    };
14616
14617    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
14618            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
14619            final int[] userIds) {
14620        mHandler.post(new Runnable() {
14621            @Override
14622            public void run() {
14623                try {
14624                    final IActivityManager am = ActivityManager.getService();
14625                    if (am == null) return;
14626                    final int[] resolvedUserIds;
14627                    if (userIds == null) {
14628                        resolvedUserIds = am.getRunningUserIds();
14629                    } else {
14630                        resolvedUserIds = userIds;
14631                    }
14632                    for (int id : resolvedUserIds) {
14633                        final Intent intent = new Intent(action,
14634                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
14635                        if (extras != null) {
14636                            intent.putExtras(extras);
14637                        }
14638                        if (targetPkg != null) {
14639                            intent.setPackage(targetPkg);
14640                        }
14641                        // Modify the UID when posting to other users
14642                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
14643                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
14644                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
14645                            intent.putExtra(Intent.EXTRA_UID, uid);
14646                        }
14647                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
14648                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
14649                        if (DEBUG_BROADCASTS) {
14650                            RuntimeException here = new RuntimeException("here");
14651                            here.fillInStackTrace();
14652                            Slog.d(TAG, "Sending to user " + id + ": "
14653                                    + intent.toShortString(false, true, false, false)
14654                                    + " " + intent.getExtras(), here);
14655                        }
14656                        am.broadcastIntent(null, intent, null, finishedReceiver,
14657                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
14658                                null, finishedReceiver != null, false, id);
14659                    }
14660                } catch (RemoteException ex) {
14661                }
14662            }
14663        });
14664    }
14665
14666    /**
14667     * Check if the external storage media is available. This is true if there
14668     * is a mounted external storage medium or if the external storage is
14669     * emulated.
14670     */
14671    private boolean isExternalMediaAvailable() {
14672        return mMediaMounted || Environment.isExternalStorageEmulated();
14673    }
14674
14675    @Override
14676    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
14677        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14678            return null;
14679        }
14680        // writer
14681        synchronized (mPackages) {
14682            if (!isExternalMediaAvailable()) {
14683                // If the external storage is no longer mounted at this point,
14684                // the caller may not have been able to delete all of this
14685                // packages files and can not delete any more.  Bail.
14686                return null;
14687            }
14688            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14689            if (lastPackage != null) {
14690                pkgs.remove(lastPackage);
14691            }
14692            if (pkgs.size() > 0) {
14693                return pkgs.get(0);
14694            }
14695        }
14696        return null;
14697    }
14698
14699    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14700        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14701                userId, andCode ? 1 : 0, packageName);
14702        if (mSystemReady) {
14703            msg.sendToTarget();
14704        } else {
14705            if (mPostSystemReadyMessages == null) {
14706                mPostSystemReadyMessages = new ArrayList<>();
14707            }
14708            mPostSystemReadyMessages.add(msg);
14709        }
14710    }
14711
14712    void startCleaningPackages() {
14713        // reader
14714        if (!isExternalMediaAvailable()) {
14715            return;
14716        }
14717        synchronized (mPackages) {
14718            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14719                return;
14720            }
14721        }
14722        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14723        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14724        IActivityManager am = ActivityManager.getService();
14725        if (am != null) {
14726            int dcsUid = -1;
14727            synchronized (mPackages) {
14728                if (!mDefaultContainerWhitelisted) {
14729                    mDefaultContainerWhitelisted = true;
14730                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14731                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14732                }
14733            }
14734            try {
14735                if (dcsUid > 0) {
14736                    am.backgroundWhitelistUid(dcsUid);
14737                }
14738                am.startService(null, intent, null, false, mContext.getOpPackageName(),
14739                        UserHandle.USER_SYSTEM);
14740            } catch (RemoteException e) {
14741            }
14742        }
14743    }
14744
14745    @Override
14746    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14747            int installFlags, String installerPackageName, int userId) {
14748        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14749
14750        final int callingUid = Binder.getCallingUid();
14751        enforceCrossUserPermission(callingUid, userId,
14752                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14753
14754        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14755            try {
14756                if (observer != null) {
14757                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14758                }
14759            } catch (RemoteException re) {
14760            }
14761            return;
14762        }
14763
14764        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14765            installFlags |= PackageManager.INSTALL_FROM_ADB;
14766
14767        } else {
14768            // Caller holds INSTALL_PACKAGES permission, so we're less strict
14769            // about installerPackageName.
14770
14771            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14772            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14773        }
14774
14775        UserHandle user;
14776        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14777            user = UserHandle.ALL;
14778        } else {
14779            user = new UserHandle(userId);
14780        }
14781
14782        // Only system components can circumvent runtime permissions when installing.
14783        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14784                && mContext.checkCallingOrSelfPermission(Manifest.permission
14785                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14786            throw new SecurityException("You need the "
14787                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14788                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14789        }
14790
14791        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14792                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14793            throw new IllegalArgumentException(
14794                    "New installs into ASEC containers no longer supported");
14795        }
14796
14797        final File originFile = new File(originPath);
14798        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14799
14800        final Message msg = mHandler.obtainMessage(INIT_COPY);
14801        final VerificationInfo verificationInfo = new VerificationInfo(
14802                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14803        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14804                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14805                null /*packageAbiOverride*/, null /*grantedPermissions*/,
14806                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14807        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14808        msg.obj = params;
14809
14810        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14811                System.identityHashCode(msg.obj));
14812        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14813                System.identityHashCode(msg.obj));
14814
14815        mHandler.sendMessage(msg);
14816    }
14817
14818
14819    /**
14820     * Ensure that the install reason matches what we know about the package installer (e.g. whether
14821     * it is acting on behalf on an enterprise or the user).
14822     *
14823     * Note that the ordering of the conditionals in this method is important. The checks we perform
14824     * are as follows, in this order:
14825     *
14826     * 1) If the install is being performed by a system app, we can trust the app to have set the
14827     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14828     *    what it is.
14829     * 2) If the install is being performed by a device or profile owner app, the install reason
14830     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14831     *    set the install reason correctly. If the app targets an older SDK version where install
14832     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14833     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14834     * 3) In all other cases, the install is being performed by a regular app that is neither part
14835     *    of the system nor a device or profile owner. We have no reason to believe that this app is
14836     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14837     *    set to enterprise policy and if so, change it to unknown instead.
14838     */
14839    private int fixUpInstallReason(String installerPackageName, int installerUid,
14840            int installReason) {
14841        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14842                == PERMISSION_GRANTED) {
14843            // If the install is being performed by a system app, we trust that app to have set the
14844            // install reason correctly.
14845            return installReason;
14846        }
14847
14848        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14849            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14850        if (dpm != null) {
14851            ComponentName owner = null;
14852            try {
14853                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14854                if (owner == null) {
14855                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14856                }
14857            } catch (RemoteException e) {
14858            }
14859            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14860                // If the install is being performed by a device or profile owner, the install
14861                // reason should be enterprise policy.
14862                return PackageManager.INSTALL_REASON_POLICY;
14863            }
14864        }
14865
14866        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14867            // If the install is being performed by a regular app (i.e. neither system app nor
14868            // device or profile owner), we have no reason to believe that the app is acting on
14869            // behalf of an enterprise. If the app set the install reason to enterprise policy,
14870            // change it to unknown instead.
14871            return PackageManager.INSTALL_REASON_UNKNOWN;
14872        }
14873
14874        // If the install is being performed by a regular app and the install reason was set to any
14875        // value but enterprise policy, leave the install reason unchanged.
14876        return installReason;
14877    }
14878
14879    void installStage(String packageName, File stagedDir, String stagedCid,
14880            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14881            String installerPackageName, int installerUid, UserHandle user,
14882            Certificate[][] certificates) {
14883        if (DEBUG_EPHEMERAL) {
14884            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14885                Slog.d(TAG, "Ephemeral install of " + packageName);
14886            }
14887        }
14888        final VerificationInfo verificationInfo = new VerificationInfo(
14889                sessionParams.originatingUri, sessionParams.referrerUri,
14890                sessionParams.originatingUid, installerUid);
14891
14892        final OriginInfo origin;
14893        if (stagedDir != null) {
14894            origin = OriginInfo.fromStagedFile(stagedDir);
14895        } else {
14896            origin = OriginInfo.fromStagedContainer(stagedCid);
14897        }
14898
14899        final Message msg = mHandler.obtainMessage(INIT_COPY);
14900        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14901                sessionParams.installReason);
14902        final InstallParams params = new InstallParams(origin, null, observer,
14903                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14904                verificationInfo, user, sessionParams.abiOverride,
14905                sessionParams.grantedRuntimePermissions, certificates, installReason);
14906        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14907        msg.obj = params;
14908
14909        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14910                System.identityHashCode(msg.obj));
14911        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14912                System.identityHashCode(msg.obj));
14913
14914        mHandler.sendMessage(msg);
14915    }
14916
14917    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14918            int userId) {
14919        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14920        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
14921                false /*startReceiver*/, pkgSetting.appId, userId);
14922
14923        // Send a session commit broadcast
14924        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14925        info.installReason = pkgSetting.getInstallReason(userId);
14926        info.appPackageName = packageName;
14927        sendSessionCommitBroadcast(info, userId);
14928    }
14929
14930    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
14931            boolean includeStopped, int appId, int... userIds) {
14932        if (ArrayUtils.isEmpty(userIds)) {
14933            return;
14934        }
14935        Bundle extras = new Bundle(1);
14936        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14937        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14938
14939        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14940                packageName, extras, 0, null, null, userIds);
14941        if (sendBootCompleted) {
14942            mHandler.post(() -> {
14943                        for (int userId : userIds) {
14944                            sendBootCompletedBroadcastToSystemApp(
14945                                    packageName, includeStopped, userId);
14946                        }
14947                    }
14948            );
14949        }
14950    }
14951
14952    /**
14953     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14954     * automatically without needing an explicit launch.
14955     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14956     */
14957    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
14958            int userId) {
14959        // If user is not running, the app didn't miss any broadcast
14960        if (!mUserManagerInternal.isUserRunning(userId)) {
14961            return;
14962        }
14963        final IActivityManager am = ActivityManager.getService();
14964        try {
14965            // Deliver LOCKED_BOOT_COMPLETED first
14966            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14967                    .setPackage(packageName);
14968            if (includeStopped) {
14969                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14970            }
14971            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14972            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14973                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14974
14975            // Deliver BOOT_COMPLETED only if user is unlocked
14976            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14977                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14978                if (includeStopped) {
14979                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14980                }
14981                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14982                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14983            }
14984        } catch (RemoteException e) {
14985            throw e.rethrowFromSystemServer();
14986        }
14987    }
14988
14989    @Override
14990    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14991            int userId) {
14992        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14993        PackageSetting pkgSetting;
14994        final int callingUid = Binder.getCallingUid();
14995        enforceCrossUserPermission(callingUid, userId,
14996                true /* requireFullPermission */, true /* checkShell */,
14997                "setApplicationHiddenSetting for user " + userId);
14998
14999        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
15000            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
15001            return false;
15002        }
15003
15004        long callingId = Binder.clearCallingIdentity();
15005        try {
15006            boolean sendAdded = false;
15007            boolean sendRemoved = false;
15008            // writer
15009            synchronized (mPackages) {
15010                pkgSetting = mSettings.mPackages.get(packageName);
15011                if (pkgSetting == null) {
15012                    return false;
15013                }
15014                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
15015                    return false;
15016                }
15017                // Do not allow "android" is being disabled
15018                if ("android".equals(packageName)) {
15019                    Slog.w(TAG, "Cannot hide package: android");
15020                    return false;
15021                }
15022                // Cannot hide static shared libs as they are considered
15023                // a part of the using app (emulating static linking). Also
15024                // static libs are installed always on internal storage.
15025                PackageParser.Package pkg = mPackages.get(packageName);
15026                if (pkg != null && pkg.staticSharedLibName != null) {
15027                    Slog.w(TAG, "Cannot hide package: " + packageName
15028                            + " providing static shared library: "
15029                            + pkg.staticSharedLibName);
15030                    return false;
15031                }
15032                // Only allow protected packages to hide themselves.
15033                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
15034                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
15035                    Slog.w(TAG, "Not hiding protected package: " + packageName);
15036                    return false;
15037                }
15038
15039                if (pkgSetting.getHidden(userId) != hidden) {
15040                    pkgSetting.setHidden(hidden, userId);
15041                    mSettings.writePackageRestrictionsLPr(userId);
15042                    if (hidden) {
15043                        sendRemoved = true;
15044                    } else {
15045                        sendAdded = true;
15046                    }
15047                }
15048            }
15049            if (sendAdded) {
15050                sendPackageAddedForUser(packageName, pkgSetting, userId);
15051                return true;
15052            }
15053            if (sendRemoved) {
15054                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
15055                        "hiding pkg");
15056                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
15057                return true;
15058            }
15059        } finally {
15060            Binder.restoreCallingIdentity(callingId);
15061        }
15062        return false;
15063    }
15064
15065    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
15066            int userId) {
15067        final PackageRemovedInfo info = new PackageRemovedInfo(this);
15068        info.removedPackage = packageName;
15069        info.installerPackageName = pkgSetting.installerPackageName;
15070        info.removedUsers = new int[] {userId};
15071        info.broadcastUsers = new int[] {userId};
15072        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
15073        info.sendPackageRemovedBroadcasts(true /*killApp*/);
15074    }
15075
15076    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
15077        if (pkgList.length > 0) {
15078            Bundle extras = new Bundle(1);
15079            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15080
15081            sendPackageBroadcast(
15082                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
15083                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
15084                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
15085                    new int[] {userId});
15086        }
15087    }
15088
15089    /**
15090     * Returns true if application is not found or there was an error. Otherwise it returns
15091     * the hidden state of the package for the given user.
15092     */
15093    @Override
15094    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
15095        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
15096        final int callingUid = Binder.getCallingUid();
15097        enforceCrossUserPermission(callingUid, userId,
15098                true /* requireFullPermission */, false /* checkShell */,
15099                "getApplicationHidden for user " + userId);
15100        PackageSetting ps;
15101        long callingId = Binder.clearCallingIdentity();
15102        try {
15103            // writer
15104            synchronized (mPackages) {
15105                ps = mSettings.mPackages.get(packageName);
15106                if (ps == null) {
15107                    return true;
15108                }
15109                if (filterAppAccessLPr(ps, callingUid, userId)) {
15110                    return true;
15111                }
15112                return ps.getHidden(userId);
15113            }
15114        } finally {
15115            Binder.restoreCallingIdentity(callingId);
15116        }
15117    }
15118
15119    /**
15120     * @hide
15121     */
15122    @Override
15123    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
15124            int installReason) {
15125        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
15126                null);
15127        PackageSetting pkgSetting;
15128        final int callingUid = Binder.getCallingUid();
15129        enforceCrossUserPermission(callingUid, userId,
15130                true /* requireFullPermission */, true /* checkShell */,
15131                "installExistingPackage for user " + userId);
15132        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
15133            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
15134        }
15135
15136        long callingId = Binder.clearCallingIdentity();
15137        try {
15138            boolean installed = false;
15139            final boolean instantApp =
15140                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15141            final boolean fullApp =
15142                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
15143
15144            // writer
15145            synchronized (mPackages) {
15146                pkgSetting = mSettings.mPackages.get(packageName);
15147                if (pkgSetting == null) {
15148                    return PackageManager.INSTALL_FAILED_INVALID_URI;
15149                }
15150                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
15151                    // only allow the existing package to be used if it's installed as a full
15152                    // application for at least one user
15153                    boolean installAllowed = false;
15154                    for (int checkUserId : sUserManager.getUserIds()) {
15155                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
15156                        if (installAllowed) {
15157                            break;
15158                        }
15159                    }
15160                    if (!installAllowed) {
15161                        return PackageManager.INSTALL_FAILED_INVALID_URI;
15162                    }
15163                }
15164                if (!pkgSetting.getInstalled(userId)) {
15165                    pkgSetting.setInstalled(true, userId);
15166                    pkgSetting.setHidden(false, userId);
15167                    pkgSetting.setInstallReason(installReason, userId);
15168                    mSettings.writePackageRestrictionsLPr(userId);
15169                    mSettings.writeKernelMappingLPr(pkgSetting);
15170                    installed = true;
15171                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
15172                    // upgrade app from instant to full; we don't allow app downgrade
15173                    installed = true;
15174                }
15175                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
15176            }
15177
15178            if (installed) {
15179                if (pkgSetting.pkg != null) {
15180                    synchronized (mInstallLock) {
15181                        // We don't need to freeze for a brand new install
15182                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
15183                    }
15184                }
15185                sendPackageAddedForUser(packageName, pkgSetting, userId);
15186                synchronized (mPackages) {
15187                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
15188                }
15189            }
15190        } finally {
15191            Binder.restoreCallingIdentity(callingId);
15192        }
15193
15194        return PackageManager.INSTALL_SUCCEEDED;
15195    }
15196
15197    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
15198            boolean instantApp, boolean fullApp) {
15199        // no state specified; do nothing
15200        if (!instantApp && !fullApp) {
15201            return;
15202        }
15203        if (userId != UserHandle.USER_ALL) {
15204            if (instantApp && !pkgSetting.getInstantApp(userId)) {
15205                pkgSetting.setInstantApp(true /*instantApp*/, userId);
15206            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
15207                pkgSetting.setInstantApp(false /*instantApp*/, userId);
15208            }
15209        } else {
15210            for (int currentUserId : sUserManager.getUserIds()) {
15211                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
15212                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
15213                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
15214                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
15215                }
15216            }
15217        }
15218    }
15219
15220    boolean isUserRestricted(int userId, String restrictionKey) {
15221        Bundle restrictions = sUserManager.getUserRestrictions(userId);
15222        if (restrictions.getBoolean(restrictionKey, false)) {
15223            Log.w(TAG, "User is restricted: " + restrictionKey);
15224            return true;
15225        }
15226        return false;
15227    }
15228
15229    @Override
15230    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
15231            int userId) {
15232        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
15233        final int callingUid = Binder.getCallingUid();
15234        enforceCrossUserPermission(callingUid, userId,
15235                true /* requireFullPermission */, true /* checkShell */,
15236                "setPackagesSuspended for user " + userId);
15237
15238        if (ArrayUtils.isEmpty(packageNames)) {
15239            return packageNames;
15240        }
15241
15242        // List of package names for whom the suspended state has changed.
15243        List<String> changedPackages = new ArrayList<>(packageNames.length);
15244        // List of package names for whom the suspended state is not set as requested in this
15245        // method.
15246        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
15247        long callingId = Binder.clearCallingIdentity();
15248        try {
15249            for (int i = 0; i < packageNames.length; i++) {
15250                String packageName = packageNames[i];
15251                boolean changed = false;
15252                final int appId;
15253                synchronized (mPackages) {
15254                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
15255                    if (pkgSetting == null
15256                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
15257                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
15258                                + "\". Skipping suspending/un-suspending.");
15259                        unactionedPackages.add(packageName);
15260                        continue;
15261                    }
15262                    appId = pkgSetting.appId;
15263                    if (pkgSetting.getSuspended(userId) != suspended) {
15264                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
15265                            unactionedPackages.add(packageName);
15266                            continue;
15267                        }
15268                        pkgSetting.setSuspended(suspended, userId);
15269                        mSettings.writePackageRestrictionsLPr(userId);
15270                        changed = true;
15271                        changedPackages.add(packageName);
15272                    }
15273                }
15274
15275                if (changed && suspended) {
15276                    killApplication(packageName, UserHandle.getUid(userId, appId),
15277                            "suspending package");
15278                }
15279            }
15280        } finally {
15281            Binder.restoreCallingIdentity(callingId);
15282        }
15283
15284        if (!changedPackages.isEmpty()) {
15285            sendPackagesSuspendedForUser(changedPackages.toArray(
15286                    new String[changedPackages.size()]), userId, suspended);
15287        }
15288
15289        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
15290    }
15291
15292    @Override
15293    public boolean isPackageSuspendedForUser(String packageName, int userId) {
15294        final int callingUid = Binder.getCallingUid();
15295        enforceCrossUserPermission(callingUid, userId,
15296                true /* requireFullPermission */, false /* checkShell */,
15297                "isPackageSuspendedForUser for user " + userId);
15298        synchronized (mPackages) {
15299            final PackageSetting ps = mSettings.mPackages.get(packageName);
15300            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
15301                throw new IllegalArgumentException("Unknown target package: " + packageName);
15302            }
15303            return ps.getSuspended(userId);
15304        }
15305    }
15306
15307    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
15308        if (isPackageDeviceAdmin(packageName, userId)) {
15309            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15310                    + "\": has an active device admin");
15311            return false;
15312        }
15313
15314        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
15315        if (packageName.equals(activeLauncherPackageName)) {
15316            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15317                    + "\": contains the active launcher");
15318            return false;
15319        }
15320
15321        if (packageName.equals(mRequiredInstallerPackage)) {
15322            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15323                    + "\": required for package installation");
15324            return false;
15325        }
15326
15327        if (packageName.equals(mRequiredUninstallerPackage)) {
15328            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15329                    + "\": required for package uninstallation");
15330            return false;
15331        }
15332
15333        if (packageName.equals(mRequiredVerifierPackage)) {
15334            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15335                    + "\": required for package verification");
15336            return false;
15337        }
15338
15339        if (packageName.equals(getDefaultDialerPackageName(userId))) {
15340            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15341                    + "\": is the default dialer");
15342            return false;
15343        }
15344
15345        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
15346            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15347                    + "\": protected package");
15348            return false;
15349        }
15350
15351        // Cannot suspend static shared libs as they are considered
15352        // a part of the using app (emulating static linking). Also
15353        // static libs are installed always on internal storage.
15354        PackageParser.Package pkg = mPackages.get(packageName);
15355        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
15356            Slog.w(TAG, "Cannot suspend package: " + packageName
15357                    + " providing static shared library: "
15358                    + pkg.staticSharedLibName);
15359            return false;
15360        }
15361
15362        return true;
15363    }
15364
15365    private String getActiveLauncherPackageName(int userId) {
15366        Intent intent = new Intent(Intent.ACTION_MAIN);
15367        intent.addCategory(Intent.CATEGORY_HOME);
15368        ResolveInfo resolveInfo = resolveIntent(
15369                intent,
15370                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
15371                PackageManager.MATCH_DEFAULT_ONLY,
15372                userId);
15373
15374        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
15375    }
15376
15377    private String getDefaultDialerPackageName(int userId) {
15378        synchronized (mPackages) {
15379            return mSettings.getDefaultDialerPackageNameLPw(userId);
15380        }
15381    }
15382
15383    @Override
15384    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
15385        mContext.enforceCallingOrSelfPermission(
15386                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15387                "Only package verification agents can verify applications");
15388
15389        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
15390        final PackageVerificationResponse response = new PackageVerificationResponse(
15391                verificationCode, Binder.getCallingUid());
15392        msg.arg1 = id;
15393        msg.obj = response;
15394        mHandler.sendMessage(msg);
15395    }
15396
15397    @Override
15398    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
15399            long millisecondsToDelay) {
15400        mContext.enforceCallingOrSelfPermission(
15401                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15402                "Only package verification agents can extend verification timeouts");
15403
15404        final PackageVerificationState state = mPendingVerification.get(id);
15405        final PackageVerificationResponse response = new PackageVerificationResponse(
15406                verificationCodeAtTimeout, Binder.getCallingUid());
15407
15408        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
15409            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
15410        }
15411        if (millisecondsToDelay < 0) {
15412            millisecondsToDelay = 0;
15413        }
15414        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
15415                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
15416            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
15417        }
15418
15419        if ((state != null) && !state.timeoutExtended()) {
15420            state.extendTimeout();
15421
15422            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
15423            msg.arg1 = id;
15424            msg.obj = response;
15425            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
15426        }
15427    }
15428
15429    private void broadcastPackageVerified(int verificationId, Uri packageUri,
15430            int verificationCode, UserHandle user) {
15431        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
15432        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
15433        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15434        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15435        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
15436
15437        mContext.sendBroadcastAsUser(intent, user,
15438                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
15439    }
15440
15441    private ComponentName matchComponentForVerifier(String packageName,
15442            List<ResolveInfo> receivers) {
15443        ActivityInfo targetReceiver = null;
15444
15445        final int NR = receivers.size();
15446        for (int i = 0; i < NR; i++) {
15447            final ResolveInfo info = receivers.get(i);
15448            if (info.activityInfo == null) {
15449                continue;
15450            }
15451
15452            if (packageName.equals(info.activityInfo.packageName)) {
15453                targetReceiver = info.activityInfo;
15454                break;
15455            }
15456        }
15457
15458        if (targetReceiver == null) {
15459            return null;
15460        }
15461
15462        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
15463    }
15464
15465    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
15466            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
15467        if (pkgInfo.verifiers.length == 0) {
15468            return null;
15469        }
15470
15471        final int N = pkgInfo.verifiers.length;
15472        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
15473        for (int i = 0; i < N; i++) {
15474            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
15475
15476            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
15477                    receivers);
15478            if (comp == null) {
15479                continue;
15480            }
15481
15482            final int verifierUid = getUidForVerifier(verifierInfo);
15483            if (verifierUid == -1) {
15484                continue;
15485            }
15486
15487            if (DEBUG_VERIFY) {
15488                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
15489                        + " with the correct signature");
15490            }
15491            sufficientVerifiers.add(comp);
15492            verificationState.addSufficientVerifier(verifierUid);
15493        }
15494
15495        return sufficientVerifiers;
15496    }
15497
15498    private int getUidForVerifier(VerifierInfo verifierInfo) {
15499        synchronized (mPackages) {
15500            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
15501            if (pkg == null) {
15502                return -1;
15503            } else if (pkg.mSignatures.length != 1) {
15504                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15505                        + " has more than one signature; ignoring");
15506                return -1;
15507            }
15508
15509            /*
15510             * If the public key of the package's signature does not match
15511             * our expected public key, then this is a different package and
15512             * we should skip.
15513             */
15514
15515            final byte[] expectedPublicKey;
15516            try {
15517                final Signature verifierSig = pkg.mSignatures[0];
15518                final PublicKey publicKey = verifierSig.getPublicKey();
15519                expectedPublicKey = publicKey.getEncoded();
15520            } catch (CertificateException e) {
15521                return -1;
15522            }
15523
15524            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
15525
15526            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
15527                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15528                        + " does not have the expected public key; ignoring");
15529                return -1;
15530            }
15531
15532            return pkg.applicationInfo.uid;
15533        }
15534    }
15535
15536    @Override
15537    public void finishPackageInstall(int token, boolean didLaunch) {
15538        enforceSystemOrRoot("Only the system is allowed to finish installs");
15539
15540        if (DEBUG_INSTALL) {
15541            Slog.v(TAG, "BM finishing package install for " + token);
15542        }
15543        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15544
15545        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
15546        mHandler.sendMessage(msg);
15547    }
15548
15549    /**
15550     * Get the verification agent timeout.  Used for both the APK verifier and the
15551     * intent filter verifier.
15552     *
15553     * @return verification timeout in milliseconds
15554     */
15555    private long getVerificationTimeout() {
15556        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
15557                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
15558                DEFAULT_VERIFICATION_TIMEOUT);
15559    }
15560
15561    /**
15562     * Get the default verification agent response code.
15563     *
15564     * @return default verification response code
15565     */
15566    private int getDefaultVerificationResponse(UserHandle user) {
15567        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
15568            return PackageManager.VERIFICATION_REJECT;
15569        }
15570        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15571                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
15572                DEFAULT_VERIFICATION_RESPONSE);
15573    }
15574
15575    /**
15576     * Check whether or not package verification has been enabled.
15577     *
15578     * @return true if verification should be performed
15579     */
15580    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
15581        if (!DEFAULT_VERIFY_ENABLE) {
15582            return false;
15583        }
15584
15585        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
15586
15587        // Check if installing from ADB
15588        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
15589            // Do not run verification in a test harness environment
15590            if (ActivityManager.isRunningInTestHarness()) {
15591                return false;
15592            }
15593            if (ensureVerifyAppsEnabled) {
15594                return true;
15595            }
15596            // Check if the developer does not want package verification for ADB installs
15597            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15598                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
15599                return false;
15600            }
15601        } else {
15602            // only when not installed from ADB, skip verification for instant apps when
15603            // the installer and verifier are the same.
15604            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
15605                if (mInstantAppInstallerActivity != null
15606                        && mInstantAppInstallerActivity.packageName.equals(
15607                                mRequiredVerifierPackage)) {
15608                    try {
15609                        mContext.getSystemService(AppOpsManager.class)
15610                                .checkPackage(installerUid, mRequiredVerifierPackage);
15611                        if (DEBUG_VERIFY) {
15612                            Slog.i(TAG, "disable verification for instant app");
15613                        }
15614                        return false;
15615                    } catch (SecurityException ignore) { }
15616                }
15617            }
15618        }
15619
15620        if (ensureVerifyAppsEnabled) {
15621            return true;
15622        }
15623
15624        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15625                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
15626    }
15627
15628    @Override
15629    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
15630            throws RemoteException {
15631        mContext.enforceCallingOrSelfPermission(
15632                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
15633                "Only intentfilter verification agents can verify applications");
15634
15635        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
15636        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
15637                Binder.getCallingUid(), verificationCode, failedDomains);
15638        msg.arg1 = id;
15639        msg.obj = response;
15640        mHandler.sendMessage(msg);
15641    }
15642
15643    @Override
15644    public int getIntentVerificationStatus(String packageName, int userId) {
15645        final int callingUid = Binder.getCallingUid();
15646        if (UserHandle.getUserId(callingUid) != userId) {
15647            mContext.enforceCallingOrSelfPermission(
15648                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15649                    "getIntentVerificationStatus" + userId);
15650        }
15651        if (getInstantAppPackageName(callingUid) != null) {
15652            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15653        }
15654        synchronized (mPackages) {
15655            final PackageSetting ps = mSettings.mPackages.get(packageName);
15656            if (ps == null
15657                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15658                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15659            }
15660            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
15661        }
15662    }
15663
15664    @Override
15665    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
15666        mContext.enforceCallingOrSelfPermission(
15667                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15668
15669        boolean result = false;
15670        synchronized (mPackages) {
15671            final PackageSetting ps = mSettings.mPackages.get(packageName);
15672            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15673                return false;
15674            }
15675            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
15676        }
15677        if (result) {
15678            scheduleWritePackageRestrictionsLocked(userId);
15679        }
15680        return result;
15681    }
15682
15683    @Override
15684    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
15685            String packageName) {
15686        final int callingUid = Binder.getCallingUid();
15687        if (getInstantAppPackageName(callingUid) != null) {
15688            return ParceledListSlice.emptyList();
15689        }
15690        synchronized (mPackages) {
15691            final PackageSetting ps = mSettings.mPackages.get(packageName);
15692            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15693                return ParceledListSlice.emptyList();
15694            }
15695            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
15696        }
15697    }
15698
15699    @Override
15700    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
15701        if (TextUtils.isEmpty(packageName)) {
15702            return ParceledListSlice.emptyList();
15703        }
15704        final int callingUid = Binder.getCallingUid();
15705        final int callingUserId = UserHandle.getUserId(callingUid);
15706        synchronized (mPackages) {
15707            PackageParser.Package pkg = mPackages.get(packageName);
15708            if (pkg == null || pkg.activities == null) {
15709                return ParceledListSlice.emptyList();
15710            }
15711            if (pkg.mExtras == null) {
15712                return ParceledListSlice.emptyList();
15713            }
15714            final PackageSetting ps = (PackageSetting) pkg.mExtras;
15715            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15716                return ParceledListSlice.emptyList();
15717            }
15718            final int count = pkg.activities.size();
15719            ArrayList<IntentFilter> result = new ArrayList<>();
15720            for (int n=0; n<count; n++) {
15721                PackageParser.Activity activity = pkg.activities.get(n);
15722                if (activity.intents != null && activity.intents.size() > 0) {
15723                    result.addAll(activity.intents);
15724                }
15725            }
15726            return new ParceledListSlice<>(result);
15727        }
15728    }
15729
15730    @Override
15731    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15732        mContext.enforceCallingOrSelfPermission(
15733                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15734        if (UserHandle.getCallingUserId() != userId) {
15735            mContext.enforceCallingOrSelfPermission(
15736                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15737        }
15738
15739        synchronized (mPackages) {
15740            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15741            if (packageName != null) {
15742                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
15743                        packageName, userId);
15744            }
15745            return result;
15746        }
15747    }
15748
15749    @Override
15750    public String getDefaultBrowserPackageName(int userId) {
15751        if (UserHandle.getCallingUserId() != userId) {
15752            mContext.enforceCallingOrSelfPermission(
15753                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15754        }
15755        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15756            return null;
15757        }
15758        synchronized (mPackages) {
15759            return mSettings.getDefaultBrowserPackageNameLPw(userId);
15760        }
15761    }
15762
15763    /**
15764     * Get the "allow unknown sources" setting.
15765     *
15766     * @return the current "allow unknown sources" setting
15767     */
15768    private int getUnknownSourcesSettings() {
15769        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15770                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15771                -1);
15772    }
15773
15774    @Override
15775    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15776        final int callingUid = Binder.getCallingUid();
15777        if (getInstantAppPackageName(callingUid) != null) {
15778            return;
15779        }
15780        // writer
15781        synchronized (mPackages) {
15782            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15783            if (targetPackageSetting == null
15784                    || filterAppAccessLPr(
15785                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15786                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15787            }
15788
15789            PackageSetting installerPackageSetting;
15790            if (installerPackageName != null) {
15791                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15792                if (installerPackageSetting == null) {
15793                    throw new IllegalArgumentException("Unknown installer package: "
15794                            + installerPackageName);
15795                }
15796            } else {
15797                installerPackageSetting = null;
15798            }
15799
15800            Signature[] callerSignature;
15801            Object obj = mSettings.getUserIdLPr(callingUid);
15802            if (obj != null) {
15803                if (obj instanceof SharedUserSetting) {
15804                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15805                } else if (obj instanceof PackageSetting) {
15806                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15807                } else {
15808                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15809                }
15810            } else {
15811                throw new SecurityException("Unknown calling UID: " + callingUid);
15812            }
15813
15814            // Verify: can't set installerPackageName to a package that is
15815            // not signed with the same cert as the caller.
15816            if (installerPackageSetting != null) {
15817                if (compareSignatures(callerSignature,
15818                        installerPackageSetting.signatures.mSignatures)
15819                        != PackageManager.SIGNATURE_MATCH) {
15820                    throw new SecurityException(
15821                            "Caller does not have same cert as new installer package "
15822                            + installerPackageName);
15823                }
15824            }
15825
15826            // Verify: if target already has an installer package, it must
15827            // be signed with the same cert as the caller.
15828            if (targetPackageSetting.installerPackageName != null) {
15829                PackageSetting setting = mSettings.mPackages.get(
15830                        targetPackageSetting.installerPackageName);
15831                // If the currently set package isn't valid, then it's always
15832                // okay to change it.
15833                if (setting != null) {
15834                    if (compareSignatures(callerSignature,
15835                            setting.signatures.mSignatures)
15836                            != PackageManager.SIGNATURE_MATCH) {
15837                        throw new SecurityException(
15838                                "Caller does not have same cert as old installer package "
15839                                + targetPackageSetting.installerPackageName);
15840                    }
15841                }
15842            }
15843
15844            // Okay!
15845            targetPackageSetting.installerPackageName = installerPackageName;
15846            if (installerPackageName != null) {
15847                mSettings.mInstallerPackages.add(installerPackageName);
15848            }
15849            scheduleWriteSettingsLocked();
15850        }
15851    }
15852
15853    @Override
15854    public void setApplicationCategoryHint(String packageName, int categoryHint,
15855            String callerPackageName) {
15856        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15857            throw new SecurityException("Instant applications don't have access to this method");
15858        }
15859        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15860                callerPackageName);
15861        synchronized (mPackages) {
15862            PackageSetting ps = mSettings.mPackages.get(packageName);
15863            if (ps == null) {
15864                throw new IllegalArgumentException("Unknown target package " + packageName);
15865            }
15866            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15867                throw new IllegalArgumentException("Unknown target package " + packageName);
15868            }
15869            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15870                throw new IllegalArgumentException("Calling package " + callerPackageName
15871                        + " is not installer for " + packageName);
15872            }
15873
15874            if (ps.categoryHint != categoryHint) {
15875                ps.categoryHint = categoryHint;
15876                scheduleWriteSettingsLocked();
15877            }
15878        }
15879    }
15880
15881    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15882        // Queue up an async operation since the package installation may take a little while.
15883        mHandler.post(new Runnable() {
15884            public void run() {
15885                mHandler.removeCallbacks(this);
15886                 // Result object to be returned
15887                PackageInstalledInfo res = new PackageInstalledInfo();
15888                res.setReturnCode(currentStatus);
15889                res.uid = -1;
15890                res.pkg = null;
15891                res.removedInfo = null;
15892                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15893                    args.doPreInstall(res.returnCode);
15894                    synchronized (mInstallLock) {
15895                        installPackageTracedLI(args, res);
15896                    }
15897                    args.doPostInstall(res.returnCode, res.uid);
15898                }
15899
15900                // A restore should be performed at this point if (a) the install
15901                // succeeded, (b) the operation is not an update, and (c) the new
15902                // package has not opted out of backup participation.
15903                final boolean update = res.removedInfo != null
15904                        && res.removedInfo.removedPackage != null;
15905                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15906                boolean doRestore = !update
15907                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15908
15909                // Set up the post-install work request bookkeeping.  This will be used
15910                // and cleaned up by the post-install event handling regardless of whether
15911                // there's a restore pass performed.  Token values are >= 1.
15912                int token;
15913                if (mNextInstallToken < 0) mNextInstallToken = 1;
15914                token = mNextInstallToken++;
15915
15916                PostInstallData data = new PostInstallData(args, res);
15917                mRunningInstalls.put(token, data);
15918                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15919
15920                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15921                    // Pass responsibility to the Backup Manager.  It will perform a
15922                    // restore if appropriate, then pass responsibility back to the
15923                    // Package Manager to run the post-install observer callbacks
15924                    // and broadcasts.
15925                    IBackupManager bm = IBackupManager.Stub.asInterface(
15926                            ServiceManager.getService(Context.BACKUP_SERVICE));
15927                    if (bm != null) {
15928                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15929                                + " to BM for possible restore");
15930                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15931                        try {
15932                            // TODO: http://b/22388012
15933                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15934                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15935                            } else {
15936                                doRestore = false;
15937                            }
15938                        } catch (RemoteException e) {
15939                            // can't happen; the backup manager is local
15940                        } catch (Exception e) {
15941                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15942                            doRestore = false;
15943                        }
15944                    } else {
15945                        Slog.e(TAG, "Backup Manager not found!");
15946                        doRestore = false;
15947                    }
15948                }
15949
15950                if (!doRestore) {
15951                    // No restore possible, or the Backup Manager was mysteriously not
15952                    // available -- just fire the post-install work request directly.
15953                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15954
15955                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15956
15957                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15958                    mHandler.sendMessage(msg);
15959                }
15960            }
15961        });
15962    }
15963
15964    /**
15965     * Callback from PackageSettings whenever an app is first transitioned out of the
15966     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15967     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15968     * here whether the app is the target of an ongoing install, and only send the
15969     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15970     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15971     * handling.
15972     */
15973    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15974        // Serialize this with the rest of the install-process message chain.  In the
15975        // restore-at-install case, this Runnable will necessarily run before the
15976        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15977        // are coherent.  In the non-restore case, the app has already completed install
15978        // and been launched through some other means, so it is not in a problematic
15979        // state for observers to see the FIRST_LAUNCH signal.
15980        mHandler.post(new Runnable() {
15981            @Override
15982            public void run() {
15983                for (int i = 0; i < mRunningInstalls.size(); i++) {
15984                    final PostInstallData data = mRunningInstalls.valueAt(i);
15985                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15986                        continue;
15987                    }
15988                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15989                        // right package; but is it for the right user?
15990                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15991                            if (userId == data.res.newUsers[uIndex]) {
15992                                if (DEBUG_BACKUP) {
15993                                    Slog.i(TAG, "Package " + pkgName
15994                                            + " being restored so deferring FIRST_LAUNCH");
15995                                }
15996                                return;
15997                            }
15998                        }
15999                    }
16000                }
16001                // didn't find it, so not being restored
16002                if (DEBUG_BACKUP) {
16003                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
16004                }
16005                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
16006            }
16007        });
16008    }
16009
16010    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
16011        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
16012                installerPkg, null, userIds);
16013    }
16014
16015    private abstract class HandlerParams {
16016        private static final int MAX_RETRIES = 4;
16017
16018        /**
16019         * Number of times startCopy() has been attempted and had a non-fatal
16020         * error.
16021         */
16022        private int mRetries = 0;
16023
16024        /** User handle for the user requesting the information or installation. */
16025        private final UserHandle mUser;
16026        String traceMethod;
16027        int traceCookie;
16028
16029        HandlerParams(UserHandle user) {
16030            mUser = user;
16031        }
16032
16033        UserHandle getUser() {
16034            return mUser;
16035        }
16036
16037        HandlerParams setTraceMethod(String traceMethod) {
16038            this.traceMethod = traceMethod;
16039            return this;
16040        }
16041
16042        HandlerParams setTraceCookie(int traceCookie) {
16043            this.traceCookie = traceCookie;
16044            return this;
16045        }
16046
16047        final boolean startCopy() {
16048            boolean res;
16049            try {
16050                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
16051
16052                if (++mRetries > MAX_RETRIES) {
16053                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
16054                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
16055                    handleServiceError();
16056                    return false;
16057                } else {
16058                    handleStartCopy();
16059                    res = true;
16060                }
16061            } catch (RemoteException e) {
16062                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
16063                mHandler.sendEmptyMessage(MCS_RECONNECT);
16064                res = false;
16065            }
16066            handleReturnCode();
16067            return res;
16068        }
16069
16070        final void serviceError() {
16071            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
16072            handleServiceError();
16073            handleReturnCode();
16074        }
16075
16076        abstract void handleStartCopy() throws RemoteException;
16077        abstract void handleServiceError();
16078        abstract void handleReturnCode();
16079    }
16080
16081    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
16082        for (File path : paths) {
16083            try {
16084                mcs.clearDirectory(path.getAbsolutePath());
16085            } catch (RemoteException e) {
16086            }
16087        }
16088    }
16089
16090    static class OriginInfo {
16091        /**
16092         * Location where install is coming from, before it has been
16093         * copied/renamed into place. This could be a single monolithic APK
16094         * file, or a cluster directory. This location may be untrusted.
16095         */
16096        final File file;
16097        final String cid;
16098
16099        /**
16100         * Flag indicating that {@link #file} or {@link #cid} has already been
16101         * staged, meaning downstream users don't need to defensively copy the
16102         * contents.
16103         */
16104        final boolean staged;
16105
16106        /**
16107         * Flag indicating that {@link #file} or {@link #cid} is an already
16108         * installed app that is being moved.
16109         */
16110        final boolean existing;
16111
16112        final String resolvedPath;
16113        final File resolvedFile;
16114
16115        static OriginInfo fromNothing() {
16116            return new OriginInfo(null, null, false, false);
16117        }
16118
16119        static OriginInfo fromUntrustedFile(File file) {
16120            return new OriginInfo(file, null, false, false);
16121        }
16122
16123        static OriginInfo fromExistingFile(File file) {
16124            return new OriginInfo(file, null, false, true);
16125        }
16126
16127        static OriginInfo fromStagedFile(File file) {
16128            return new OriginInfo(file, null, true, false);
16129        }
16130
16131        static OriginInfo fromStagedContainer(String cid) {
16132            return new OriginInfo(null, cid, true, false);
16133        }
16134
16135        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
16136            this.file = file;
16137            this.cid = cid;
16138            this.staged = staged;
16139            this.existing = existing;
16140
16141            if (cid != null) {
16142                resolvedPath = PackageHelper.getSdDir(cid);
16143                resolvedFile = new File(resolvedPath);
16144            } else if (file != null) {
16145                resolvedPath = file.getAbsolutePath();
16146                resolvedFile = file;
16147            } else {
16148                resolvedPath = null;
16149                resolvedFile = null;
16150            }
16151        }
16152    }
16153
16154    static class MoveInfo {
16155        final int moveId;
16156        final String fromUuid;
16157        final String toUuid;
16158        final String packageName;
16159        final String dataAppName;
16160        final int appId;
16161        final String seinfo;
16162        final int targetSdkVersion;
16163
16164        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
16165                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
16166            this.moveId = moveId;
16167            this.fromUuid = fromUuid;
16168            this.toUuid = toUuid;
16169            this.packageName = packageName;
16170            this.dataAppName = dataAppName;
16171            this.appId = appId;
16172            this.seinfo = seinfo;
16173            this.targetSdkVersion = targetSdkVersion;
16174        }
16175    }
16176
16177    static class VerificationInfo {
16178        /** A constant used to indicate that a uid value is not present. */
16179        public static final int NO_UID = -1;
16180
16181        /** URI referencing where the package was downloaded from. */
16182        final Uri originatingUri;
16183
16184        /** HTTP referrer URI associated with the originatingURI. */
16185        final Uri referrer;
16186
16187        /** UID of the application that the install request originated from. */
16188        final int originatingUid;
16189
16190        /** UID of application requesting the install */
16191        final int installerUid;
16192
16193        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
16194            this.originatingUri = originatingUri;
16195            this.referrer = referrer;
16196            this.originatingUid = originatingUid;
16197            this.installerUid = installerUid;
16198        }
16199    }
16200
16201    class InstallParams extends HandlerParams {
16202        final OriginInfo origin;
16203        final MoveInfo move;
16204        final IPackageInstallObserver2 observer;
16205        int installFlags;
16206        final String installerPackageName;
16207        final String volumeUuid;
16208        private InstallArgs mArgs;
16209        private int mRet;
16210        final String packageAbiOverride;
16211        final String[] grantedRuntimePermissions;
16212        final VerificationInfo verificationInfo;
16213        final Certificate[][] certificates;
16214        final int installReason;
16215
16216        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16217                int installFlags, String installerPackageName, String volumeUuid,
16218                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
16219                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
16220            super(user);
16221            this.origin = origin;
16222            this.move = move;
16223            this.observer = observer;
16224            this.installFlags = installFlags;
16225            this.installerPackageName = installerPackageName;
16226            this.volumeUuid = volumeUuid;
16227            this.verificationInfo = verificationInfo;
16228            this.packageAbiOverride = packageAbiOverride;
16229            this.grantedRuntimePermissions = grantedPermissions;
16230            this.certificates = certificates;
16231            this.installReason = installReason;
16232        }
16233
16234        @Override
16235        public String toString() {
16236            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
16237                    + " file=" + origin.file + " cid=" + origin.cid + "}";
16238        }
16239
16240        private int installLocationPolicy(PackageInfoLite pkgLite) {
16241            String packageName = pkgLite.packageName;
16242            int installLocation = pkgLite.installLocation;
16243            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16244            // reader
16245            synchronized (mPackages) {
16246                // Currently installed package which the new package is attempting to replace or
16247                // null if no such package is installed.
16248                PackageParser.Package installedPkg = mPackages.get(packageName);
16249                // Package which currently owns the data which the new package will own if installed.
16250                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
16251                // will be null whereas dataOwnerPkg will contain information about the package
16252                // which was uninstalled while keeping its data.
16253                PackageParser.Package dataOwnerPkg = installedPkg;
16254                if (dataOwnerPkg  == null) {
16255                    PackageSetting ps = mSettings.mPackages.get(packageName);
16256                    if (ps != null) {
16257                        dataOwnerPkg = ps.pkg;
16258                    }
16259                }
16260
16261                if (dataOwnerPkg != null) {
16262                    // If installed, the package will get access to data left on the device by its
16263                    // predecessor. As a security measure, this is permited only if this is not a
16264                    // version downgrade or if the predecessor package is marked as debuggable and
16265                    // a downgrade is explicitly requested.
16266                    //
16267                    // On debuggable platform builds, downgrades are permitted even for
16268                    // non-debuggable packages to make testing easier. Debuggable platform builds do
16269                    // not offer security guarantees and thus it's OK to disable some security
16270                    // mechanisms to make debugging/testing easier on those builds. However, even on
16271                    // debuggable builds downgrades of packages are permitted only if requested via
16272                    // installFlags. This is because we aim to keep the behavior of debuggable
16273                    // platform builds as close as possible to the behavior of non-debuggable
16274                    // platform builds.
16275                    final boolean downgradeRequested =
16276                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
16277                    final boolean packageDebuggable =
16278                                (dataOwnerPkg.applicationInfo.flags
16279                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
16280                    final boolean downgradePermitted =
16281                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
16282                    if (!downgradePermitted) {
16283                        try {
16284                            checkDowngrade(dataOwnerPkg, pkgLite);
16285                        } catch (PackageManagerException e) {
16286                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
16287                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
16288                        }
16289                    }
16290                }
16291
16292                if (installedPkg != null) {
16293                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16294                        // Check for updated system application.
16295                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16296                            if (onSd) {
16297                                Slog.w(TAG, "Cannot install update to system app on sdcard");
16298                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
16299                            }
16300                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16301                        } else {
16302                            if (onSd) {
16303                                // Install flag overrides everything.
16304                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16305                            }
16306                            // If current upgrade specifies particular preference
16307                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
16308                                // Application explicitly specified internal.
16309                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16310                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
16311                                // App explictly prefers external. Let policy decide
16312                            } else {
16313                                // Prefer previous location
16314                                if (isExternal(installedPkg)) {
16315                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16316                                }
16317                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16318                            }
16319                        }
16320                    } else {
16321                        // Invalid install. Return error code
16322                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
16323                    }
16324                }
16325            }
16326            // All the special cases have been taken care of.
16327            // Return result based on recommended install location.
16328            if (onSd) {
16329                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16330            }
16331            return pkgLite.recommendedInstallLocation;
16332        }
16333
16334        /*
16335         * Invoke remote method to get package information and install
16336         * location values. Override install location based on default
16337         * policy if needed and then create install arguments based
16338         * on the install location.
16339         */
16340        public void handleStartCopy() throws RemoteException {
16341            int ret = PackageManager.INSTALL_SUCCEEDED;
16342
16343            // If we're already staged, we've firmly committed to an install location
16344            if (origin.staged) {
16345                if (origin.file != null) {
16346                    installFlags |= PackageManager.INSTALL_INTERNAL;
16347                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
16348                } else if (origin.cid != null) {
16349                    installFlags |= PackageManager.INSTALL_EXTERNAL;
16350                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
16351                } else {
16352                    throw new IllegalStateException("Invalid stage location");
16353                }
16354            }
16355
16356            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16357            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
16358            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16359            PackageInfoLite pkgLite = null;
16360
16361            if (onInt && onSd) {
16362                // Check if both bits are set.
16363                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
16364                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16365            } else if (onSd && ephemeral) {
16366                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
16367                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16368            } else {
16369                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
16370                        packageAbiOverride);
16371
16372                if (DEBUG_EPHEMERAL && ephemeral) {
16373                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
16374                }
16375
16376                /*
16377                 * If we have too little free space, try to free cache
16378                 * before giving up.
16379                 */
16380                if (!origin.staged && pkgLite.recommendedInstallLocation
16381                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
16382                    // TODO: focus freeing disk space on the target device
16383                    final StorageManager storage = StorageManager.from(mContext);
16384                    final long lowThreshold = storage.getStorageLowBytes(
16385                            Environment.getDataDirectory());
16386
16387                    final long sizeBytes = mContainerService.calculateInstalledSize(
16388                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
16389
16390                    try {
16391                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
16392                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
16393                                installFlags, packageAbiOverride);
16394                    } catch (InstallerException e) {
16395                        Slog.w(TAG, "Failed to free cache", e);
16396                    }
16397
16398                    /*
16399                     * The cache free must have deleted the file we
16400                     * downloaded to install.
16401                     *
16402                     * TODO: fix the "freeCache" call to not delete
16403                     *       the file we care about.
16404                     */
16405                    if (pkgLite.recommendedInstallLocation
16406                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
16407                        pkgLite.recommendedInstallLocation
16408                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
16409                    }
16410                }
16411            }
16412
16413            if (ret == PackageManager.INSTALL_SUCCEEDED) {
16414                int loc = pkgLite.recommendedInstallLocation;
16415                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
16416                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16417                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
16418                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
16419                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
16420                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16421                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
16422                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
16423                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
16424                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
16425                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
16426                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
16427                } else {
16428                    // Override with defaults if needed.
16429                    loc = installLocationPolicy(pkgLite);
16430                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
16431                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
16432                    } else if (!onSd && !onInt) {
16433                        // Override install location with flags
16434                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
16435                            // Set the flag to install on external media.
16436                            installFlags |= PackageManager.INSTALL_EXTERNAL;
16437                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
16438                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
16439                            if (DEBUG_EPHEMERAL) {
16440                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
16441                            }
16442                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
16443                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
16444                                    |PackageManager.INSTALL_INTERNAL);
16445                        } else {
16446                            // Make sure the flag for installing on external
16447                            // media is unset
16448                            installFlags |= PackageManager.INSTALL_INTERNAL;
16449                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
16450                        }
16451                    }
16452                }
16453            }
16454
16455            final InstallArgs args = createInstallArgs(this);
16456            mArgs = args;
16457
16458            if (ret == PackageManager.INSTALL_SUCCEEDED) {
16459                // TODO: http://b/22976637
16460                // Apps installed for "all" users use the device owner to verify the app
16461                UserHandle verifierUser = getUser();
16462                if (verifierUser == UserHandle.ALL) {
16463                    verifierUser = UserHandle.SYSTEM;
16464                }
16465
16466                /*
16467                 * Determine if we have any installed package verifiers. If we
16468                 * do, then we'll defer to them to verify the packages.
16469                 */
16470                final int requiredUid = mRequiredVerifierPackage == null ? -1
16471                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
16472                                verifierUser.getIdentifier());
16473                final int installerUid =
16474                        verificationInfo == null ? -1 : verificationInfo.installerUid;
16475                if (!origin.existing && requiredUid != -1
16476                        && isVerificationEnabled(
16477                                verifierUser.getIdentifier(), installFlags, installerUid)) {
16478                    final Intent verification = new Intent(
16479                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
16480                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
16481                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
16482                            PACKAGE_MIME_TYPE);
16483                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
16484
16485                    // Query all live verifiers based on current user state
16486                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
16487                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
16488                            false /*allowDynamicSplits*/);
16489
16490                    if (DEBUG_VERIFY) {
16491                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
16492                                + verification.toString() + " with " + pkgLite.verifiers.length
16493                                + " optional verifiers");
16494                    }
16495
16496                    final int verificationId = mPendingVerificationToken++;
16497
16498                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
16499
16500                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
16501                            installerPackageName);
16502
16503                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
16504                            installFlags);
16505
16506                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
16507                            pkgLite.packageName);
16508
16509                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
16510                            pkgLite.versionCode);
16511
16512                    if (verificationInfo != null) {
16513                        if (verificationInfo.originatingUri != null) {
16514                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
16515                                    verificationInfo.originatingUri);
16516                        }
16517                        if (verificationInfo.referrer != null) {
16518                            verification.putExtra(Intent.EXTRA_REFERRER,
16519                                    verificationInfo.referrer);
16520                        }
16521                        if (verificationInfo.originatingUid >= 0) {
16522                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
16523                                    verificationInfo.originatingUid);
16524                        }
16525                        if (verificationInfo.installerUid >= 0) {
16526                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
16527                                    verificationInfo.installerUid);
16528                        }
16529                    }
16530
16531                    final PackageVerificationState verificationState = new PackageVerificationState(
16532                            requiredUid, args);
16533
16534                    mPendingVerification.append(verificationId, verificationState);
16535
16536                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
16537                            receivers, verificationState);
16538
16539                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
16540                    final long idleDuration = getVerificationTimeout();
16541
16542                    /*
16543                     * If any sufficient verifiers were listed in the package
16544                     * manifest, attempt to ask them.
16545                     */
16546                    if (sufficientVerifiers != null) {
16547                        final int N = sufficientVerifiers.size();
16548                        if (N == 0) {
16549                            Slog.i(TAG, "Additional verifiers required, but none installed.");
16550                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
16551                        } else {
16552                            for (int i = 0; i < N; i++) {
16553                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
16554                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16555                                        verifierComponent.getPackageName(), idleDuration,
16556                                        verifierUser.getIdentifier(), false, "package verifier");
16557
16558                                final Intent sufficientIntent = new Intent(verification);
16559                                sufficientIntent.setComponent(verifierComponent);
16560                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
16561                            }
16562                        }
16563                    }
16564
16565                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
16566                            mRequiredVerifierPackage, receivers);
16567                    if (ret == PackageManager.INSTALL_SUCCEEDED
16568                            && mRequiredVerifierPackage != null) {
16569                        Trace.asyncTraceBegin(
16570                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
16571                        /*
16572                         * Send the intent to the required verification agent,
16573                         * but only start the verification timeout after the
16574                         * target BroadcastReceivers have run.
16575                         */
16576                        verification.setComponent(requiredVerifierComponent);
16577                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16578                                mRequiredVerifierPackage, idleDuration,
16579                                verifierUser.getIdentifier(), false, "package verifier");
16580                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
16581                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16582                                new BroadcastReceiver() {
16583                                    @Override
16584                                    public void onReceive(Context context, Intent intent) {
16585                                        final Message msg = mHandler
16586                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
16587                                        msg.arg1 = verificationId;
16588                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
16589                                    }
16590                                }, null, 0, null, null);
16591
16592                        /*
16593                         * We don't want the copy to proceed until verification
16594                         * succeeds, so null out this field.
16595                         */
16596                        mArgs = null;
16597                    }
16598                } else {
16599                    /*
16600                     * No package verification is enabled, so immediately start
16601                     * the remote call to initiate copy using temporary file.
16602                     */
16603                    ret = args.copyApk(mContainerService, true);
16604                }
16605            }
16606
16607            mRet = ret;
16608        }
16609
16610        @Override
16611        void handleReturnCode() {
16612            // If mArgs is null, then MCS couldn't be reached. When it
16613            // reconnects, it will try again to install. At that point, this
16614            // will succeed.
16615            if (mArgs != null) {
16616                processPendingInstall(mArgs, mRet);
16617            }
16618        }
16619
16620        @Override
16621        void handleServiceError() {
16622            mArgs = createInstallArgs(this);
16623            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16624        }
16625
16626        public boolean isForwardLocked() {
16627            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16628        }
16629    }
16630
16631    /**
16632     * Used during creation of InstallArgs
16633     *
16634     * @param installFlags package installation flags
16635     * @return true if should be installed on external storage
16636     */
16637    private static boolean installOnExternalAsec(int installFlags) {
16638        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
16639            return false;
16640        }
16641        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
16642            return true;
16643        }
16644        return false;
16645    }
16646
16647    /**
16648     * Used during creation of InstallArgs
16649     *
16650     * @param installFlags package installation flags
16651     * @return true if should be installed as forward locked
16652     */
16653    private static boolean installForwardLocked(int installFlags) {
16654        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16655    }
16656
16657    private InstallArgs createInstallArgs(InstallParams params) {
16658        if (params.move != null) {
16659            return new MoveInstallArgs(params);
16660        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
16661            return new AsecInstallArgs(params);
16662        } else {
16663            return new FileInstallArgs(params);
16664        }
16665    }
16666
16667    /**
16668     * Create args that describe an existing installed package. Typically used
16669     * when cleaning up old installs, or used as a move source.
16670     */
16671    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
16672            String resourcePath, String[] instructionSets) {
16673        final boolean isInAsec;
16674        if (installOnExternalAsec(installFlags)) {
16675            /* Apps on SD card are always in ASEC containers. */
16676            isInAsec = true;
16677        } else if (installForwardLocked(installFlags)
16678                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
16679            /*
16680             * Forward-locked apps are only in ASEC containers if they're the
16681             * new style
16682             */
16683            isInAsec = true;
16684        } else {
16685            isInAsec = false;
16686        }
16687
16688        if (isInAsec) {
16689            return new AsecInstallArgs(codePath, instructionSets,
16690                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
16691        } else {
16692            return new FileInstallArgs(codePath, resourcePath, instructionSets);
16693        }
16694    }
16695
16696    static abstract class InstallArgs {
16697        /** @see InstallParams#origin */
16698        final OriginInfo origin;
16699        /** @see InstallParams#move */
16700        final MoveInfo move;
16701
16702        final IPackageInstallObserver2 observer;
16703        // Always refers to PackageManager flags only
16704        final int installFlags;
16705        final String installerPackageName;
16706        final String volumeUuid;
16707        final UserHandle user;
16708        final String abiOverride;
16709        final String[] installGrantPermissions;
16710        /** If non-null, drop an async trace when the install completes */
16711        final String traceMethod;
16712        final int traceCookie;
16713        final Certificate[][] certificates;
16714        final int installReason;
16715
16716        // The list of instruction sets supported by this app. This is currently
16717        // only used during the rmdex() phase to clean up resources. We can get rid of this
16718        // if we move dex files under the common app path.
16719        /* nullable */ String[] instructionSets;
16720
16721        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16722                int installFlags, String installerPackageName, String volumeUuid,
16723                UserHandle user, String[] instructionSets,
16724                String abiOverride, String[] installGrantPermissions,
16725                String traceMethod, int traceCookie, Certificate[][] certificates,
16726                int installReason) {
16727            this.origin = origin;
16728            this.move = move;
16729            this.installFlags = installFlags;
16730            this.observer = observer;
16731            this.installerPackageName = installerPackageName;
16732            this.volumeUuid = volumeUuid;
16733            this.user = user;
16734            this.instructionSets = instructionSets;
16735            this.abiOverride = abiOverride;
16736            this.installGrantPermissions = installGrantPermissions;
16737            this.traceMethod = traceMethod;
16738            this.traceCookie = traceCookie;
16739            this.certificates = certificates;
16740            this.installReason = installReason;
16741        }
16742
16743        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16744        abstract int doPreInstall(int status);
16745
16746        /**
16747         * Rename package into final resting place. All paths on the given
16748         * scanned package should be updated to reflect the rename.
16749         */
16750        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16751        abstract int doPostInstall(int status, int uid);
16752
16753        /** @see PackageSettingBase#codePathString */
16754        abstract String getCodePath();
16755        /** @see PackageSettingBase#resourcePathString */
16756        abstract String getResourcePath();
16757
16758        // Need installer lock especially for dex file removal.
16759        abstract void cleanUpResourcesLI();
16760        abstract boolean doPostDeleteLI(boolean delete);
16761
16762        /**
16763         * Called before the source arguments are copied. This is used mostly
16764         * for MoveParams when it needs to read the source file to put it in the
16765         * destination.
16766         */
16767        int doPreCopy() {
16768            return PackageManager.INSTALL_SUCCEEDED;
16769        }
16770
16771        /**
16772         * Called after the source arguments are copied. This is used mostly for
16773         * MoveParams when it needs to read the source file to put it in the
16774         * destination.
16775         */
16776        int doPostCopy(int uid) {
16777            return PackageManager.INSTALL_SUCCEEDED;
16778        }
16779
16780        protected boolean isFwdLocked() {
16781            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16782        }
16783
16784        protected boolean isExternalAsec() {
16785            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16786        }
16787
16788        protected boolean isEphemeral() {
16789            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16790        }
16791
16792        UserHandle getUser() {
16793            return user;
16794        }
16795    }
16796
16797    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16798        if (!allCodePaths.isEmpty()) {
16799            if (instructionSets == null) {
16800                throw new IllegalStateException("instructionSet == null");
16801            }
16802            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16803            for (String codePath : allCodePaths) {
16804                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16805                    try {
16806                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
16807                    } catch (InstallerException ignored) {
16808                    }
16809                }
16810            }
16811        }
16812    }
16813
16814    /**
16815     * Logic to handle installation of non-ASEC applications, including copying
16816     * and renaming logic.
16817     */
16818    class FileInstallArgs extends InstallArgs {
16819        private File codeFile;
16820        private File resourceFile;
16821
16822        // Example topology:
16823        // /data/app/com.example/base.apk
16824        // /data/app/com.example/split_foo.apk
16825        // /data/app/com.example/lib/arm/libfoo.so
16826        // /data/app/com.example/lib/arm64/libfoo.so
16827        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16828
16829        /** New install */
16830        FileInstallArgs(InstallParams params) {
16831            super(params.origin, params.move, params.observer, params.installFlags,
16832                    params.installerPackageName, params.volumeUuid,
16833                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16834                    params.grantedRuntimePermissions,
16835                    params.traceMethod, params.traceCookie, params.certificates,
16836                    params.installReason);
16837            if (isFwdLocked()) {
16838                throw new IllegalArgumentException("Forward locking only supported in ASEC");
16839            }
16840        }
16841
16842        /** Existing install */
16843        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16844            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16845                    null, null, null, 0, null /*certificates*/,
16846                    PackageManager.INSTALL_REASON_UNKNOWN);
16847            this.codeFile = (codePath != null) ? new File(codePath) : null;
16848            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16849        }
16850
16851        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16852            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16853            try {
16854                return doCopyApk(imcs, temp);
16855            } finally {
16856                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16857            }
16858        }
16859
16860        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16861            if (origin.staged) {
16862                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16863                codeFile = origin.file;
16864                resourceFile = origin.file;
16865                return PackageManager.INSTALL_SUCCEEDED;
16866            }
16867
16868            try {
16869                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16870                final File tempDir =
16871                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16872                codeFile = tempDir;
16873                resourceFile = tempDir;
16874            } catch (IOException e) {
16875                Slog.w(TAG, "Failed to create copy file: " + e);
16876                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16877            }
16878
16879            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16880                @Override
16881                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16882                    if (!FileUtils.isValidExtFilename(name)) {
16883                        throw new IllegalArgumentException("Invalid filename: " + name);
16884                    }
16885                    try {
16886                        final File file = new File(codeFile, name);
16887                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16888                                O_RDWR | O_CREAT, 0644);
16889                        Os.chmod(file.getAbsolutePath(), 0644);
16890                        return new ParcelFileDescriptor(fd);
16891                    } catch (ErrnoException e) {
16892                        throw new RemoteException("Failed to open: " + e.getMessage());
16893                    }
16894                }
16895            };
16896
16897            int ret = PackageManager.INSTALL_SUCCEEDED;
16898            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16899            if (ret != PackageManager.INSTALL_SUCCEEDED) {
16900                Slog.e(TAG, "Failed to copy package");
16901                return ret;
16902            }
16903
16904            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16905            NativeLibraryHelper.Handle handle = null;
16906            try {
16907                handle = NativeLibraryHelper.Handle.create(codeFile);
16908                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16909                        abiOverride);
16910            } catch (IOException e) {
16911                Slog.e(TAG, "Copying native libraries failed", e);
16912                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16913            } finally {
16914                IoUtils.closeQuietly(handle);
16915            }
16916
16917            return ret;
16918        }
16919
16920        int doPreInstall(int status) {
16921            if (status != PackageManager.INSTALL_SUCCEEDED) {
16922                cleanUp();
16923            }
16924            return status;
16925        }
16926
16927        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16928            if (status != PackageManager.INSTALL_SUCCEEDED) {
16929                cleanUp();
16930                return false;
16931            }
16932
16933            final File targetDir = codeFile.getParentFile();
16934            final File beforeCodeFile = codeFile;
16935            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16936
16937            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16938            try {
16939                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16940            } catch (ErrnoException e) {
16941                Slog.w(TAG, "Failed to rename", e);
16942                return false;
16943            }
16944
16945            if (!SELinux.restoreconRecursive(afterCodeFile)) {
16946                Slog.w(TAG, "Failed to restorecon");
16947                return false;
16948            }
16949
16950            // Reflect the rename internally
16951            codeFile = afterCodeFile;
16952            resourceFile = afterCodeFile;
16953
16954            // Reflect the rename in scanned details
16955            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16956            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16957                    afterCodeFile, pkg.baseCodePath));
16958            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16959                    afterCodeFile, pkg.splitCodePaths));
16960
16961            // Reflect the rename in app info
16962            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16963            pkg.setApplicationInfoCodePath(pkg.codePath);
16964            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16965            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16966            pkg.setApplicationInfoResourcePath(pkg.codePath);
16967            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16968            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16969
16970            return true;
16971        }
16972
16973        int doPostInstall(int status, int uid) {
16974            if (status != PackageManager.INSTALL_SUCCEEDED) {
16975                cleanUp();
16976            }
16977            return status;
16978        }
16979
16980        @Override
16981        String getCodePath() {
16982            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16983        }
16984
16985        @Override
16986        String getResourcePath() {
16987            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16988        }
16989
16990        private boolean cleanUp() {
16991            if (codeFile == null || !codeFile.exists()) {
16992                return false;
16993            }
16994
16995            removeCodePathLI(codeFile);
16996
16997            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16998                resourceFile.delete();
16999            }
17000
17001            return true;
17002        }
17003
17004        void cleanUpResourcesLI() {
17005            // Try enumerating all code paths before deleting
17006            List<String> allCodePaths = Collections.EMPTY_LIST;
17007            if (codeFile != null && codeFile.exists()) {
17008                try {
17009                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
17010                    allCodePaths = pkg.getAllCodePaths();
17011                } catch (PackageParserException e) {
17012                    // Ignored; we tried our best
17013                }
17014            }
17015
17016            cleanUp();
17017            removeDexFiles(allCodePaths, instructionSets);
17018        }
17019
17020        boolean doPostDeleteLI(boolean delete) {
17021            // XXX err, shouldn't we respect the delete flag?
17022            cleanUpResourcesLI();
17023            return true;
17024        }
17025    }
17026
17027    private boolean isAsecExternal(String cid) {
17028        final String asecPath = PackageHelper.getSdFilesystem(cid);
17029        return !asecPath.startsWith(mAsecInternalPath);
17030    }
17031
17032    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
17033            PackageManagerException {
17034        if (copyRet < 0) {
17035            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
17036                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
17037                throw new PackageManagerException(copyRet, message);
17038            }
17039        }
17040    }
17041
17042    /**
17043     * Extract the StorageManagerService "container ID" from the full code path of an
17044     * .apk.
17045     */
17046    static String cidFromCodePath(String fullCodePath) {
17047        int eidx = fullCodePath.lastIndexOf("/");
17048        String subStr1 = fullCodePath.substring(0, eidx);
17049        int sidx = subStr1.lastIndexOf("/");
17050        return subStr1.substring(sidx+1, eidx);
17051    }
17052
17053    /**
17054     * Logic to handle installation of ASEC applications, including copying and
17055     * renaming logic.
17056     */
17057    class AsecInstallArgs extends InstallArgs {
17058        static final String RES_FILE_NAME = "pkg.apk";
17059        static final String PUBLIC_RES_FILE_NAME = "res.zip";
17060
17061        String cid;
17062        String packagePath;
17063        String resourcePath;
17064
17065        /** New install */
17066        AsecInstallArgs(InstallParams params) {
17067            super(params.origin, params.move, params.observer, params.installFlags,
17068                    params.installerPackageName, params.volumeUuid,
17069                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
17070                    params.grantedRuntimePermissions,
17071                    params.traceMethod, params.traceCookie, params.certificates,
17072                    params.installReason);
17073        }
17074
17075        /** Existing install */
17076        AsecInstallArgs(String fullCodePath, String[] instructionSets,
17077                        boolean isExternal, boolean isForwardLocked) {
17078            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
17079                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
17080                    instructionSets, null, null, null, 0, null /*certificates*/,
17081                    PackageManager.INSTALL_REASON_UNKNOWN);
17082            // Hackily pretend we're still looking at a full code path
17083            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
17084                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
17085            }
17086
17087            // Extract cid from fullCodePath
17088            int eidx = fullCodePath.lastIndexOf("/");
17089            String subStr1 = fullCodePath.substring(0, eidx);
17090            int sidx = subStr1.lastIndexOf("/");
17091            cid = subStr1.substring(sidx+1, eidx);
17092            setMountPath(subStr1);
17093        }
17094
17095        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
17096            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
17097                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
17098                    instructionSets, null, null, null, 0, null /*certificates*/,
17099                    PackageManager.INSTALL_REASON_UNKNOWN);
17100            this.cid = cid;
17101            setMountPath(PackageHelper.getSdDir(cid));
17102        }
17103
17104        void createCopyFile() {
17105            cid = mInstallerService.allocateExternalStageCidLegacy();
17106        }
17107
17108        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
17109            if (origin.staged && origin.cid != null) {
17110                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
17111                cid = origin.cid;
17112                setMountPath(PackageHelper.getSdDir(cid));
17113                return PackageManager.INSTALL_SUCCEEDED;
17114            }
17115
17116            if (temp) {
17117                createCopyFile();
17118            } else {
17119                /*
17120                 * Pre-emptively destroy the container since it's destroyed if
17121                 * copying fails due to it existing anyway.
17122                 */
17123                PackageHelper.destroySdDir(cid);
17124            }
17125
17126            final String newMountPath = imcs.copyPackageToContainer(
17127                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
17128                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
17129
17130            if (newMountPath != null) {
17131                setMountPath(newMountPath);
17132                return PackageManager.INSTALL_SUCCEEDED;
17133            } else {
17134                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17135            }
17136        }
17137
17138        @Override
17139        String getCodePath() {
17140            return packagePath;
17141        }
17142
17143        @Override
17144        String getResourcePath() {
17145            return resourcePath;
17146        }
17147
17148        int doPreInstall(int status) {
17149            if (status != PackageManager.INSTALL_SUCCEEDED) {
17150                // Destroy container
17151                PackageHelper.destroySdDir(cid);
17152            } else {
17153                boolean mounted = PackageHelper.isContainerMounted(cid);
17154                if (!mounted) {
17155                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
17156                            Process.SYSTEM_UID);
17157                    if (newMountPath != null) {
17158                        setMountPath(newMountPath);
17159                    } else {
17160                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17161                    }
17162                }
17163            }
17164            return status;
17165        }
17166
17167        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
17168            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
17169            String newMountPath = null;
17170            if (PackageHelper.isContainerMounted(cid)) {
17171                // Unmount the container
17172                if (!PackageHelper.unMountSdDir(cid)) {
17173                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
17174                    return false;
17175                }
17176            }
17177            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
17178                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
17179                        " which might be stale. Will try to clean up.");
17180                // Clean up the stale container and proceed to recreate.
17181                if (!PackageHelper.destroySdDir(newCacheId)) {
17182                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
17183                    return false;
17184                }
17185                // Successfully cleaned up stale container. Try to rename again.
17186                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
17187                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
17188                            + " inspite of cleaning it up.");
17189                    return false;
17190                }
17191            }
17192            if (!PackageHelper.isContainerMounted(newCacheId)) {
17193                Slog.w(TAG, "Mounting container " + newCacheId);
17194                newMountPath = PackageHelper.mountSdDir(newCacheId,
17195                        getEncryptKey(), Process.SYSTEM_UID);
17196            } else {
17197                newMountPath = PackageHelper.getSdDir(newCacheId);
17198            }
17199            if (newMountPath == null) {
17200                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
17201                return false;
17202            }
17203            Log.i(TAG, "Succesfully renamed " + cid +
17204                    " to " + newCacheId +
17205                    " at new path: " + newMountPath);
17206            cid = newCacheId;
17207
17208            final File beforeCodeFile = new File(packagePath);
17209            setMountPath(newMountPath);
17210            final File afterCodeFile = new File(packagePath);
17211
17212            // Reflect the rename in scanned details
17213            pkg.setCodePath(afterCodeFile.getAbsolutePath());
17214            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
17215                    afterCodeFile, pkg.baseCodePath));
17216            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
17217                    afterCodeFile, pkg.splitCodePaths));
17218
17219            // Reflect the rename in app info
17220            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
17221            pkg.setApplicationInfoCodePath(pkg.codePath);
17222            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
17223            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
17224            pkg.setApplicationInfoResourcePath(pkg.codePath);
17225            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
17226            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
17227
17228            return true;
17229        }
17230
17231        private void setMountPath(String mountPath) {
17232            final File mountFile = new File(mountPath);
17233
17234            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
17235            if (monolithicFile.exists()) {
17236                packagePath = monolithicFile.getAbsolutePath();
17237                if (isFwdLocked()) {
17238                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
17239                } else {
17240                    resourcePath = packagePath;
17241                }
17242            } else {
17243                packagePath = mountFile.getAbsolutePath();
17244                resourcePath = packagePath;
17245            }
17246        }
17247
17248        int doPostInstall(int status, int uid) {
17249            if (status != PackageManager.INSTALL_SUCCEEDED) {
17250                cleanUp();
17251            } else {
17252                final int groupOwner;
17253                final String protectedFile;
17254                if (isFwdLocked()) {
17255                    groupOwner = UserHandle.getSharedAppGid(uid);
17256                    protectedFile = RES_FILE_NAME;
17257                } else {
17258                    groupOwner = -1;
17259                    protectedFile = null;
17260                }
17261
17262                if (uid < Process.FIRST_APPLICATION_UID
17263                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
17264                    Slog.e(TAG, "Failed to finalize " + cid);
17265                    PackageHelper.destroySdDir(cid);
17266                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17267                }
17268
17269                boolean mounted = PackageHelper.isContainerMounted(cid);
17270                if (!mounted) {
17271                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
17272                }
17273            }
17274            return status;
17275        }
17276
17277        private void cleanUp() {
17278            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
17279
17280            // Destroy secure container
17281            PackageHelper.destroySdDir(cid);
17282        }
17283
17284        private List<String> getAllCodePaths() {
17285            final File codeFile = new File(getCodePath());
17286            if (codeFile != null && codeFile.exists()) {
17287                try {
17288                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
17289                    return pkg.getAllCodePaths();
17290                } catch (PackageParserException e) {
17291                    // Ignored; we tried our best
17292                }
17293            }
17294            return Collections.EMPTY_LIST;
17295        }
17296
17297        void cleanUpResourcesLI() {
17298            // Enumerate all code paths before deleting
17299            cleanUpResourcesLI(getAllCodePaths());
17300        }
17301
17302        private void cleanUpResourcesLI(List<String> allCodePaths) {
17303            cleanUp();
17304            removeDexFiles(allCodePaths, instructionSets);
17305        }
17306
17307        String getPackageName() {
17308            return getAsecPackageName(cid);
17309        }
17310
17311        boolean doPostDeleteLI(boolean delete) {
17312            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
17313            final List<String> allCodePaths = getAllCodePaths();
17314            boolean mounted = PackageHelper.isContainerMounted(cid);
17315            if (mounted) {
17316                // Unmount first
17317                if (PackageHelper.unMountSdDir(cid)) {
17318                    mounted = false;
17319                }
17320            }
17321            if (!mounted && delete) {
17322                cleanUpResourcesLI(allCodePaths);
17323            }
17324            return !mounted;
17325        }
17326
17327        @Override
17328        int doPreCopy() {
17329            if (isFwdLocked()) {
17330                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
17331                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
17332                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17333                }
17334            }
17335
17336            return PackageManager.INSTALL_SUCCEEDED;
17337        }
17338
17339        @Override
17340        int doPostCopy(int uid) {
17341            if (isFwdLocked()) {
17342                if (uid < Process.FIRST_APPLICATION_UID
17343                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
17344                                RES_FILE_NAME)) {
17345                    Slog.e(TAG, "Failed to finalize " + cid);
17346                    PackageHelper.destroySdDir(cid);
17347                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17348                }
17349            }
17350
17351            return PackageManager.INSTALL_SUCCEEDED;
17352        }
17353    }
17354
17355    /**
17356     * Logic to handle movement of existing installed applications.
17357     */
17358    class MoveInstallArgs extends InstallArgs {
17359        private File codeFile;
17360        private File resourceFile;
17361
17362        /** New install */
17363        MoveInstallArgs(InstallParams params) {
17364            super(params.origin, params.move, params.observer, params.installFlags,
17365                    params.installerPackageName, params.volumeUuid,
17366                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
17367                    params.grantedRuntimePermissions,
17368                    params.traceMethod, params.traceCookie, params.certificates,
17369                    params.installReason);
17370        }
17371
17372        int copyApk(IMediaContainerService imcs, boolean temp) {
17373            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
17374                    + move.fromUuid + " to " + move.toUuid);
17375            synchronized (mInstaller) {
17376                try {
17377                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
17378                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
17379                } catch (InstallerException e) {
17380                    Slog.w(TAG, "Failed to move app", e);
17381                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
17382                }
17383            }
17384
17385            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
17386            resourceFile = codeFile;
17387            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
17388
17389            return PackageManager.INSTALL_SUCCEEDED;
17390        }
17391
17392        int doPreInstall(int status) {
17393            if (status != PackageManager.INSTALL_SUCCEEDED) {
17394                cleanUp(move.toUuid);
17395            }
17396            return status;
17397        }
17398
17399        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
17400            if (status != PackageManager.INSTALL_SUCCEEDED) {
17401                cleanUp(move.toUuid);
17402                return false;
17403            }
17404
17405            // Reflect the move in app info
17406            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
17407            pkg.setApplicationInfoCodePath(pkg.codePath);
17408            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
17409            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
17410            pkg.setApplicationInfoResourcePath(pkg.codePath);
17411            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
17412            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
17413
17414            return true;
17415        }
17416
17417        int doPostInstall(int status, int uid) {
17418            if (status == PackageManager.INSTALL_SUCCEEDED) {
17419                cleanUp(move.fromUuid);
17420            } else {
17421                cleanUp(move.toUuid);
17422            }
17423            return status;
17424        }
17425
17426        @Override
17427        String getCodePath() {
17428            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
17429        }
17430
17431        @Override
17432        String getResourcePath() {
17433            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
17434        }
17435
17436        private boolean cleanUp(String volumeUuid) {
17437            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
17438                    move.dataAppName);
17439            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
17440            final int[] userIds = sUserManager.getUserIds();
17441            synchronized (mInstallLock) {
17442                // Clean up both app data and code
17443                // All package moves are frozen until finished
17444                for (int userId : userIds) {
17445                    try {
17446                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
17447                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
17448                    } catch (InstallerException e) {
17449                        Slog.w(TAG, String.valueOf(e));
17450                    }
17451                }
17452                removeCodePathLI(codeFile);
17453            }
17454            return true;
17455        }
17456
17457        void cleanUpResourcesLI() {
17458            throw new UnsupportedOperationException();
17459        }
17460
17461        boolean doPostDeleteLI(boolean delete) {
17462            throw new UnsupportedOperationException();
17463        }
17464    }
17465
17466    static String getAsecPackageName(String packageCid) {
17467        int idx = packageCid.lastIndexOf("-");
17468        if (idx == -1) {
17469            return packageCid;
17470        }
17471        return packageCid.substring(0, idx);
17472    }
17473
17474    // Utility method used to create code paths based on package name and available index.
17475    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
17476        String idxStr = "";
17477        int idx = 1;
17478        // Fall back to default value of idx=1 if prefix is not
17479        // part of oldCodePath
17480        if (oldCodePath != null) {
17481            String subStr = oldCodePath;
17482            // Drop the suffix right away
17483            if (suffix != null && subStr.endsWith(suffix)) {
17484                subStr = subStr.substring(0, subStr.length() - suffix.length());
17485            }
17486            // If oldCodePath already contains prefix find out the
17487            // ending index to either increment or decrement.
17488            int sidx = subStr.lastIndexOf(prefix);
17489            if (sidx != -1) {
17490                subStr = subStr.substring(sidx + prefix.length());
17491                if (subStr != null) {
17492                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
17493                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
17494                    }
17495                    try {
17496                        idx = Integer.parseInt(subStr);
17497                        if (idx <= 1) {
17498                            idx++;
17499                        } else {
17500                            idx--;
17501                        }
17502                    } catch(NumberFormatException e) {
17503                    }
17504                }
17505            }
17506        }
17507        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
17508        return prefix + idxStr;
17509    }
17510
17511    private File getNextCodePath(File targetDir, String packageName) {
17512        File result;
17513        SecureRandom random = new SecureRandom();
17514        byte[] bytes = new byte[16];
17515        do {
17516            random.nextBytes(bytes);
17517            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
17518            result = new File(targetDir, packageName + "-" + suffix);
17519        } while (result.exists());
17520        return result;
17521    }
17522
17523    // Utility method that returns the relative package path with respect
17524    // to the installation directory. Like say for /data/data/com.test-1.apk
17525    // string com.test-1 is returned.
17526    static String deriveCodePathName(String codePath) {
17527        if (codePath == null) {
17528            return null;
17529        }
17530        final File codeFile = new File(codePath);
17531        final String name = codeFile.getName();
17532        if (codeFile.isDirectory()) {
17533            return name;
17534        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
17535            final int lastDot = name.lastIndexOf('.');
17536            return name.substring(0, lastDot);
17537        } else {
17538            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
17539            return null;
17540        }
17541    }
17542
17543    static class PackageInstalledInfo {
17544        String name;
17545        int uid;
17546        // The set of users that originally had this package installed.
17547        int[] origUsers;
17548        // The set of users that now have this package installed.
17549        int[] newUsers;
17550        PackageParser.Package pkg;
17551        int returnCode;
17552        String returnMsg;
17553        String installerPackageName;
17554        PackageRemovedInfo removedInfo;
17555        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
17556
17557        public void setError(int code, String msg) {
17558            setReturnCode(code);
17559            setReturnMessage(msg);
17560            Slog.w(TAG, msg);
17561        }
17562
17563        public void setError(String msg, PackageParserException e) {
17564            setReturnCode(e.error);
17565            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17566            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17567            for (int i = 0; i < childCount; i++) {
17568                addedChildPackages.valueAt(i).setError(msg, e);
17569            }
17570            Slog.w(TAG, msg, e);
17571        }
17572
17573        public void setError(String msg, PackageManagerException e) {
17574            returnCode = e.error;
17575            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17576            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17577            for (int i = 0; i < childCount; i++) {
17578                addedChildPackages.valueAt(i).setError(msg, e);
17579            }
17580            Slog.w(TAG, msg, e);
17581        }
17582
17583        public void setReturnCode(int returnCode) {
17584            this.returnCode = returnCode;
17585            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17586            for (int i = 0; i < childCount; i++) {
17587                addedChildPackages.valueAt(i).returnCode = returnCode;
17588            }
17589        }
17590
17591        private void setReturnMessage(String returnMsg) {
17592            this.returnMsg = returnMsg;
17593            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17594            for (int i = 0; i < childCount; i++) {
17595                addedChildPackages.valueAt(i).returnMsg = returnMsg;
17596            }
17597        }
17598
17599        // In some error cases we want to convey more info back to the observer
17600        String origPackage;
17601        String origPermission;
17602    }
17603
17604    /*
17605     * Install a non-existing package.
17606     */
17607    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
17608            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
17609            PackageInstalledInfo res, int installReason) {
17610        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
17611
17612        // Remember this for later, in case we need to rollback this install
17613        String pkgName = pkg.packageName;
17614
17615        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
17616
17617        synchronized(mPackages) {
17618            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
17619            if (renamedPackage != null) {
17620                // A package with the same name is already installed, though
17621                // it has been renamed to an older name.  The package we
17622                // are trying to install should be installed as an update to
17623                // the existing one, but that has not been requested, so bail.
17624                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17625                        + " without first uninstalling package running as "
17626                        + renamedPackage);
17627                return;
17628            }
17629            if (mPackages.containsKey(pkgName)) {
17630                // Don't allow installation over an existing package with the same name.
17631                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17632                        + " without first uninstalling.");
17633                return;
17634            }
17635        }
17636
17637        try {
17638            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
17639                    System.currentTimeMillis(), user);
17640
17641            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
17642
17643            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17644                prepareAppDataAfterInstallLIF(newPackage);
17645
17646            } else {
17647                // Remove package from internal structures, but keep around any
17648                // data that might have already existed
17649                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
17650                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
17651            }
17652        } catch (PackageManagerException e) {
17653            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17654        }
17655
17656        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17657    }
17658
17659    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
17660        // Can't rotate keys during boot or if sharedUser.
17661        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
17662                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
17663            return false;
17664        }
17665        // app is using upgradeKeySets; make sure all are valid
17666        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17667        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
17668        for (int i = 0; i < upgradeKeySets.length; i++) {
17669            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
17670                Slog.wtf(TAG, "Package "
17671                         + (oldPs.name != null ? oldPs.name : "<null>")
17672                         + " contains upgrade-key-set reference to unknown key-set: "
17673                         + upgradeKeySets[i]
17674                         + " reverting to signatures check.");
17675                return false;
17676            }
17677        }
17678        return true;
17679    }
17680
17681    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
17682        // Upgrade keysets are being used.  Determine if new package has a superset of the
17683        // required keys.
17684        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
17685        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17686        for (int i = 0; i < upgradeKeySets.length; i++) {
17687            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
17688            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
17689                return true;
17690            }
17691        }
17692        return false;
17693    }
17694
17695    private static void updateDigest(MessageDigest digest, File file) throws IOException {
17696        try (DigestInputStream digestStream =
17697                new DigestInputStream(new FileInputStream(file), digest)) {
17698            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
17699        }
17700    }
17701
17702    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
17703            UserHandle user, String installerPackageName, PackageInstalledInfo res,
17704            int installReason) {
17705        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17706
17707        final PackageParser.Package oldPackage;
17708        final PackageSetting ps;
17709        final String pkgName = pkg.packageName;
17710        final int[] allUsers;
17711        final int[] installedUsers;
17712
17713        synchronized(mPackages) {
17714            oldPackage = mPackages.get(pkgName);
17715            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
17716
17717            // don't allow upgrade to target a release SDK from a pre-release SDK
17718            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
17719                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17720            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
17721                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17722            if (oldTargetsPreRelease
17723                    && !newTargetsPreRelease
17724                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
17725                Slog.w(TAG, "Can't install package targeting released sdk");
17726                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
17727                return;
17728            }
17729
17730            ps = mSettings.mPackages.get(pkgName);
17731
17732            // verify signatures are valid
17733            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17734                if (!checkUpgradeKeySetLP(ps, pkg)) {
17735                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17736                            "New package not signed by keys specified by upgrade-keysets: "
17737                                    + pkgName);
17738                    return;
17739                }
17740            } else {
17741                // default to original signature matching
17742                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17743                        != PackageManager.SIGNATURE_MATCH) {
17744                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17745                            "New package has a different signature: " + pkgName);
17746                    return;
17747                }
17748            }
17749
17750            // don't allow a system upgrade unless the upgrade hash matches
17751            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17752                byte[] digestBytes = null;
17753                try {
17754                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17755                    updateDigest(digest, new File(pkg.baseCodePath));
17756                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17757                        for (String path : pkg.splitCodePaths) {
17758                            updateDigest(digest, new File(path));
17759                        }
17760                    }
17761                    digestBytes = digest.digest();
17762                } catch (NoSuchAlgorithmException | IOException e) {
17763                    res.setError(INSTALL_FAILED_INVALID_APK,
17764                            "Could not compute hash: " + pkgName);
17765                    return;
17766                }
17767                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17768                    res.setError(INSTALL_FAILED_INVALID_APK,
17769                            "New package fails restrict-update check: " + pkgName);
17770                    return;
17771                }
17772                // retain upgrade restriction
17773                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17774            }
17775
17776            // Check for shared user id changes
17777            String invalidPackageName =
17778                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17779            if (invalidPackageName != null) {
17780                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17781                        "Package " + invalidPackageName + " tried to change user "
17782                                + oldPackage.mSharedUserId);
17783                return;
17784            }
17785
17786            // In case of rollback, remember per-user/profile install state
17787            allUsers = sUserManager.getUserIds();
17788            installedUsers = ps.queryInstalledUsers(allUsers, true);
17789
17790            // don't allow an upgrade from full to ephemeral
17791            if (isInstantApp) {
17792                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17793                    for (int currentUser : allUsers) {
17794                        if (!ps.getInstantApp(currentUser)) {
17795                            // can't downgrade from full to instant
17796                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17797                                    + " for user: " + currentUser);
17798                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17799                            return;
17800                        }
17801                    }
17802                } else if (!ps.getInstantApp(user.getIdentifier())) {
17803                    // can't downgrade from full to instant
17804                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17805                            + " for user: " + user.getIdentifier());
17806                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17807                    return;
17808                }
17809            }
17810        }
17811
17812        // Update what is removed
17813        res.removedInfo = new PackageRemovedInfo(this);
17814        res.removedInfo.uid = oldPackage.applicationInfo.uid;
17815        res.removedInfo.removedPackage = oldPackage.packageName;
17816        res.removedInfo.installerPackageName = ps.installerPackageName;
17817        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17818        res.removedInfo.isUpdate = true;
17819        res.removedInfo.origUsers = installedUsers;
17820        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17821        for (int i = 0; i < installedUsers.length; i++) {
17822            final int userId = installedUsers[i];
17823            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17824        }
17825
17826        final int childCount = (oldPackage.childPackages != null)
17827                ? oldPackage.childPackages.size() : 0;
17828        for (int i = 0; i < childCount; i++) {
17829            boolean childPackageUpdated = false;
17830            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17831            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17832            if (res.addedChildPackages != null) {
17833                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17834                if (childRes != null) {
17835                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17836                    childRes.removedInfo.removedPackage = childPkg.packageName;
17837                    if (childPs != null) {
17838                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17839                    }
17840                    childRes.removedInfo.isUpdate = true;
17841                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17842                    childPackageUpdated = true;
17843                }
17844            }
17845            if (!childPackageUpdated) {
17846                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17847                childRemovedRes.removedPackage = childPkg.packageName;
17848                if (childPs != null) {
17849                    childRemovedRes.installerPackageName = childPs.installerPackageName;
17850                }
17851                childRemovedRes.isUpdate = false;
17852                childRemovedRes.dataRemoved = true;
17853                synchronized (mPackages) {
17854                    if (childPs != null) {
17855                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17856                    }
17857                }
17858                if (res.removedInfo.removedChildPackages == null) {
17859                    res.removedInfo.removedChildPackages = new ArrayMap<>();
17860                }
17861                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17862            }
17863        }
17864
17865        boolean sysPkg = (isSystemApp(oldPackage));
17866        if (sysPkg) {
17867            // Set the system/privileged/oem flags as needed
17868            final boolean privileged =
17869                    (oldPackage.applicationInfo.privateFlags
17870                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17871            final boolean oem =
17872                    (oldPackage.applicationInfo.privateFlags
17873                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
17874            final int systemPolicyFlags = policyFlags
17875                    | PackageParser.PARSE_IS_SYSTEM
17876                    | (privileged ? PARSE_IS_PRIVILEGED : 0)
17877                    | (oem ? PARSE_IS_OEM : 0);
17878
17879            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17880                    user, allUsers, installerPackageName, res, installReason);
17881        } else {
17882            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17883                    user, allUsers, installerPackageName, res, installReason);
17884        }
17885    }
17886
17887    @Override
17888    public List<String> getPreviousCodePaths(String packageName) {
17889        final int callingUid = Binder.getCallingUid();
17890        final List<String> result = new ArrayList<>();
17891        if (getInstantAppPackageName(callingUid) != null) {
17892            return result;
17893        }
17894        final PackageSetting ps = mSettings.mPackages.get(packageName);
17895        if (ps != null
17896                && ps.oldCodePaths != null
17897                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17898            result.addAll(ps.oldCodePaths);
17899        }
17900        return result;
17901    }
17902
17903    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17904            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17905            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17906            int installReason) {
17907        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17908                + deletedPackage);
17909
17910        String pkgName = deletedPackage.packageName;
17911        boolean deletedPkg = true;
17912        boolean addedPkg = false;
17913        boolean updatedSettings = false;
17914        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17915        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17916                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17917
17918        final long origUpdateTime = (pkg.mExtras != null)
17919                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17920
17921        // First delete the existing package while retaining the data directory
17922        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17923                res.removedInfo, true, pkg)) {
17924            // If the existing package wasn't successfully deleted
17925            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17926            deletedPkg = false;
17927        } else {
17928            // Successfully deleted the old package; proceed with replace.
17929
17930            // If deleted package lived in a container, give users a chance to
17931            // relinquish resources before killing.
17932            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17933                if (DEBUG_INSTALL) {
17934                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17935                }
17936                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17937                final ArrayList<String> pkgList = new ArrayList<String>(1);
17938                pkgList.add(deletedPackage.applicationInfo.packageName);
17939                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17940            }
17941
17942            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17943                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17944            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17945
17946            try {
17947                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17948                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17949                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17950                        installReason);
17951
17952                // Update the in-memory copy of the previous code paths.
17953                PackageSetting ps = mSettings.mPackages.get(pkgName);
17954                if (!killApp) {
17955                    if (ps.oldCodePaths == null) {
17956                        ps.oldCodePaths = new ArraySet<>();
17957                    }
17958                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17959                    if (deletedPackage.splitCodePaths != null) {
17960                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17961                    }
17962                } else {
17963                    ps.oldCodePaths = null;
17964                }
17965                if (ps.childPackageNames != null) {
17966                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17967                        final String childPkgName = ps.childPackageNames.get(i);
17968                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17969                        childPs.oldCodePaths = ps.oldCodePaths;
17970                    }
17971                }
17972                // set instant app status, but, only if it's explicitly specified
17973                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17974                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17975                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17976                prepareAppDataAfterInstallLIF(newPackage);
17977                addedPkg = true;
17978                mDexManager.notifyPackageUpdated(newPackage.packageName,
17979                        newPackage.baseCodePath, newPackage.splitCodePaths);
17980            } catch (PackageManagerException e) {
17981                res.setError("Package couldn't be installed in " + pkg.codePath, e);
17982            }
17983        }
17984
17985        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17986            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17987
17988            // Revert all internal state mutations and added folders for the failed install
17989            if (addedPkg) {
17990                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17991                        res.removedInfo, true, null);
17992            }
17993
17994            // Restore the old package
17995            if (deletedPkg) {
17996                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17997                File restoreFile = new File(deletedPackage.codePath);
17998                // Parse old package
17999                boolean oldExternal = isExternal(deletedPackage);
18000                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
18001                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
18002                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
18003                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
18004                try {
18005                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
18006                            null);
18007                } catch (PackageManagerException e) {
18008                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
18009                            + e.getMessage());
18010                    return;
18011                }
18012
18013                synchronized (mPackages) {
18014                    // Ensure the installer package name up to date
18015                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
18016
18017                    // Update permissions for restored package
18018                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
18019
18020                    mSettings.writeLPr();
18021                }
18022
18023                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
18024            }
18025        } else {
18026            synchronized (mPackages) {
18027                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
18028                if (ps != null) {
18029                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18030                    if (res.removedInfo.removedChildPackages != null) {
18031                        final int childCount = res.removedInfo.removedChildPackages.size();
18032                        // Iterate in reverse as we may modify the collection
18033                        for (int i = childCount - 1; i >= 0; i--) {
18034                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
18035                            if (res.addedChildPackages.containsKey(childPackageName)) {
18036                                res.removedInfo.removedChildPackages.removeAt(i);
18037                            } else {
18038                                PackageRemovedInfo childInfo = res.removedInfo
18039                                        .removedChildPackages.valueAt(i);
18040                                childInfo.removedForAllUsers = mPackages.get(
18041                                        childInfo.removedPackage) == null;
18042                            }
18043                        }
18044                    }
18045                }
18046            }
18047        }
18048    }
18049
18050    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
18051            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
18052            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
18053            int installReason) {
18054        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
18055                + ", old=" + deletedPackage);
18056
18057        final boolean disabledSystem;
18058
18059        // Remove existing system package
18060        removePackageLI(deletedPackage, true);
18061
18062        synchronized (mPackages) {
18063            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
18064        }
18065        if (!disabledSystem) {
18066            // We didn't need to disable the .apk as a current system package,
18067            // which means we are replacing another update that is already
18068            // installed.  We need to make sure to delete the older one's .apk.
18069            res.removedInfo.args = createInstallArgsForExisting(0,
18070                    deletedPackage.applicationInfo.getCodePath(),
18071                    deletedPackage.applicationInfo.getResourcePath(),
18072                    getAppDexInstructionSets(deletedPackage.applicationInfo));
18073        } else {
18074            res.removedInfo.args = null;
18075        }
18076
18077        // Successfully disabled the old package. Now proceed with re-installation
18078        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
18079                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18080        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
18081
18082        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18083        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
18084                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
18085
18086        PackageParser.Package newPackage = null;
18087        try {
18088            // Add the package to the internal data structures
18089            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
18090
18091            // Set the update and install times
18092            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
18093            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
18094                    System.currentTimeMillis());
18095
18096            // Update the package dynamic state if succeeded
18097            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18098                // Now that the install succeeded make sure we remove data
18099                // directories for any child package the update removed.
18100                final int deletedChildCount = (deletedPackage.childPackages != null)
18101                        ? deletedPackage.childPackages.size() : 0;
18102                final int newChildCount = (newPackage.childPackages != null)
18103                        ? newPackage.childPackages.size() : 0;
18104                for (int i = 0; i < deletedChildCount; i++) {
18105                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
18106                    boolean childPackageDeleted = true;
18107                    for (int j = 0; j < newChildCount; j++) {
18108                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
18109                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
18110                            childPackageDeleted = false;
18111                            break;
18112                        }
18113                    }
18114                    if (childPackageDeleted) {
18115                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
18116                                deletedChildPkg.packageName);
18117                        if (ps != null && res.removedInfo.removedChildPackages != null) {
18118                            PackageRemovedInfo removedChildRes = res.removedInfo
18119                                    .removedChildPackages.get(deletedChildPkg.packageName);
18120                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
18121                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
18122                        }
18123                    }
18124                }
18125
18126                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
18127                        installReason);
18128                prepareAppDataAfterInstallLIF(newPackage);
18129
18130                mDexManager.notifyPackageUpdated(newPackage.packageName,
18131                            newPackage.baseCodePath, newPackage.splitCodePaths);
18132            }
18133        } catch (PackageManagerException e) {
18134            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
18135            res.setError("Package couldn't be installed in " + pkg.codePath, e);
18136        }
18137
18138        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
18139            // Re installation failed. Restore old information
18140            // Remove new pkg information
18141            if (newPackage != null) {
18142                removeInstalledPackageLI(newPackage, true);
18143            }
18144            // Add back the old system package
18145            try {
18146                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
18147            } catch (PackageManagerException e) {
18148                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
18149            }
18150
18151            synchronized (mPackages) {
18152                if (disabledSystem) {
18153                    enableSystemPackageLPw(deletedPackage);
18154                }
18155
18156                // Ensure the installer package name up to date
18157                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
18158
18159                // Update permissions for restored package
18160                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
18161
18162                mSettings.writeLPr();
18163            }
18164
18165            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
18166                    + " after failed upgrade");
18167        }
18168    }
18169
18170    /**
18171     * Checks whether the parent or any of the child packages have a change shared
18172     * user. For a package to be a valid update the shred users of the parent and
18173     * the children should match. We may later support changing child shared users.
18174     * @param oldPkg The updated package.
18175     * @param newPkg The update package.
18176     * @return The shared user that change between the versions.
18177     */
18178    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
18179            PackageParser.Package newPkg) {
18180        // Check parent shared user
18181        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
18182            return newPkg.packageName;
18183        }
18184        // Check child shared users
18185        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
18186        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
18187        for (int i = 0; i < newChildCount; i++) {
18188            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
18189            // If this child was present, did it have the same shared user?
18190            for (int j = 0; j < oldChildCount; j++) {
18191                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
18192                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
18193                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
18194                    return newChildPkg.packageName;
18195                }
18196            }
18197        }
18198        return null;
18199    }
18200
18201    private void removeNativeBinariesLI(PackageSetting ps) {
18202        // Remove the lib path for the parent package
18203        if (ps != null) {
18204            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
18205            // Remove the lib path for the child packages
18206            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18207            for (int i = 0; i < childCount; i++) {
18208                PackageSetting childPs = null;
18209                synchronized (mPackages) {
18210                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18211                }
18212                if (childPs != null) {
18213                    NativeLibraryHelper.removeNativeBinariesLI(childPs
18214                            .legacyNativeLibraryPathString);
18215                }
18216            }
18217        }
18218    }
18219
18220    private void enableSystemPackageLPw(PackageParser.Package pkg) {
18221        // Enable the parent package
18222        mSettings.enableSystemPackageLPw(pkg.packageName);
18223        // Enable the child packages
18224        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18225        for (int i = 0; i < childCount; i++) {
18226            PackageParser.Package childPkg = pkg.childPackages.get(i);
18227            mSettings.enableSystemPackageLPw(childPkg.packageName);
18228        }
18229    }
18230
18231    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
18232            PackageParser.Package newPkg) {
18233        // Disable the parent package (parent always replaced)
18234        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
18235        // Disable the child packages
18236        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
18237        for (int i = 0; i < childCount; i++) {
18238            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
18239            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
18240            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
18241        }
18242        return disabled;
18243    }
18244
18245    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
18246            String installerPackageName) {
18247        // Enable the parent package
18248        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
18249        // Enable the child packages
18250        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18251        for (int i = 0; i < childCount; i++) {
18252            PackageParser.Package childPkg = pkg.childPackages.get(i);
18253            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
18254        }
18255    }
18256
18257    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
18258        // Collect all used permissions in the UID
18259        ArraySet<String> usedPermissions = new ArraySet<>();
18260        final int packageCount = su.packages.size();
18261        for (int i = 0; i < packageCount; i++) {
18262            PackageSetting ps = su.packages.valueAt(i);
18263            if (ps.pkg == null) {
18264                continue;
18265            }
18266            final int requestedPermCount = ps.pkg.requestedPermissions.size();
18267            for (int j = 0; j < requestedPermCount; j++) {
18268                String permission = ps.pkg.requestedPermissions.get(j);
18269                BasePermission bp = mSettings.mPermissions.get(permission);
18270                if (bp != null) {
18271                    usedPermissions.add(permission);
18272                }
18273            }
18274        }
18275
18276        PermissionsState permissionsState = su.getPermissionsState();
18277        // Prune install permissions
18278        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
18279        final int installPermCount = installPermStates.size();
18280        for (int i = installPermCount - 1; i >= 0;  i--) {
18281            PermissionState permissionState = installPermStates.get(i);
18282            if (!usedPermissions.contains(permissionState.getName())) {
18283                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
18284                if (bp != null) {
18285                    permissionsState.revokeInstallPermission(bp);
18286                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
18287                            PackageManager.MASK_PERMISSION_FLAGS, 0);
18288                }
18289            }
18290        }
18291
18292        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
18293
18294        // Prune runtime permissions
18295        for (int userId : allUserIds) {
18296            List<PermissionState> runtimePermStates = permissionsState
18297                    .getRuntimePermissionStates(userId);
18298            final int runtimePermCount = runtimePermStates.size();
18299            for (int i = runtimePermCount - 1; i >= 0; i--) {
18300                PermissionState permissionState = runtimePermStates.get(i);
18301                if (!usedPermissions.contains(permissionState.getName())) {
18302                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
18303                    if (bp != null) {
18304                        permissionsState.revokeRuntimePermission(bp, userId);
18305                        permissionsState.updatePermissionFlags(bp, userId,
18306                                PackageManager.MASK_PERMISSION_FLAGS, 0);
18307                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
18308                                runtimePermissionChangedUserIds, userId);
18309                    }
18310                }
18311            }
18312        }
18313
18314        return runtimePermissionChangedUserIds;
18315    }
18316
18317    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
18318            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
18319        // Update the parent package setting
18320        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
18321                res, user, installReason);
18322        // Update the child packages setting
18323        final int childCount = (newPackage.childPackages != null)
18324                ? newPackage.childPackages.size() : 0;
18325        for (int i = 0; i < childCount; i++) {
18326            PackageParser.Package childPackage = newPackage.childPackages.get(i);
18327            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
18328            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
18329                    childRes.origUsers, childRes, user, installReason);
18330        }
18331    }
18332
18333    private void updateSettingsInternalLI(PackageParser.Package newPackage,
18334            String installerPackageName, int[] allUsers, int[] installedForUsers,
18335            PackageInstalledInfo res, UserHandle user, int installReason) {
18336        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
18337
18338        String pkgName = newPackage.packageName;
18339        synchronized (mPackages) {
18340            //write settings. the installStatus will be incomplete at this stage.
18341            //note that the new package setting would have already been
18342            //added to mPackages. It hasn't been persisted yet.
18343            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
18344            // TODO: Remove this write? It's also written at the end of this method
18345            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
18346            mSettings.writeLPr();
18347            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18348        }
18349
18350        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
18351        synchronized (mPackages) {
18352            updatePermissionsLPw(newPackage.packageName, newPackage,
18353                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
18354                            ? UPDATE_PERMISSIONS_ALL : 0));
18355            // For system-bundled packages, we assume that installing an upgraded version
18356            // of the package implies that the user actually wants to run that new code,
18357            // so we enable the package.
18358            PackageSetting ps = mSettings.mPackages.get(pkgName);
18359            final int userId = user.getIdentifier();
18360            if (ps != null) {
18361                if (isSystemApp(newPackage)) {
18362                    if (DEBUG_INSTALL) {
18363                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
18364                    }
18365                    // Enable system package for requested users
18366                    if (res.origUsers != null) {
18367                        for (int origUserId : res.origUsers) {
18368                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
18369                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
18370                                        origUserId, installerPackageName);
18371                            }
18372                        }
18373                    }
18374                    // Also convey the prior install/uninstall state
18375                    if (allUsers != null && installedForUsers != null) {
18376                        for (int currentUserId : allUsers) {
18377                            final boolean installed = ArrayUtils.contains(
18378                                    installedForUsers, currentUserId);
18379                            if (DEBUG_INSTALL) {
18380                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
18381                            }
18382                            ps.setInstalled(installed, currentUserId);
18383                        }
18384                        // these install state changes will be persisted in the
18385                        // upcoming call to mSettings.writeLPr().
18386                    }
18387                }
18388                // It's implied that when a user requests installation, they want the app to be
18389                // installed and enabled.
18390                if (userId != UserHandle.USER_ALL) {
18391                    ps.setInstalled(true, userId);
18392                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
18393                }
18394
18395                // When replacing an existing package, preserve the original install reason for all
18396                // users that had the package installed before.
18397                final Set<Integer> previousUserIds = new ArraySet<>();
18398                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
18399                    final int installReasonCount = res.removedInfo.installReasons.size();
18400                    for (int i = 0; i < installReasonCount; i++) {
18401                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
18402                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
18403                        ps.setInstallReason(previousInstallReason, previousUserId);
18404                        previousUserIds.add(previousUserId);
18405                    }
18406                }
18407
18408                // Set install reason for users that are having the package newly installed.
18409                if (userId == UserHandle.USER_ALL) {
18410                    for (int currentUserId : sUserManager.getUserIds()) {
18411                        if (!previousUserIds.contains(currentUserId)) {
18412                            ps.setInstallReason(installReason, currentUserId);
18413                        }
18414                    }
18415                } else if (!previousUserIds.contains(userId)) {
18416                    ps.setInstallReason(installReason, userId);
18417                }
18418                mSettings.writeKernelMappingLPr(ps);
18419            }
18420            res.name = pkgName;
18421            res.uid = newPackage.applicationInfo.uid;
18422            res.pkg = newPackage;
18423            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
18424            mSettings.setInstallerPackageName(pkgName, installerPackageName);
18425            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18426            //to update install status
18427            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
18428            mSettings.writeLPr();
18429            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18430        }
18431
18432        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18433    }
18434
18435    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
18436        try {
18437            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
18438            installPackageLI(args, res);
18439        } finally {
18440            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18441        }
18442    }
18443
18444    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
18445        final int installFlags = args.installFlags;
18446        final String installerPackageName = args.installerPackageName;
18447        final String volumeUuid = args.volumeUuid;
18448        final File tmpPackageFile = new File(args.getCodePath());
18449        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
18450        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
18451                || (args.volumeUuid != null));
18452        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
18453        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
18454        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
18455        final boolean virtualPreload =
18456                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
18457        boolean replace = false;
18458        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
18459        if (args.move != null) {
18460            // moving a complete application; perform an initial scan on the new install location
18461            scanFlags |= SCAN_INITIAL;
18462        }
18463        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
18464            scanFlags |= SCAN_DONT_KILL_APP;
18465        }
18466        if (instantApp) {
18467            scanFlags |= SCAN_AS_INSTANT_APP;
18468        }
18469        if (fullApp) {
18470            scanFlags |= SCAN_AS_FULL_APP;
18471        }
18472        if (virtualPreload) {
18473            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
18474        }
18475
18476        // Result object to be returned
18477        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18478        res.installerPackageName = installerPackageName;
18479
18480        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
18481
18482        // Sanity check
18483        if (instantApp && (forwardLocked || onExternal)) {
18484            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
18485                    + " external=" + onExternal);
18486            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
18487            return;
18488        }
18489
18490        // Retrieve PackageSettings and parse package
18491        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
18492                | PackageParser.PARSE_ENFORCE_CODE
18493                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
18494                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
18495                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
18496                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
18497        PackageParser pp = new PackageParser();
18498        pp.setSeparateProcesses(mSeparateProcesses);
18499        pp.setDisplayMetrics(mMetrics);
18500        pp.setCallback(mPackageParserCallback);
18501
18502        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
18503        final PackageParser.Package pkg;
18504        try {
18505            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
18506        } catch (PackageParserException e) {
18507            res.setError("Failed parse during installPackageLI", e);
18508            return;
18509        } finally {
18510            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18511        }
18512
18513        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
18514        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
18515            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
18516            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18517                    "Instant app package must target O");
18518            return;
18519        }
18520        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
18521            Slog.w(TAG, "Instant app package " + pkg.packageName
18522                    + " does not target targetSandboxVersion 2");
18523            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18524                    "Instant app package must use targetSanboxVersion 2");
18525            return;
18526        }
18527
18528        if (pkg.applicationInfo.isStaticSharedLibrary()) {
18529            // Static shared libraries have synthetic package names
18530            renameStaticSharedLibraryPackage(pkg);
18531
18532            // No static shared libs on external storage
18533            if (onExternal) {
18534                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
18535                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18536                        "Packages declaring static-shared libs cannot be updated");
18537                return;
18538            }
18539        }
18540
18541        // If we are installing a clustered package add results for the children
18542        if (pkg.childPackages != null) {
18543            synchronized (mPackages) {
18544                final int childCount = pkg.childPackages.size();
18545                for (int i = 0; i < childCount; i++) {
18546                    PackageParser.Package childPkg = pkg.childPackages.get(i);
18547                    PackageInstalledInfo childRes = new PackageInstalledInfo();
18548                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18549                    childRes.pkg = childPkg;
18550                    childRes.name = childPkg.packageName;
18551                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18552                    if (childPs != null) {
18553                        childRes.origUsers = childPs.queryInstalledUsers(
18554                                sUserManager.getUserIds(), true);
18555                    }
18556                    if ((mPackages.containsKey(childPkg.packageName))) {
18557                        childRes.removedInfo = new PackageRemovedInfo(this);
18558                        childRes.removedInfo.removedPackage = childPkg.packageName;
18559                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
18560                    }
18561                    if (res.addedChildPackages == null) {
18562                        res.addedChildPackages = new ArrayMap<>();
18563                    }
18564                    res.addedChildPackages.put(childPkg.packageName, childRes);
18565                }
18566            }
18567        }
18568
18569        // If package doesn't declare API override, mark that we have an install
18570        // time CPU ABI override.
18571        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
18572            pkg.cpuAbiOverride = args.abiOverride;
18573        }
18574
18575        String pkgName = res.name = pkg.packageName;
18576        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
18577            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
18578                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
18579                return;
18580            }
18581        }
18582
18583        try {
18584            // either use what we've been given or parse directly from the APK
18585            if (args.certificates != null) {
18586                try {
18587                    PackageParser.populateCertificates(pkg, args.certificates);
18588                } catch (PackageParserException e) {
18589                    // there was something wrong with the certificates we were given;
18590                    // try to pull them from the APK
18591                    PackageParser.collectCertificates(pkg, parseFlags);
18592                }
18593            } else {
18594                PackageParser.collectCertificates(pkg, parseFlags);
18595            }
18596        } catch (PackageParserException e) {
18597            res.setError("Failed collect during installPackageLI", e);
18598            return;
18599        }
18600
18601        // Get rid of all references to package scan path via parser.
18602        pp = null;
18603        String oldCodePath = null;
18604        boolean systemApp = false;
18605        synchronized (mPackages) {
18606            // Check if installing already existing package
18607            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
18608                String oldName = mSettings.getRenamedPackageLPr(pkgName);
18609                if (pkg.mOriginalPackages != null
18610                        && pkg.mOriginalPackages.contains(oldName)
18611                        && mPackages.containsKey(oldName)) {
18612                    // This package is derived from an original package,
18613                    // and this device has been updating from that original
18614                    // name.  We must continue using the original name, so
18615                    // rename the new package here.
18616                    pkg.setPackageName(oldName);
18617                    pkgName = pkg.packageName;
18618                    replace = true;
18619                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
18620                            + oldName + " pkgName=" + pkgName);
18621                } else if (mPackages.containsKey(pkgName)) {
18622                    // This package, under its official name, already exists
18623                    // on the device; we should replace it.
18624                    replace = true;
18625                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
18626                }
18627
18628                // Child packages are installed through the parent package
18629                if (pkg.parentPackage != null) {
18630                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18631                            "Package " + pkg.packageName + " is child of package "
18632                                    + pkg.parentPackage.parentPackage + ". Child packages "
18633                                    + "can be updated only through the parent package.");
18634                    return;
18635                }
18636
18637                if (replace) {
18638                    // Prevent apps opting out from runtime permissions
18639                    PackageParser.Package oldPackage = mPackages.get(pkgName);
18640                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
18641                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
18642                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
18643                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
18644                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
18645                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
18646                                        + " doesn't support runtime permissions but the old"
18647                                        + " target SDK " + oldTargetSdk + " does.");
18648                        return;
18649                    }
18650                    // Prevent apps from downgrading their targetSandbox.
18651                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
18652                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
18653                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
18654                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18655                                "Package " + pkg.packageName + " new target sandbox "
18656                                + newTargetSandbox + " is incompatible with the previous value of"
18657                                + oldTargetSandbox + ".");
18658                        return;
18659                    }
18660
18661                    // Prevent installing of child packages
18662                    if (oldPackage.parentPackage != null) {
18663                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18664                                "Package " + pkg.packageName + " is child of package "
18665                                        + oldPackage.parentPackage + ". Child packages "
18666                                        + "can be updated only through the parent package.");
18667                        return;
18668                    }
18669                }
18670            }
18671
18672            PackageSetting ps = mSettings.mPackages.get(pkgName);
18673            if (ps != null) {
18674                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
18675
18676                // Static shared libs have same package with different versions where
18677                // we internally use a synthetic package name to allow multiple versions
18678                // of the same package, therefore we need to compare signatures against
18679                // the package setting for the latest library version.
18680                PackageSetting signatureCheckPs = ps;
18681                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18682                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
18683                    if (libraryEntry != null) {
18684                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
18685                    }
18686                }
18687
18688                // Quick sanity check that we're signed correctly if updating;
18689                // we'll check this again later when scanning, but we want to
18690                // bail early here before tripping over redefined permissions.
18691                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
18692                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
18693                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
18694                                + pkg.packageName + " upgrade keys do not match the "
18695                                + "previously installed version");
18696                        return;
18697                    }
18698                } else {
18699                    try {
18700                        verifySignaturesLP(signatureCheckPs, pkg);
18701                    } catch (PackageManagerException e) {
18702                        res.setError(e.error, e.getMessage());
18703                        return;
18704                    }
18705                }
18706
18707                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
18708                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
18709                    systemApp = (ps.pkg.applicationInfo.flags &
18710                            ApplicationInfo.FLAG_SYSTEM) != 0;
18711                }
18712                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18713            }
18714
18715            int N = pkg.permissions.size();
18716            for (int i = N-1; i >= 0; i--) {
18717                PackageParser.Permission perm = pkg.permissions.get(i);
18718                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
18719
18720                // Don't allow anyone but the system to define ephemeral permissions.
18721                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
18722                        && !systemApp) {
18723                    Slog.w(TAG, "Non-System package " + pkg.packageName
18724                            + " attempting to delcare ephemeral permission "
18725                            + perm.info.name + "; Removing ephemeral.");
18726                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
18727                }
18728
18729                // Check whether the newly-scanned package wants to define an already-defined perm
18730                if (bp != null) {
18731                    // If the defining package is signed with our cert, it's okay.  This
18732                    // also includes the "updating the same package" case, of course.
18733                    // "updating same package" could also involve key-rotation.
18734                    final boolean sigsOk;
18735                    if (bp.sourcePackage.equals(pkg.packageName)
18736                            && (bp.packageSetting instanceof PackageSetting)
18737                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
18738                                    scanFlags))) {
18739                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
18740                    } else {
18741                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
18742                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18743                    }
18744                    if (!sigsOk) {
18745                        // If the owning package is the system itself, we log but allow
18746                        // install to proceed; we fail the install on all other permission
18747                        // redefinitions.
18748                        if (!bp.sourcePackage.equals("android")) {
18749                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18750                                    + pkg.packageName + " attempting to redeclare permission "
18751                                    + perm.info.name + " already owned by " + bp.sourcePackage);
18752                            res.origPermission = perm.info.name;
18753                            res.origPackage = bp.sourcePackage;
18754                            return;
18755                        } else {
18756                            Slog.w(TAG, "Package " + pkg.packageName
18757                                    + " attempting to redeclare system permission "
18758                                    + perm.info.name + "; ignoring new declaration");
18759                            pkg.permissions.remove(i);
18760                        }
18761                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18762                        // Prevent apps to change protection level to dangerous from any other
18763                        // type as this would allow a privilege escalation where an app adds a
18764                        // normal/signature permission in other app's group and later redefines
18765                        // it as dangerous leading to the group auto-grant.
18766                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18767                                == PermissionInfo.PROTECTION_DANGEROUS) {
18768                            if (bp != null && !bp.isRuntime()) {
18769                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18770                                        + "non-runtime permission " + perm.info.name
18771                                        + " to runtime; keeping old protection level");
18772                                perm.info.protectionLevel = bp.protectionLevel;
18773                            }
18774                        }
18775                    }
18776                }
18777            }
18778        }
18779
18780        if (systemApp) {
18781            if (onExternal) {
18782                // Abort update; system app can't be replaced with app on sdcard
18783                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18784                        "Cannot install updates to system apps on sdcard");
18785                return;
18786            } else if (instantApp) {
18787                // Abort update; system app can't be replaced with an instant app
18788                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18789                        "Cannot update a system app with an instant app");
18790                return;
18791            }
18792        }
18793
18794        if (args.move != null) {
18795            // We did an in-place move, so dex is ready to roll
18796            scanFlags |= SCAN_NO_DEX;
18797            scanFlags |= SCAN_MOVE;
18798
18799            synchronized (mPackages) {
18800                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18801                if (ps == null) {
18802                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18803                            "Missing settings for moved package " + pkgName);
18804                }
18805
18806                // We moved the entire application as-is, so bring over the
18807                // previously derived ABI information.
18808                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18809                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18810            }
18811
18812        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18813            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18814            scanFlags |= SCAN_NO_DEX;
18815
18816            try {
18817                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18818                    args.abiOverride : pkg.cpuAbiOverride);
18819                final boolean extractNativeLibs = !pkg.isLibrary();
18820                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18821                        extractNativeLibs, mAppLib32InstallDir);
18822            } catch (PackageManagerException pme) {
18823                Slog.e(TAG, "Error deriving application ABI", pme);
18824                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18825                return;
18826            }
18827
18828            // Shared libraries for the package need to be updated.
18829            synchronized (mPackages) {
18830                try {
18831                    updateSharedLibrariesLPr(pkg, null);
18832                } catch (PackageManagerException e) {
18833                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18834                }
18835            }
18836        }
18837
18838        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18839            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18840            return;
18841        }
18842
18843        // Verify if we need to dexopt the app.
18844        //
18845        // NOTE: it is *important* to call dexopt after doRename which will sync the
18846        // package data from PackageParser.Package and its corresponding ApplicationInfo.
18847        //
18848        // We only need to dexopt if the package meets ALL of the following conditions:
18849        //   1) it is not forward locked.
18850        //   2) it is not on on an external ASEC container.
18851        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
18852        //
18853        // Note that we do not dexopt instant apps by default. dexopt can take some time to
18854        // complete, so we skip this step during installation. Instead, we'll take extra time
18855        // the first time the instant app starts. It's preferred to do it this way to provide
18856        // continuous progress to the useur instead of mysteriously blocking somewhere in the
18857        // middle of running an instant app. The default behaviour can be overridden
18858        // via gservices.
18859        final boolean performDexopt = !forwardLocked
18860            && !pkg.applicationInfo.isExternalAsec()
18861            && (!instantApp || Global.getInt(mContext.getContentResolver(),
18862                    Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
18863
18864        if (performDexopt) {
18865            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18866            // Do not run PackageDexOptimizer through the local performDexOpt
18867            // method because `pkg` may not be in `mPackages` yet.
18868            //
18869            // Also, don't fail application installs if the dexopt step fails.
18870            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
18871                REASON_INSTALL,
18872                DexoptOptions.DEXOPT_BOOT_COMPLETE);
18873            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18874                null /* instructionSets */,
18875                getOrCreateCompilerPackageStats(pkg),
18876                mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
18877                dexoptOptions);
18878            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18879        }
18880
18881        // Notify BackgroundDexOptService that the package has been changed.
18882        // If this is an update of a package which used to fail to compile,
18883        // BackgroundDexOptService will remove it from its blacklist.
18884        // TODO: Layering violation
18885        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18886
18887        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18888
18889        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18890                "installPackageLI")) {
18891            if (replace) {
18892                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18893                    // Static libs have a synthetic package name containing the version
18894                    // and cannot be updated as an update would get a new package name,
18895                    // unless this is the exact same version code which is useful for
18896                    // development.
18897                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18898                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18899                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18900                                + "static-shared libs cannot be updated");
18901                        return;
18902                    }
18903                }
18904                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18905                        installerPackageName, res, args.installReason);
18906            } else {
18907                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18908                        args.user, installerPackageName, volumeUuid, res, args.installReason);
18909            }
18910        }
18911
18912        synchronized (mPackages) {
18913            final PackageSetting ps = mSettings.mPackages.get(pkgName);
18914            if (ps != null) {
18915                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18916                ps.setUpdateAvailable(false /*updateAvailable*/);
18917            }
18918
18919            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18920            for (int i = 0; i < childCount; i++) {
18921                PackageParser.Package childPkg = pkg.childPackages.get(i);
18922                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18923                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18924                if (childPs != null) {
18925                    childRes.newUsers = childPs.queryInstalledUsers(
18926                            sUserManager.getUserIds(), true);
18927                }
18928            }
18929
18930            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18931                updateSequenceNumberLP(ps, res.newUsers);
18932                updateInstantAppInstallerLocked(pkgName);
18933            }
18934        }
18935    }
18936
18937    private void startIntentFilterVerifications(int userId, boolean replacing,
18938            PackageParser.Package pkg) {
18939        if (mIntentFilterVerifierComponent == null) {
18940            Slog.w(TAG, "No IntentFilter verification will not be done as "
18941                    + "there is no IntentFilterVerifier available!");
18942            return;
18943        }
18944
18945        final int verifierUid = getPackageUid(
18946                mIntentFilterVerifierComponent.getPackageName(),
18947                MATCH_DEBUG_TRIAGED_MISSING,
18948                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18949
18950        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18951        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18952        mHandler.sendMessage(msg);
18953
18954        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18955        for (int i = 0; i < childCount; i++) {
18956            PackageParser.Package childPkg = pkg.childPackages.get(i);
18957            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18958            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18959            mHandler.sendMessage(msg);
18960        }
18961    }
18962
18963    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18964            PackageParser.Package pkg) {
18965        int size = pkg.activities.size();
18966        if (size == 0) {
18967            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18968                    "No activity, so no need to verify any IntentFilter!");
18969            return;
18970        }
18971
18972        final boolean hasDomainURLs = hasDomainURLs(pkg);
18973        if (!hasDomainURLs) {
18974            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18975                    "No domain URLs, so no need to verify any IntentFilter!");
18976            return;
18977        }
18978
18979        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18980                + " if any IntentFilter from the " + size
18981                + " Activities needs verification ...");
18982
18983        int count = 0;
18984        final String packageName = pkg.packageName;
18985
18986        synchronized (mPackages) {
18987            // If this is a new install and we see that we've already run verification for this
18988            // package, we have nothing to do: it means the state was restored from backup.
18989            if (!replacing) {
18990                IntentFilterVerificationInfo ivi =
18991                        mSettings.getIntentFilterVerificationLPr(packageName);
18992                if (ivi != null) {
18993                    if (DEBUG_DOMAIN_VERIFICATION) {
18994                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
18995                                + ivi.getStatusString());
18996                    }
18997                    return;
18998                }
18999            }
19000
19001            // If any filters need to be verified, then all need to be.
19002            boolean needToVerify = false;
19003            for (PackageParser.Activity a : pkg.activities) {
19004                for (ActivityIntentInfo filter : a.intents) {
19005                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
19006                        if (DEBUG_DOMAIN_VERIFICATION) {
19007                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
19008                        }
19009                        needToVerify = true;
19010                        break;
19011                    }
19012                }
19013            }
19014
19015            if (needToVerify) {
19016                final int verificationId = mIntentFilterVerificationToken++;
19017                for (PackageParser.Activity a : pkg.activities) {
19018                    for (ActivityIntentInfo filter : a.intents) {
19019                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
19020                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
19021                                    "Verification needed for IntentFilter:" + filter.toString());
19022                            mIntentFilterVerifier.addOneIntentFilterVerification(
19023                                    verifierUid, userId, verificationId, filter, packageName);
19024                            count++;
19025                        }
19026                    }
19027                }
19028            }
19029        }
19030
19031        if (count > 0) {
19032            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
19033                    + " IntentFilter verification" + (count > 1 ? "s" : "")
19034                    +  " for userId:" + userId);
19035            mIntentFilterVerifier.startVerifications(userId);
19036        } else {
19037            if (DEBUG_DOMAIN_VERIFICATION) {
19038                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
19039            }
19040        }
19041    }
19042
19043    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
19044        final ComponentName cn  = filter.activity.getComponentName();
19045        final String packageName = cn.getPackageName();
19046
19047        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
19048                packageName);
19049        if (ivi == null) {
19050            return true;
19051        }
19052        int status = ivi.getStatus();
19053        switch (status) {
19054            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
19055            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
19056                return true;
19057
19058            default:
19059                // Nothing to do
19060                return false;
19061        }
19062    }
19063
19064    private static boolean isMultiArch(ApplicationInfo info) {
19065        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
19066    }
19067
19068    private static boolean isExternal(PackageParser.Package pkg) {
19069        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
19070    }
19071
19072    private static boolean isExternal(PackageSetting ps) {
19073        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
19074    }
19075
19076    private static boolean isSystemApp(PackageParser.Package pkg) {
19077        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
19078    }
19079
19080    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
19081        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
19082    }
19083
19084    private static boolean isOemApp(PackageParser.Package pkg) {
19085        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
19086    }
19087
19088    private static boolean hasDomainURLs(PackageParser.Package pkg) {
19089        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
19090    }
19091
19092    private static boolean isSystemApp(PackageSetting ps) {
19093        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
19094    }
19095
19096    private static boolean isUpdatedSystemApp(PackageSetting ps) {
19097        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
19098    }
19099
19100    private int packageFlagsToInstallFlags(PackageSetting ps) {
19101        int installFlags = 0;
19102        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
19103            // This existing package was an external ASEC install when we have
19104            // the external flag without a UUID
19105            installFlags |= PackageManager.INSTALL_EXTERNAL;
19106        }
19107        if (ps.isForwardLocked()) {
19108            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
19109        }
19110        return installFlags;
19111    }
19112
19113    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
19114        if (isExternal(pkg)) {
19115            if (TextUtils.isEmpty(pkg.volumeUuid)) {
19116                return StorageManager.UUID_PRIMARY_PHYSICAL;
19117            } else {
19118                return pkg.volumeUuid;
19119            }
19120        } else {
19121            return StorageManager.UUID_PRIVATE_INTERNAL;
19122        }
19123    }
19124
19125    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
19126        if (isExternal(pkg)) {
19127            if (TextUtils.isEmpty(pkg.volumeUuid)) {
19128                return mSettings.getExternalVersion();
19129            } else {
19130                return mSettings.findOrCreateVersion(pkg.volumeUuid);
19131            }
19132        } else {
19133            return mSettings.getInternalVersion();
19134        }
19135    }
19136
19137    private void deleteTempPackageFiles() {
19138        final FilenameFilter filter = new FilenameFilter() {
19139            public boolean accept(File dir, String name) {
19140                return name.startsWith("vmdl") && name.endsWith(".tmp");
19141            }
19142        };
19143        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
19144            file.delete();
19145        }
19146    }
19147
19148    @Override
19149    public void deletePackageAsUser(String packageName, int versionCode,
19150            IPackageDeleteObserver observer, int userId, int flags) {
19151        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
19152                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
19153    }
19154
19155    @Override
19156    public void deletePackageVersioned(VersionedPackage versionedPackage,
19157            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
19158        final int callingUid = Binder.getCallingUid();
19159        mContext.enforceCallingOrSelfPermission(
19160                android.Manifest.permission.DELETE_PACKAGES, null);
19161        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
19162        Preconditions.checkNotNull(versionedPackage);
19163        Preconditions.checkNotNull(observer);
19164        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
19165                PackageManager.VERSION_CODE_HIGHEST,
19166                Integer.MAX_VALUE, "versionCode must be >= -1");
19167
19168        final String packageName = versionedPackage.getPackageName();
19169        final int versionCode = versionedPackage.getVersionCode();
19170        final String internalPackageName;
19171        synchronized (mPackages) {
19172            // Normalize package name to handle renamed packages and static libs
19173            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
19174                    versionedPackage.getVersionCode());
19175        }
19176
19177        final int uid = Binder.getCallingUid();
19178        if (!isOrphaned(internalPackageName)
19179                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
19180            try {
19181                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
19182                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
19183                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
19184                observer.onUserActionRequired(intent);
19185            } catch (RemoteException re) {
19186            }
19187            return;
19188        }
19189        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
19190        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
19191        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
19192            mContext.enforceCallingOrSelfPermission(
19193                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
19194                    "deletePackage for user " + userId);
19195        }
19196
19197        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
19198            try {
19199                observer.onPackageDeleted(packageName,
19200                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
19201            } catch (RemoteException re) {
19202            }
19203            return;
19204        }
19205
19206        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
19207            try {
19208                observer.onPackageDeleted(packageName,
19209                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
19210            } catch (RemoteException re) {
19211            }
19212            return;
19213        }
19214
19215        if (DEBUG_REMOVE) {
19216            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
19217                    + " deleteAllUsers: " + deleteAllUsers + " version="
19218                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
19219                    ? "VERSION_CODE_HIGHEST" : versionCode));
19220        }
19221        // Queue up an async operation since the package deletion may take a little while.
19222        mHandler.post(new Runnable() {
19223            public void run() {
19224                mHandler.removeCallbacks(this);
19225                int returnCode;
19226                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
19227                boolean doDeletePackage = true;
19228                if (ps != null) {
19229                    final boolean targetIsInstantApp =
19230                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19231                    doDeletePackage = !targetIsInstantApp
19232                            || canViewInstantApps;
19233                }
19234                if (doDeletePackage) {
19235                    if (!deleteAllUsers) {
19236                        returnCode = deletePackageX(internalPackageName, versionCode,
19237                                userId, deleteFlags);
19238                    } else {
19239                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
19240                                internalPackageName, users);
19241                        // If nobody is blocking uninstall, proceed with delete for all users
19242                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
19243                            returnCode = deletePackageX(internalPackageName, versionCode,
19244                                    userId, deleteFlags);
19245                        } else {
19246                            // Otherwise uninstall individually for users with blockUninstalls=false
19247                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
19248                            for (int userId : users) {
19249                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
19250                                    returnCode = deletePackageX(internalPackageName, versionCode,
19251                                            userId, userFlags);
19252                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
19253                                        Slog.w(TAG, "Package delete failed for user " + userId
19254                                                + ", returnCode " + returnCode);
19255                                    }
19256                                }
19257                            }
19258                            // The app has only been marked uninstalled for certain users.
19259                            // We still need to report that delete was blocked
19260                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
19261                        }
19262                    }
19263                } else {
19264                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19265                }
19266                try {
19267                    observer.onPackageDeleted(packageName, returnCode, null);
19268                } catch (RemoteException e) {
19269                    Log.i(TAG, "Observer no longer exists.");
19270                } //end catch
19271            } //end run
19272        });
19273    }
19274
19275    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
19276        if (pkg.staticSharedLibName != null) {
19277            return pkg.manifestPackageName;
19278        }
19279        return pkg.packageName;
19280    }
19281
19282    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
19283        // Handle renamed packages
19284        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
19285        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
19286
19287        // Is this a static library?
19288        SparseArray<SharedLibraryEntry> versionedLib =
19289                mStaticLibsByDeclaringPackage.get(packageName);
19290        if (versionedLib == null || versionedLib.size() <= 0) {
19291            return packageName;
19292        }
19293
19294        // Figure out which lib versions the caller can see
19295        SparseIntArray versionsCallerCanSee = null;
19296        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
19297        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
19298                && callingAppId != Process.ROOT_UID) {
19299            versionsCallerCanSee = new SparseIntArray();
19300            String libName = versionedLib.valueAt(0).info.getName();
19301            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
19302            if (uidPackages != null) {
19303                for (String uidPackage : uidPackages) {
19304                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
19305                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
19306                    if (libIdx >= 0) {
19307                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
19308                        versionsCallerCanSee.append(libVersion, libVersion);
19309                    }
19310                }
19311            }
19312        }
19313
19314        // Caller can see nothing - done
19315        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
19316            return packageName;
19317        }
19318
19319        // Find the version the caller can see and the app version code
19320        SharedLibraryEntry highestVersion = null;
19321        final int versionCount = versionedLib.size();
19322        for (int i = 0; i < versionCount; i++) {
19323            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
19324            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
19325                    libEntry.info.getVersion()) < 0) {
19326                continue;
19327            }
19328            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
19329            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
19330                if (libVersionCode == versionCode) {
19331                    return libEntry.apk;
19332                }
19333            } else if (highestVersion == null) {
19334                highestVersion = libEntry;
19335            } else if (libVersionCode  > highestVersion.info
19336                    .getDeclaringPackage().getVersionCode()) {
19337                highestVersion = libEntry;
19338            }
19339        }
19340
19341        if (highestVersion != null) {
19342            return highestVersion.apk;
19343        }
19344
19345        return packageName;
19346    }
19347
19348    boolean isCallerVerifier(int callingUid) {
19349        final int callingUserId = UserHandle.getUserId(callingUid);
19350        return mRequiredVerifierPackage != null &&
19351                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
19352    }
19353
19354    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
19355        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
19356              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19357            return true;
19358        }
19359        final int callingUserId = UserHandle.getUserId(callingUid);
19360        // If the caller installed the pkgName, then allow it to silently uninstall.
19361        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
19362            return true;
19363        }
19364
19365        // Allow package verifier to silently uninstall.
19366        if (mRequiredVerifierPackage != null &&
19367                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
19368            return true;
19369        }
19370
19371        // Allow package uninstaller to silently uninstall.
19372        if (mRequiredUninstallerPackage != null &&
19373                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
19374            return true;
19375        }
19376
19377        // Allow storage manager to silently uninstall.
19378        if (mStorageManagerPackage != null &&
19379                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
19380            return true;
19381        }
19382
19383        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
19384        // uninstall for device owner provisioning.
19385        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
19386                == PERMISSION_GRANTED) {
19387            return true;
19388        }
19389
19390        return false;
19391    }
19392
19393    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
19394        int[] result = EMPTY_INT_ARRAY;
19395        for (int userId : userIds) {
19396            if (getBlockUninstallForUser(packageName, userId)) {
19397                result = ArrayUtils.appendInt(result, userId);
19398            }
19399        }
19400        return result;
19401    }
19402
19403    @Override
19404    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
19405        final int callingUid = Binder.getCallingUid();
19406        if (getInstantAppPackageName(callingUid) != null
19407                && !isCallerSameApp(packageName, callingUid)) {
19408            return false;
19409        }
19410        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
19411    }
19412
19413    private boolean isPackageDeviceAdmin(String packageName, int userId) {
19414        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
19415                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
19416        try {
19417            if (dpm != null) {
19418                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
19419                        /* callingUserOnly =*/ false);
19420                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
19421                        : deviceOwnerComponentName.getPackageName();
19422                // Does the package contains the device owner?
19423                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
19424                // this check is probably not needed, since DO should be registered as a device
19425                // admin on some user too. (Original bug for this: b/17657954)
19426                if (packageName.equals(deviceOwnerPackageName)) {
19427                    return true;
19428                }
19429                // Does it contain a device admin for any user?
19430                int[] users;
19431                if (userId == UserHandle.USER_ALL) {
19432                    users = sUserManager.getUserIds();
19433                } else {
19434                    users = new int[]{userId};
19435                }
19436                for (int i = 0; i < users.length; ++i) {
19437                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
19438                        return true;
19439                    }
19440                }
19441            }
19442        } catch (RemoteException e) {
19443        }
19444        return false;
19445    }
19446
19447    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
19448        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
19449    }
19450
19451    /**
19452     *  This method is an internal method that could be get invoked either
19453     *  to delete an installed package or to clean up a failed installation.
19454     *  After deleting an installed package, a broadcast is sent to notify any
19455     *  listeners that the package has been removed. For cleaning up a failed
19456     *  installation, the broadcast is not necessary since the package's
19457     *  installation wouldn't have sent the initial broadcast either
19458     *  The key steps in deleting a package are
19459     *  deleting the package information in internal structures like mPackages,
19460     *  deleting the packages base directories through installd
19461     *  updating mSettings to reflect current status
19462     *  persisting settings for later use
19463     *  sending a broadcast if necessary
19464     */
19465    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
19466        final PackageRemovedInfo info = new PackageRemovedInfo(this);
19467        final boolean res;
19468
19469        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
19470                ? UserHandle.USER_ALL : userId;
19471
19472        if (isPackageDeviceAdmin(packageName, removeUser)) {
19473            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
19474            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
19475        }
19476
19477        PackageSetting uninstalledPs = null;
19478        PackageParser.Package pkg = null;
19479
19480        // for the uninstall-updates case and restricted profiles, remember the per-
19481        // user handle installed state
19482        int[] allUsers;
19483        synchronized (mPackages) {
19484            uninstalledPs = mSettings.mPackages.get(packageName);
19485            if (uninstalledPs == null) {
19486                Slog.w(TAG, "Not removing non-existent package " + packageName);
19487                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19488            }
19489
19490            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
19491                    && uninstalledPs.versionCode != versionCode) {
19492                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
19493                        + uninstalledPs.versionCode + " != " + versionCode);
19494                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19495            }
19496
19497            // Static shared libs can be declared by any package, so let us not
19498            // allow removing a package if it provides a lib others depend on.
19499            pkg = mPackages.get(packageName);
19500
19501            allUsers = sUserManager.getUserIds();
19502
19503            if (pkg != null && pkg.staticSharedLibName != null) {
19504                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
19505                        pkg.staticSharedLibVersion);
19506                if (libEntry != null) {
19507                    for (int currUserId : allUsers) {
19508                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
19509                            continue;
19510                        }
19511                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
19512                                libEntry.info, 0, currUserId);
19513                        if (!ArrayUtils.isEmpty(libClientPackages)) {
19514                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
19515                                    + " hosting lib " + libEntry.info.getName() + " version "
19516                                    + libEntry.info.getVersion() + " used by " + libClientPackages
19517                                    + " for user " + currUserId);
19518                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
19519                        }
19520                    }
19521                }
19522            }
19523
19524            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
19525        }
19526
19527        final int freezeUser;
19528        if (isUpdatedSystemApp(uninstalledPs)
19529                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
19530            // We're downgrading a system app, which will apply to all users, so
19531            // freeze them all during the downgrade
19532            freezeUser = UserHandle.USER_ALL;
19533        } else {
19534            freezeUser = removeUser;
19535        }
19536
19537        synchronized (mInstallLock) {
19538            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
19539            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
19540                    deleteFlags, "deletePackageX")) {
19541                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
19542                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
19543            }
19544            synchronized (mPackages) {
19545                if (res) {
19546                    if (pkg != null) {
19547                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
19548                    }
19549                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
19550                    updateInstantAppInstallerLocked(packageName);
19551                }
19552            }
19553        }
19554
19555        if (res) {
19556            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
19557            info.sendPackageRemovedBroadcasts(killApp);
19558            info.sendSystemPackageUpdatedBroadcasts();
19559            info.sendSystemPackageAppearedBroadcasts();
19560        }
19561        // Force a gc here.
19562        Runtime.getRuntime().gc();
19563        // Delete the resources here after sending the broadcast to let
19564        // other processes clean up before deleting resources.
19565        if (info.args != null) {
19566            synchronized (mInstallLock) {
19567                info.args.doPostDeleteLI(true);
19568            }
19569        }
19570
19571        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19572    }
19573
19574    static class PackageRemovedInfo {
19575        final PackageSender packageSender;
19576        String removedPackage;
19577        String installerPackageName;
19578        int uid = -1;
19579        int removedAppId = -1;
19580        int[] origUsers;
19581        int[] removedUsers = null;
19582        int[] broadcastUsers = null;
19583        SparseArray<Integer> installReasons;
19584        boolean isRemovedPackageSystemUpdate = false;
19585        boolean isUpdate;
19586        boolean dataRemoved;
19587        boolean removedForAllUsers;
19588        boolean isStaticSharedLib;
19589        // Clean up resources deleted packages.
19590        InstallArgs args = null;
19591        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
19592        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
19593
19594        PackageRemovedInfo(PackageSender packageSender) {
19595            this.packageSender = packageSender;
19596        }
19597
19598        void sendPackageRemovedBroadcasts(boolean killApp) {
19599            sendPackageRemovedBroadcastInternal(killApp);
19600            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
19601            for (int i = 0; i < childCount; i++) {
19602                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19603                childInfo.sendPackageRemovedBroadcastInternal(killApp);
19604            }
19605        }
19606
19607        void sendSystemPackageUpdatedBroadcasts() {
19608            if (isRemovedPackageSystemUpdate) {
19609                sendSystemPackageUpdatedBroadcastsInternal();
19610                final int childCount = (removedChildPackages != null)
19611                        ? removedChildPackages.size() : 0;
19612                for (int i = 0; i < childCount; i++) {
19613                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19614                    if (childInfo.isRemovedPackageSystemUpdate) {
19615                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
19616                    }
19617                }
19618            }
19619        }
19620
19621        void sendSystemPackageAppearedBroadcasts() {
19622            final int packageCount = (appearedChildPackages != null)
19623                    ? appearedChildPackages.size() : 0;
19624            for (int i = 0; i < packageCount; i++) {
19625                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
19626                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
19627                    true /*sendBootCompleted*/, false /*startReceiver*/,
19628                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
19629            }
19630        }
19631
19632        private void sendSystemPackageUpdatedBroadcastsInternal() {
19633            Bundle extras = new Bundle(2);
19634            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
19635            extras.putBoolean(Intent.EXTRA_REPLACING, true);
19636            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19637                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19638            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19639                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19640            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
19641                null, null, 0, removedPackage, null, null);
19642            if (installerPackageName != null) {
19643                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19644                        removedPackage, extras, 0 /*flags*/,
19645                        installerPackageName, null, null);
19646                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19647                        removedPackage, extras, 0 /*flags*/,
19648                        installerPackageName, null, null);
19649            }
19650        }
19651
19652        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
19653            // Don't send static shared library removal broadcasts as these
19654            // libs are visible only the the apps that depend on them an one
19655            // cannot remove the library if it has a dependency.
19656            if (isStaticSharedLib) {
19657                return;
19658            }
19659            Bundle extras = new Bundle(2);
19660            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
19661            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
19662            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
19663            if (isUpdate || isRemovedPackageSystemUpdate) {
19664                extras.putBoolean(Intent.EXTRA_REPLACING, true);
19665            }
19666            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
19667            if (removedPackage != null) {
19668                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19669                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
19670                if (installerPackageName != null) {
19671                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19672                            removedPackage, extras, 0 /*flags*/,
19673                            installerPackageName, null, broadcastUsers);
19674                }
19675                if (dataRemoved && !isRemovedPackageSystemUpdate) {
19676                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
19677                        removedPackage, extras,
19678                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19679                        null, null, broadcastUsers);
19680                }
19681            }
19682            if (removedAppId >= 0) {
19683                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
19684                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19685                    null, null, broadcastUsers);
19686            }
19687        }
19688
19689        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
19690            removedUsers = userIds;
19691            if (removedUsers == null) {
19692                broadcastUsers = null;
19693                return;
19694            }
19695
19696            broadcastUsers = EMPTY_INT_ARRAY;
19697            for (int i = userIds.length - 1; i >= 0; --i) {
19698                final int userId = userIds[i];
19699                if (deletedPackageSetting.getInstantApp(userId)) {
19700                    continue;
19701                }
19702                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
19703            }
19704        }
19705    }
19706
19707    /*
19708     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
19709     * flag is not set, the data directory is removed as well.
19710     * make sure this flag is set for partially installed apps. If not its meaningless to
19711     * delete a partially installed application.
19712     */
19713    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
19714            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
19715        String packageName = ps.name;
19716        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
19717        // Retrieve object to delete permissions for shared user later on
19718        final PackageParser.Package deletedPkg;
19719        final PackageSetting deletedPs;
19720        // reader
19721        synchronized (mPackages) {
19722            deletedPkg = mPackages.get(packageName);
19723            deletedPs = mSettings.mPackages.get(packageName);
19724            if (outInfo != null) {
19725                outInfo.removedPackage = packageName;
19726                outInfo.installerPackageName = ps.installerPackageName;
19727                outInfo.isStaticSharedLib = deletedPkg != null
19728                        && deletedPkg.staticSharedLibName != null;
19729                outInfo.populateUsers(deletedPs == null ? null
19730                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
19731            }
19732        }
19733
19734        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
19735
19736        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
19737            final PackageParser.Package resolvedPkg;
19738            if (deletedPkg != null) {
19739                resolvedPkg = deletedPkg;
19740            } else {
19741                // We don't have a parsed package when it lives on an ejected
19742                // adopted storage device, so fake something together
19743                resolvedPkg = new PackageParser.Package(ps.name);
19744                resolvedPkg.setVolumeUuid(ps.volumeUuid);
19745            }
19746            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
19747                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19748            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
19749            if (outInfo != null) {
19750                outInfo.dataRemoved = true;
19751            }
19752            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
19753        }
19754
19755        int removedAppId = -1;
19756
19757        // writer
19758        synchronized (mPackages) {
19759            boolean installedStateChanged = false;
19760            if (deletedPs != null) {
19761                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
19762                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
19763                    clearDefaultBrowserIfNeeded(packageName);
19764                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
19765                    removedAppId = mSettings.removePackageLPw(packageName);
19766                    if (outInfo != null) {
19767                        outInfo.removedAppId = removedAppId;
19768                    }
19769                    updatePermissionsLPw(deletedPs.name, null, 0);
19770                    if (deletedPs.sharedUser != null) {
19771                        // Remove permissions associated with package. Since runtime
19772                        // permissions are per user we have to kill the removed package
19773                        // or packages running under the shared user of the removed
19774                        // package if revoking the permissions requested only by the removed
19775                        // package is successful and this causes a change in gids.
19776                        for (int userId : UserManagerService.getInstance().getUserIds()) {
19777                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19778                                    userId);
19779                            if (userIdToKill == UserHandle.USER_ALL
19780                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
19781                                // If gids changed for this user, kill all affected packages.
19782                                mHandler.post(new Runnable() {
19783                                    @Override
19784                                    public void run() {
19785                                        // This has to happen with no lock held.
19786                                        killApplication(deletedPs.name, deletedPs.appId,
19787                                                KILL_APP_REASON_GIDS_CHANGED);
19788                                    }
19789                                });
19790                                break;
19791                            }
19792                        }
19793                    }
19794                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19795                }
19796                // make sure to preserve per-user disabled state if this removal was just
19797                // a downgrade of a system app to the factory package
19798                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19799                    if (DEBUG_REMOVE) {
19800                        Slog.d(TAG, "Propagating install state across downgrade");
19801                    }
19802                    for (int userId : allUserHandles) {
19803                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19804                        if (DEBUG_REMOVE) {
19805                            Slog.d(TAG, "    user " + userId + " => " + installed);
19806                        }
19807                        if (installed != ps.getInstalled(userId)) {
19808                            installedStateChanged = true;
19809                        }
19810                        ps.setInstalled(installed, userId);
19811                    }
19812                }
19813            }
19814            // can downgrade to reader
19815            if (writeSettings) {
19816                // Save settings now
19817                mSettings.writeLPr();
19818            }
19819            if (installedStateChanged) {
19820                mSettings.writeKernelMappingLPr(ps);
19821            }
19822        }
19823        if (removedAppId != -1) {
19824            // A user ID was deleted here. Go through all users and remove it
19825            // from KeyStore.
19826            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19827        }
19828    }
19829
19830    static boolean locationIsPrivileged(File path) {
19831        try {
19832            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19833                    .getCanonicalPath();
19834            return path.getCanonicalPath().startsWith(privilegedAppDir);
19835        } catch (IOException e) {
19836            Slog.e(TAG, "Unable to access code path " + path);
19837        }
19838        return false;
19839    }
19840
19841    static boolean locationIsOem(File path) {
19842        try {
19843            return path.getCanonicalPath().startsWith(
19844                    Environment.getOemDirectory().getCanonicalPath());
19845        } catch (IOException e) {
19846            Slog.e(TAG, "Unable to access code path " + path);
19847        }
19848        return false;
19849    }
19850
19851    /*
19852     * Tries to delete system package.
19853     */
19854    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19855            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19856            boolean writeSettings) {
19857        if (deletedPs.parentPackageName != null) {
19858            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19859            return false;
19860        }
19861
19862        final boolean applyUserRestrictions
19863                = (allUserHandles != null) && (outInfo.origUsers != null);
19864        final PackageSetting disabledPs;
19865        // Confirm if the system package has been updated
19866        // An updated system app can be deleted. This will also have to restore
19867        // the system pkg from system partition
19868        // reader
19869        synchronized (mPackages) {
19870            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19871        }
19872
19873        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19874                + " disabledPs=" + disabledPs);
19875
19876        if (disabledPs == null) {
19877            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19878            return false;
19879        } else if (DEBUG_REMOVE) {
19880            Slog.d(TAG, "Deleting system pkg from data partition");
19881        }
19882
19883        if (DEBUG_REMOVE) {
19884            if (applyUserRestrictions) {
19885                Slog.d(TAG, "Remembering install states:");
19886                for (int userId : allUserHandles) {
19887                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19888                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
19889                }
19890            }
19891        }
19892
19893        // Delete the updated package
19894        outInfo.isRemovedPackageSystemUpdate = true;
19895        if (outInfo.removedChildPackages != null) {
19896            final int childCount = (deletedPs.childPackageNames != null)
19897                    ? deletedPs.childPackageNames.size() : 0;
19898            for (int i = 0; i < childCount; i++) {
19899                String childPackageName = deletedPs.childPackageNames.get(i);
19900                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19901                        .contains(childPackageName)) {
19902                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19903                            childPackageName);
19904                    if (childInfo != null) {
19905                        childInfo.isRemovedPackageSystemUpdate = true;
19906                    }
19907                }
19908            }
19909        }
19910
19911        if (disabledPs.versionCode < deletedPs.versionCode) {
19912            // Delete data for downgrades
19913            flags &= ~PackageManager.DELETE_KEEP_DATA;
19914        } else {
19915            // Preserve data by setting flag
19916            flags |= PackageManager.DELETE_KEEP_DATA;
19917        }
19918
19919        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19920                outInfo, writeSettings, disabledPs.pkg);
19921        if (!ret) {
19922            return false;
19923        }
19924
19925        // writer
19926        synchronized (mPackages) {
19927            // NOTE: The system package always needs to be enabled; even if it's for
19928            // a compressed stub. If we don't, installing the system package fails
19929            // during scan [scanning checks the disabled packages]. We will reverse
19930            // this later, after we've "installed" the stub.
19931            // Reinstate the old system package
19932            enableSystemPackageLPw(disabledPs.pkg);
19933            // Remove any native libraries from the upgraded package.
19934            removeNativeBinariesLI(deletedPs);
19935        }
19936
19937        // Install the system package
19938        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19939        try {
19940            installPackageFromSystemLIF(disabledPs.codePath, false /*isPrivileged*/, allUserHandles,
19941                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
19942        } catch (PackageManagerException e) {
19943            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19944                    + e.getMessage());
19945            return false;
19946        } finally {
19947            if (disabledPs.pkg.isStub) {
19948                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
19949            }
19950        }
19951        return true;
19952    }
19953
19954    /**
19955     * Installs a package that's already on the system partition.
19956     */
19957    private PackageParser.Package installPackageFromSystemLIF(@NonNull File codePath,
19958            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
19959            @Nullable PermissionsState origPermissionState, boolean writeSettings)
19960                    throws PackageManagerException {
19961        int parseFlags = mDefParseFlags
19962                | PackageParser.PARSE_MUST_BE_APK
19963                | PackageParser.PARSE_IS_SYSTEM
19964                | PackageParser.PARSE_IS_SYSTEM_DIR;
19965        if (isPrivileged || locationIsPrivileged(codePath)) {
19966            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19967        }
19968        if (locationIsOem(codePath)) {
19969            parseFlags |= PackageParser.PARSE_IS_OEM;
19970        }
19971
19972        final PackageParser.Package newPkg =
19973                scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/, 0 /*currentTime*/, null);
19974
19975        try {
19976            // update shared libraries for the newly re-installed system package
19977            updateSharedLibrariesLPr(newPkg, null);
19978        } catch (PackageManagerException e) {
19979            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19980        }
19981
19982        prepareAppDataAfterInstallLIF(newPkg);
19983
19984        // writer
19985        synchronized (mPackages) {
19986            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19987
19988            // Propagate the permissions state as we do not want to drop on the floor
19989            // runtime permissions. The update permissions method below will take
19990            // care of removing obsolete permissions and grant install permissions.
19991            if (origPermissionState != null) {
19992                ps.getPermissionsState().copyFrom(origPermissionState);
19993            }
19994            updatePermissionsLPw(newPkg.packageName, newPkg,
19995                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19996
19997            final boolean applyUserRestrictions
19998                    = (allUserHandles != null) && (origUserHandles != null);
19999            if (applyUserRestrictions) {
20000                boolean installedStateChanged = false;
20001                if (DEBUG_REMOVE) {
20002                    Slog.d(TAG, "Propagating install state across reinstall");
20003                }
20004                for (int userId : allUserHandles) {
20005                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
20006                    if (DEBUG_REMOVE) {
20007                        Slog.d(TAG, "    user " + userId + " => " + installed);
20008                    }
20009                    if (installed != ps.getInstalled(userId)) {
20010                        installedStateChanged = true;
20011                    }
20012                    ps.setInstalled(installed, userId);
20013
20014                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20015                }
20016                // Regardless of writeSettings we need to ensure that this restriction
20017                // state propagation is persisted
20018                mSettings.writeAllUsersPackageRestrictionsLPr();
20019                if (installedStateChanged) {
20020                    mSettings.writeKernelMappingLPr(ps);
20021                }
20022            }
20023            // can downgrade to reader here
20024            if (writeSettings) {
20025                mSettings.writeLPr();
20026            }
20027        }
20028        return newPkg;
20029    }
20030
20031    private boolean deleteInstalledPackageLIF(PackageSetting ps,
20032            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
20033            PackageRemovedInfo outInfo, boolean writeSettings,
20034            PackageParser.Package replacingPackage) {
20035        synchronized (mPackages) {
20036            if (outInfo != null) {
20037                outInfo.uid = ps.appId;
20038            }
20039
20040            if (outInfo != null && outInfo.removedChildPackages != null) {
20041                final int childCount = (ps.childPackageNames != null)
20042                        ? ps.childPackageNames.size() : 0;
20043                for (int i = 0; i < childCount; i++) {
20044                    String childPackageName = ps.childPackageNames.get(i);
20045                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
20046                    if (childPs == null) {
20047                        return false;
20048                    }
20049                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
20050                            childPackageName);
20051                    if (childInfo != null) {
20052                        childInfo.uid = childPs.appId;
20053                    }
20054                }
20055            }
20056        }
20057
20058        // Delete package data from internal structures and also remove data if flag is set
20059        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
20060
20061        // Delete the child packages data
20062        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
20063        for (int i = 0; i < childCount; i++) {
20064            PackageSetting childPs;
20065            synchronized (mPackages) {
20066                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
20067            }
20068            if (childPs != null) {
20069                PackageRemovedInfo childOutInfo = (outInfo != null
20070                        && outInfo.removedChildPackages != null)
20071                        ? outInfo.removedChildPackages.get(childPs.name) : null;
20072                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
20073                        && (replacingPackage != null
20074                        && !replacingPackage.hasChildPackage(childPs.name))
20075                        ? flags & ~DELETE_KEEP_DATA : flags;
20076                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
20077                        deleteFlags, writeSettings);
20078            }
20079        }
20080
20081        // Delete application code and resources only for parent packages
20082        if (ps.parentPackageName == null) {
20083            if (deleteCodeAndResources && (outInfo != null)) {
20084                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
20085                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
20086                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
20087            }
20088        }
20089
20090        return true;
20091    }
20092
20093    @Override
20094    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
20095            int userId) {
20096        mContext.enforceCallingOrSelfPermission(
20097                android.Manifest.permission.DELETE_PACKAGES, null);
20098        synchronized (mPackages) {
20099            // Cannot block uninstall of static shared libs as they are
20100            // considered a part of the using app (emulating static linking).
20101            // Also static libs are installed always on internal storage.
20102            PackageParser.Package pkg = mPackages.get(packageName);
20103            if (pkg != null && pkg.staticSharedLibName != null) {
20104                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
20105                        + " providing static shared library: " + pkg.staticSharedLibName);
20106                return false;
20107            }
20108            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
20109            mSettings.writePackageRestrictionsLPr(userId);
20110        }
20111        return true;
20112    }
20113
20114    @Override
20115    public boolean getBlockUninstallForUser(String packageName, int userId) {
20116        synchronized (mPackages) {
20117            final PackageSetting ps = mSettings.mPackages.get(packageName);
20118            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
20119                return false;
20120            }
20121            return mSettings.getBlockUninstallLPr(userId, packageName);
20122        }
20123    }
20124
20125    @Override
20126    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
20127        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
20128        synchronized (mPackages) {
20129            PackageSetting ps = mSettings.mPackages.get(packageName);
20130            if (ps == null) {
20131                Log.w(TAG, "Package doesn't exist: " + packageName);
20132                return false;
20133            }
20134            if (systemUserApp) {
20135                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
20136            } else {
20137                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
20138            }
20139            mSettings.writeLPr();
20140        }
20141        return true;
20142    }
20143
20144    /*
20145     * This method handles package deletion in general
20146     */
20147    private boolean deletePackageLIF(String packageName, UserHandle user,
20148            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
20149            PackageRemovedInfo outInfo, boolean writeSettings,
20150            PackageParser.Package replacingPackage) {
20151        if (packageName == null) {
20152            Slog.w(TAG, "Attempt to delete null packageName.");
20153            return false;
20154        }
20155
20156        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
20157
20158        PackageSetting ps;
20159        synchronized (mPackages) {
20160            ps = mSettings.mPackages.get(packageName);
20161            if (ps == null) {
20162                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
20163                return false;
20164            }
20165
20166            if (ps.parentPackageName != null && (!isSystemApp(ps)
20167                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
20168                if (DEBUG_REMOVE) {
20169                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
20170                            + ((user == null) ? UserHandle.USER_ALL : user));
20171                }
20172                final int removedUserId = (user != null) ? user.getIdentifier()
20173                        : UserHandle.USER_ALL;
20174                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
20175                    return false;
20176                }
20177                markPackageUninstalledForUserLPw(ps, user);
20178                scheduleWritePackageRestrictionsLocked(user);
20179                return true;
20180            }
20181        }
20182
20183        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
20184                && user.getIdentifier() != UserHandle.USER_ALL)) {
20185            // The caller is asking that the package only be deleted for a single
20186            // user.  To do this, we just mark its uninstalled state and delete
20187            // its data. If this is a system app, we only allow this to happen if
20188            // they have set the special DELETE_SYSTEM_APP which requests different
20189            // semantics than normal for uninstalling system apps.
20190            markPackageUninstalledForUserLPw(ps, user);
20191
20192            if (!isSystemApp(ps)) {
20193                // Do not uninstall the APK if an app should be cached
20194                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
20195                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
20196                    // Other user still have this package installed, so all
20197                    // we need to do is clear this user's data and save that
20198                    // it is uninstalled.
20199                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
20200                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
20201                        return false;
20202                    }
20203                    scheduleWritePackageRestrictionsLocked(user);
20204                    return true;
20205                } else {
20206                    // We need to set it back to 'installed' so the uninstall
20207                    // broadcasts will be sent correctly.
20208                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
20209                    ps.setInstalled(true, user.getIdentifier());
20210                    mSettings.writeKernelMappingLPr(ps);
20211                }
20212            } else {
20213                // This is a system app, so we assume that the
20214                // other users still have this package installed, so all
20215                // we need to do is clear this user's data and save that
20216                // it is uninstalled.
20217                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
20218                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
20219                    return false;
20220                }
20221                scheduleWritePackageRestrictionsLocked(user);
20222                return true;
20223            }
20224        }
20225
20226        // If we are deleting a composite package for all users, keep track
20227        // of result for each child.
20228        if (ps.childPackageNames != null && outInfo != null) {
20229            synchronized (mPackages) {
20230                final int childCount = ps.childPackageNames.size();
20231                outInfo.removedChildPackages = new ArrayMap<>(childCount);
20232                for (int i = 0; i < childCount; i++) {
20233                    String childPackageName = ps.childPackageNames.get(i);
20234                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
20235                    childInfo.removedPackage = childPackageName;
20236                    childInfo.installerPackageName = ps.installerPackageName;
20237                    outInfo.removedChildPackages.put(childPackageName, childInfo);
20238                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
20239                    if (childPs != null) {
20240                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
20241                    }
20242                }
20243            }
20244        }
20245
20246        boolean ret = false;
20247        if (isSystemApp(ps)) {
20248            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
20249            // When an updated system application is deleted we delete the existing resources
20250            // as well and fall back to existing code in system partition
20251            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
20252        } else {
20253            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
20254            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
20255                    outInfo, writeSettings, replacingPackage);
20256        }
20257
20258        // Take a note whether we deleted the package for all users
20259        if (outInfo != null) {
20260            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
20261            if (outInfo.removedChildPackages != null) {
20262                synchronized (mPackages) {
20263                    final int childCount = outInfo.removedChildPackages.size();
20264                    for (int i = 0; i < childCount; i++) {
20265                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
20266                        if (childInfo != null) {
20267                            childInfo.removedForAllUsers = mPackages.get(
20268                                    childInfo.removedPackage) == null;
20269                        }
20270                    }
20271                }
20272            }
20273            // If we uninstalled an update to a system app there may be some
20274            // child packages that appeared as they are declared in the system
20275            // app but were not declared in the update.
20276            if (isSystemApp(ps)) {
20277                synchronized (mPackages) {
20278                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
20279                    final int childCount = (updatedPs.childPackageNames != null)
20280                            ? updatedPs.childPackageNames.size() : 0;
20281                    for (int i = 0; i < childCount; i++) {
20282                        String childPackageName = updatedPs.childPackageNames.get(i);
20283                        if (outInfo.removedChildPackages == null
20284                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
20285                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
20286                            if (childPs == null) {
20287                                continue;
20288                            }
20289                            PackageInstalledInfo installRes = new PackageInstalledInfo();
20290                            installRes.name = childPackageName;
20291                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
20292                            installRes.pkg = mPackages.get(childPackageName);
20293                            installRes.uid = childPs.pkg.applicationInfo.uid;
20294                            if (outInfo.appearedChildPackages == null) {
20295                                outInfo.appearedChildPackages = new ArrayMap<>();
20296                            }
20297                            outInfo.appearedChildPackages.put(childPackageName, installRes);
20298                        }
20299                    }
20300                }
20301            }
20302        }
20303
20304        return ret;
20305    }
20306
20307    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
20308        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
20309                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
20310        for (int nextUserId : userIds) {
20311            if (DEBUG_REMOVE) {
20312                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
20313            }
20314            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
20315                    false /*installed*/,
20316                    true /*stopped*/,
20317                    true /*notLaunched*/,
20318                    false /*hidden*/,
20319                    false /*suspended*/,
20320                    false /*instantApp*/,
20321                    false /*virtualPreload*/,
20322                    null /*lastDisableAppCaller*/,
20323                    null /*enabledComponents*/,
20324                    null /*disabledComponents*/,
20325                    ps.readUserState(nextUserId).domainVerificationStatus,
20326                    0, PackageManager.INSTALL_REASON_UNKNOWN);
20327        }
20328        mSettings.writeKernelMappingLPr(ps);
20329    }
20330
20331    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
20332            PackageRemovedInfo outInfo) {
20333        final PackageParser.Package pkg;
20334        synchronized (mPackages) {
20335            pkg = mPackages.get(ps.name);
20336        }
20337
20338        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
20339                : new int[] {userId};
20340        for (int nextUserId : userIds) {
20341            if (DEBUG_REMOVE) {
20342                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
20343                        + nextUserId);
20344            }
20345
20346            destroyAppDataLIF(pkg, userId,
20347                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20348            destroyAppProfilesLIF(pkg, userId);
20349            clearDefaultBrowserIfNeededForUser(ps.name, userId);
20350            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
20351            schedulePackageCleaning(ps.name, nextUserId, false);
20352            synchronized (mPackages) {
20353                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
20354                    scheduleWritePackageRestrictionsLocked(nextUserId);
20355                }
20356                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
20357            }
20358        }
20359
20360        if (outInfo != null) {
20361            outInfo.removedPackage = ps.name;
20362            outInfo.installerPackageName = ps.installerPackageName;
20363            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
20364            outInfo.removedAppId = ps.appId;
20365            outInfo.removedUsers = userIds;
20366            outInfo.broadcastUsers = userIds;
20367        }
20368
20369        return true;
20370    }
20371
20372    private final class ClearStorageConnection implements ServiceConnection {
20373        IMediaContainerService mContainerService;
20374
20375        @Override
20376        public void onServiceConnected(ComponentName name, IBinder service) {
20377            synchronized (this) {
20378                mContainerService = IMediaContainerService.Stub
20379                        .asInterface(Binder.allowBlocking(service));
20380                notifyAll();
20381            }
20382        }
20383
20384        @Override
20385        public void onServiceDisconnected(ComponentName name) {
20386        }
20387    }
20388
20389    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
20390        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
20391
20392        final boolean mounted;
20393        if (Environment.isExternalStorageEmulated()) {
20394            mounted = true;
20395        } else {
20396            final String status = Environment.getExternalStorageState();
20397
20398            mounted = status.equals(Environment.MEDIA_MOUNTED)
20399                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
20400        }
20401
20402        if (!mounted) {
20403            return;
20404        }
20405
20406        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
20407        int[] users;
20408        if (userId == UserHandle.USER_ALL) {
20409            users = sUserManager.getUserIds();
20410        } else {
20411            users = new int[] { userId };
20412        }
20413        final ClearStorageConnection conn = new ClearStorageConnection();
20414        if (mContext.bindServiceAsUser(
20415                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
20416            try {
20417                for (int curUser : users) {
20418                    long timeout = SystemClock.uptimeMillis() + 5000;
20419                    synchronized (conn) {
20420                        long now;
20421                        while (conn.mContainerService == null &&
20422                                (now = SystemClock.uptimeMillis()) < timeout) {
20423                            try {
20424                                conn.wait(timeout - now);
20425                            } catch (InterruptedException e) {
20426                            }
20427                        }
20428                    }
20429                    if (conn.mContainerService == null) {
20430                        return;
20431                    }
20432
20433                    final UserEnvironment userEnv = new UserEnvironment(curUser);
20434                    clearDirectory(conn.mContainerService,
20435                            userEnv.buildExternalStorageAppCacheDirs(packageName));
20436                    if (allData) {
20437                        clearDirectory(conn.mContainerService,
20438                                userEnv.buildExternalStorageAppDataDirs(packageName));
20439                        clearDirectory(conn.mContainerService,
20440                                userEnv.buildExternalStorageAppMediaDirs(packageName));
20441                    }
20442                }
20443            } finally {
20444                mContext.unbindService(conn);
20445            }
20446        }
20447    }
20448
20449    @Override
20450    public void clearApplicationProfileData(String packageName) {
20451        enforceSystemOrRoot("Only the system can clear all profile data");
20452
20453        final PackageParser.Package pkg;
20454        synchronized (mPackages) {
20455            pkg = mPackages.get(packageName);
20456        }
20457
20458        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
20459            synchronized (mInstallLock) {
20460                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
20461            }
20462        }
20463    }
20464
20465    @Override
20466    public void clearApplicationUserData(final String packageName,
20467            final IPackageDataObserver observer, final int userId) {
20468        mContext.enforceCallingOrSelfPermission(
20469                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
20470
20471        final int callingUid = Binder.getCallingUid();
20472        enforceCrossUserPermission(callingUid, userId,
20473                true /* requireFullPermission */, false /* checkShell */, "clear application data");
20474
20475        final PackageSetting ps = mSettings.getPackageLPr(packageName);
20476        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
20477        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
20478            throw new SecurityException("Cannot clear data for a protected package: "
20479                    + packageName);
20480        }
20481        // Queue up an async operation since the package deletion may take a little while.
20482        mHandler.post(new Runnable() {
20483            public void run() {
20484                mHandler.removeCallbacks(this);
20485                final boolean succeeded;
20486                if (!filterApp) {
20487                    try (PackageFreezer freezer = freezePackage(packageName,
20488                            "clearApplicationUserData")) {
20489                        synchronized (mInstallLock) {
20490                            succeeded = clearApplicationUserDataLIF(packageName, userId);
20491                        }
20492                        clearExternalStorageDataSync(packageName, userId, true);
20493                        synchronized (mPackages) {
20494                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
20495                                    packageName, userId);
20496                        }
20497                    }
20498                    if (succeeded) {
20499                        // invoke DeviceStorageMonitor's update method to clear any notifications
20500                        DeviceStorageMonitorInternal dsm = LocalServices
20501                                .getService(DeviceStorageMonitorInternal.class);
20502                        if (dsm != null) {
20503                            dsm.checkMemory();
20504                        }
20505                    }
20506                } else {
20507                    succeeded = false;
20508                }
20509                if (observer != null) {
20510                    try {
20511                        observer.onRemoveCompleted(packageName, succeeded);
20512                    } catch (RemoteException e) {
20513                        Log.i(TAG, "Observer no longer exists.");
20514                    }
20515                } //end if observer
20516            } //end run
20517        });
20518    }
20519
20520    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
20521        if (packageName == null) {
20522            Slog.w(TAG, "Attempt to delete null packageName.");
20523            return false;
20524        }
20525
20526        // Try finding details about the requested package
20527        PackageParser.Package pkg;
20528        synchronized (mPackages) {
20529            pkg = mPackages.get(packageName);
20530            if (pkg == null) {
20531                final PackageSetting ps = mSettings.mPackages.get(packageName);
20532                if (ps != null) {
20533                    pkg = ps.pkg;
20534                }
20535            }
20536
20537            if (pkg == null) {
20538                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
20539                return false;
20540            }
20541
20542            PackageSetting ps = (PackageSetting) pkg.mExtras;
20543            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
20544        }
20545
20546        clearAppDataLIF(pkg, userId,
20547                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20548
20549        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20550        removeKeystoreDataIfNeeded(userId, appId);
20551
20552        UserManagerInternal umInternal = getUserManagerInternal();
20553        final int flags;
20554        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
20555            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
20556        } else if (umInternal.isUserRunning(userId)) {
20557            flags = StorageManager.FLAG_STORAGE_DE;
20558        } else {
20559            flags = 0;
20560        }
20561        prepareAppDataContentsLIF(pkg, userId, flags);
20562
20563        return true;
20564    }
20565
20566    /**
20567     * Reverts user permission state changes (permissions and flags) in
20568     * all packages for a given user.
20569     *
20570     * @param userId The device user for which to do a reset.
20571     */
20572    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
20573        final int packageCount = mPackages.size();
20574        for (int i = 0; i < packageCount; i++) {
20575            PackageParser.Package pkg = mPackages.valueAt(i);
20576            PackageSetting ps = (PackageSetting) pkg.mExtras;
20577            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
20578        }
20579    }
20580
20581    private void resetNetworkPolicies(int userId) {
20582        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
20583    }
20584
20585    /**
20586     * Reverts user permission state changes (permissions and flags).
20587     *
20588     * @param ps The package for which to reset.
20589     * @param userId The device user for which to do a reset.
20590     */
20591    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
20592            final PackageSetting ps, final int userId) {
20593        if (ps.pkg == null) {
20594            return;
20595        }
20596
20597        // These are flags that can change base on user actions.
20598        final int userSettableMask = FLAG_PERMISSION_USER_SET
20599                | FLAG_PERMISSION_USER_FIXED
20600                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
20601                | FLAG_PERMISSION_REVIEW_REQUIRED;
20602
20603        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
20604                | FLAG_PERMISSION_POLICY_FIXED;
20605
20606        boolean writeInstallPermissions = false;
20607        boolean writeRuntimePermissions = false;
20608
20609        final int permissionCount = ps.pkg.requestedPermissions.size();
20610        for (int i = 0; i < permissionCount; i++) {
20611            String permission = ps.pkg.requestedPermissions.get(i);
20612
20613            BasePermission bp = mSettings.mPermissions.get(permission);
20614            if (bp == null) {
20615                continue;
20616            }
20617
20618            // If shared user we just reset the state to which only this app contributed.
20619            if (ps.sharedUser != null) {
20620                boolean used = false;
20621                final int packageCount = ps.sharedUser.packages.size();
20622                for (int j = 0; j < packageCount; j++) {
20623                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
20624                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
20625                            && pkg.pkg.requestedPermissions.contains(permission)) {
20626                        used = true;
20627                        break;
20628                    }
20629                }
20630                if (used) {
20631                    continue;
20632                }
20633            }
20634
20635            PermissionsState permissionsState = ps.getPermissionsState();
20636
20637            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
20638
20639            // Always clear the user settable flags.
20640            final boolean hasInstallState = permissionsState.getInstallPermissionState(
20641                    bp.name) != null;
20642            // If permission review is enabled and this is a legacy app, mark the
20643            // permission as requiring a review as this is the initial state.
20644            int flags = 0;
20645            if (mPermissionReviewRequired
20646                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
20647                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
20648            }
20649            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
20650                if (hasInstallState) {
20651                    writeInstallPermissions = true;
20652                } else {
20653                    writeRuntimePermissions = true;
20654                }
20655            }
20656
20657            // Below is only runtime permission handling.
20658            if (!bp.isRuntime()) {
20659                continue;
20660            }
20661
20662            // Never clobber system or policy.
20663            if ((oldFlags & policyOrSystemFlags) != 0) {
20664                continue;
20665            }
20666
20667            // If this permission was granted by default, make sure it is.
20668            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
20669                if (permissionsState.grantRuntimePermission(bp, userId)
20670                        != PERMISSION_OPERATION_FAILURE) {
20671                    writeRuntimePermissions = true;
20672                }
20673            // If permission review is enabled the permissions for a legacy apps
20674            // are represented as constantly granted runtime ones, so don't revoke.
20675            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
20676                // Otherwise, reset the permission.
20677                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
20678                switch (revokeResult) {
20679                    case PERMISSION_OPERATION_SUCCESS:
20680                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
20681                        writeRuntimePermissions = true;
20682                        final int appId = ps.appId;
20683                        mHandler.post(new Runnable() {
20684                            @Override
20685                            public void run() {
20686                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
20687                            }
20688                        });
20689                    } break;
20690                }
20691            }
20692        }
20693
20694        // Synchronously write as we are taking permissions away.
20695        if (writeRuntimePermissions) {
20696            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
20697        }
20698
20699        // Synchronously write as we are taking permissions away.
20700        if (writeInstallPermissions) {
20701            mSettings.writeLPr();
20702        }
20703    }
20704
20705    /**
20706     * Remove entries from the keystore daemon. Will only remove it if the
20707     * {@code appId} is valid.
20708     */
20709    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
20710        if (appId < 0) {
20711            return;
20712        }
20713
20714        final KeyStore keyStore = KeyStore.getInstance();
20715        if (keyStore != null) {
20716            if (userId == UserHandle.USER_ALL) {
20717                for (final int individual : sUserManager.getUserIds()) {
20718                    keyStore.clearUid(UserHandle.getUid(individual, appId));
20719                }
20720            } else {
20721                keyStore.clearUid(UserHandle.getUid(userId, appId));
20722            }
20723        } else {
20724            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
20725        }
20726    }
20727
20728    @Override
20729    public void deleteApplicationCacheFiles(final String packageName,
20730            final IPackageDataObserver observer) {
20731        final int userId = UserHandle.getCallingUserId();
20732        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
20733    }
20734
20735    @Override
20736    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
20737            final IPackageDataObserver observer) {
20738        final int callingUid = Binder.getCallingUid();
20739        mContext.enforceCallingOrSelfPermission(
20740                android.Manifest.permission.DELETE_CACHE_FILES, null);
20741        enforceCrossUserPermission(callingUid, userId,
20742                /* requireFullPermission= */ true, /* checkShell= */ false,
20743                "delete application cache files");
20744        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
20745                android.Manifest.permission.ACCESS_INSTANT_APPS);
20746
20747        final PackageParser.Package pkg;
20748        synchronized (mPackages) {
20749            pkg = mPackages.get(packageName);
20750        }
20751
20752        // Queue up an async operation since the package deletion may take a little while.
20753        mHandler.post(new Runnable() {
20754            public void run() {
20755                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
20756                boolean doClearData = true;
20757                if (ps != null) {
20758                    final boolean targetIsInstantApp =
20759                            ps.getInstantApp(UserHandle.getUserId(callingUid));
20760                    doClearData = !targetIsInstantApp
20761                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
20762                }
20763                if (doClearData) {
20764                    synchronized (mInstallLock) {
20765                        final int flags = StorageManager.FLAG_STORAGE_DE
20766                                | StorageManager.FLAG_STORAGE_CE;
20767                        // We're only clearing cache files, so we don't care if the
20768                        // app is unfrozen and still able to run
20769                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
20770                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20771                    }
20772                    clearExternalStorageDataSync(packageName, userId, false);
20773                }
20774                if (observer != null) {
20775                    try {
20776                        observer.onRemoveCompleted(packageName, true);
20777                    } catch (RemoteException e) {
20778                        Log.i(TAG, "Observer no longer exists.");
20779                    }
20780                }
20781            }
20782        });
20783    }
20784
20785    @Override
20786    public void getPackageSizeInfo(final String packageName, int userHandle,
20787            final IPackageStatsObserver observer) {
20788        throw new UnsupportedOperationException(
20789                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
20790    }
20791
20792    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
20793        final PackageSetting ps;
20794        synchronized (mPackages) {
20795            ps = mSettings.mPackages.get(packageName);
20796            if (ps == null) {
20797                Slog.w(TAG, "Failed to find settings for " + packageName);
20798                return false;
20799            }
20800        }
20801
20802        final String[] packageNames = { packageName };
20803        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
20804        final String[] codePaths = { ps.codePathString };
20805
20806        try {
20807            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20808                    ps.appId, ceDataInodes, codePaths, stats);
20809
20810            // For now, ignore code size of packages on system partition
20811            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20812                stats.codeSize = 0;
20813            }
20814
20815            // External clients expect these to be tracked separately
20816            stats.dataSize -= stats.cacheSize;
20817
20818        } catch (InstallerException e) {
20819            Slog.w(TAG, String.valueOf(e));
20820            return false;
20821        }
20822
20823        return true;
20824    }
20825
20826    private int getUidTargetSdkVersionLockedLPr(int uid) {
20827        Object obj = mSettings.getUserIdLPr(uid);
20828        if (obj instanceof SharedUserSetting) {
20829            final SharedUserSetting sus = (SharedUserSetting) obj;
20830            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20831            final Iterator<PackageSetting> it = sus.packages.iterator();
20832            while (it.hasNext()) {
20833                final PackageSetting ps = it.next();
20834                if (ps.pkg != null) {
20835                    int v = ps.pkg.applicationInfo.targetSdkVersion;
20836                    if (v < vers) vers = v;
20837                }
20838            }
20839            return vers;
20840        } else if (obj instanceof PackageSetting) {
20841            final PackageSetting ps = (PackageSetting) obj;
20842            if (ps.pkg != null) {
20843                return ps.pkg.applicationInfo.targetSdkVersion;
20844            }
20845        }
20846        return Build.VERSION_CODES.CUR_DEVELOPMENT;
20847    }
20848
20849    @Override
20850    public void addPreferredActivity(IntentFilter filter, int match,
20851            ComponentName[] set, ComponentName activity, int userId) {
20852        addPreferredActivityInternal(filter, match, set, activity, true, userId,
20853                "Adding preferred");
20854    }
20855
20856    private void addPreferredActivityInternal(IntentFilter filter, int match,
20857            ComponentName[] set, ComponentName activity, boolean always, int userId,
20858            String opname) {
20859        // writer
20860        int callingUid = Binder.getCallingUid();
20861        enforceCrossUserPermission(callingUid, userId,
20862                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20863        if (filter.countActions() == 0) {
20864            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20865            return;
20866        }
20867        synchronized (mPackages) {
20868            if (mContext.checkCallingOrSelfPermission(
20869                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20870                    != PackageManager.PERMISSION_GRANTED) {
20871                if (getUidTargetSdkVersionLockedLPr(callingUid)
20872                        < Build.VERSION_CODES.FROYO) {
20873                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20874                            + callingUid);
20875                    return;
20876                }
20877                mContext.enforceCallingOrSelfPermission(
20878                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20879            }
20880
20881            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20882            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20883                    + userId + ":");
20884            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20885            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20886            scheduleWritePackageRestrictionsLocked(userId);
20887            postPreferredActivityChangedBroadcast(userId);
20888        }
20889    }
20890
20891    private void postPreferredActivityChangedBroadcast(int userId) {
20892        mHandler.post(() -> {
20893            final IActivityManager am = ActivityManager.getService();
20894            if (am == null) {
20895                return;
20896            }
20897
20898            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20899            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20900            try {
20901                am.broadcastIntent(null, intent, null, null,
20902                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
20903                        null, false, false, userId);
20904            } catch (RemoteException e) {
20905            }
20906        });
20907    }
20908
20909    @Override
20910    public void replacePreferredActivity(IntentFilter filter, int match,
20911            ComponentName[] set, ComponentName activity, int userId) {
20912        if (filter.countActions() != 1) {
20913            throw new IllegalArgumentException(
20914                    "replacePreferredActivity expects filter to have only 1 action.");
20915        }
20916        if (filter.countDataAuthorities() != 0
20917                || filter.countDataPaths() != 0
20918                || filter.countDataSchemes() > 1
20919                || filter.countDataTypes() != 0) {
20920            throw new IllegalArgumentException(
20921                    "replacePreferredActivity expects filter to have no data authorities, " +
20922                    "paths, or types; and at most one scheme.");
20923        }
20924
20925        final int callingUid = Binder.getCallingUid();
20926        enforceCrossUserPermission(callingUid, userId,
20927                true /* requireFullPermission */, false /* checkShell */,
20928                "replace preferred activity");
20929        synchronized (mPackages) {
20930            if (mContext.checkCallingOrSelfPermission(
20931                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20932                    != PackageManager.PERMISSION_GRANTED) {
20933                if (getUidTargetSdkVersionLockedLPr(callingUid)
20934                        < Build.VERSION_CODES.FROYO) {
20935                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20936                            + Binder.getCallingUid());
20937                    return;
20938                }
20939                mContext.enforceCallingOrSelfPermission(
20940                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20941            }
20942
20943            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20944            if (pir != null) {
20945                // Get all of the existing entries that exactly match this filter.
20946                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20947                if (existing != null && existing.size() == 1) {
20948                    PreferredActivity cur = existing.get(0);
20949                    if (DEBUG_PREFERRED) {
20950                        Slog.i(TAG, "Checking replace of preferred:");
20951                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20952                        if (!cur.mPref.mAlways) {
20953                            Slog.i(TAG, "  -- CUR; not mAlways!");
20954                        } else {
20955                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
20956                            Slog.i(TAG, "  -- CUR: mSet="
20957                                    + Arrays.toString(cur.mPref.mSetComponents));
20958                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
20959                            Slog.i(TAG, "  -- NEW: mMatch="
20960                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
20961                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
20962                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
20963                        }
20964                    }
20965                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20966                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20967                            && cur.mPref.sameSet(set)) {
20968                        // Setting the preferred activity to what it happens to be already
20969                        if (DEBUG_PREFERRED) {
20970                            Slog.i(TAG, "Replacing with same preferred activity "
20971                                    + cur.mPref.mShortComponent + " for user "
20972                                    + userId + ":");
20973                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20974                        }
20975                        return;
20976                    }
20977                }
20978
20979                if (existing != null) {
20980                    if (DEBUG_PREFERRED) {
20981                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
20982                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20983                    }
20984                    for (int i = 0; i < existing.size(); i++) {
20985                        PreferredActivity pa = existing.get(i);
20986                        if (DEBUG_PREFERRED) {
20987                            Slog.i(TAG, "Removing existing preferred activity "
20988                                    + pa.mPref.mComponent + ":");
20989                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
20990                        }
20991                        pir.removeFilter(pa);
20992                    }
20993                }
20994            }
20995            addPreferredActivityInternal(filter, match, set, activity, true, userId,
20996                    "Replacing preferred");
20997        }
20998    }
20999
21000    @Override
21001    public void clearPackagePreferredActivities(String packageName) {
21002        final int callingUid = Binder.getCallingUid();
21003        if (getInstantAppPackageName(callingUid) != null) {
21004            return;
21005        }
21006        // writer
21007        synchronized (mPackages) {
21008            PackageParser.Package pkg = mPackages.get(packageName);
21009            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
21010                if (mContext.checkCallingOrSelfPermission(
21011                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
21012                        != PackageManager.PERMISSION_GRANTED) {
21013                    if (getUidTargetSdkVersionLockedLPr(callingUid)
21014                            < Build.VERSION_CODES.FROYO) {
21015                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
21016                                + callingUid);
21017                        return;
21018                    }
21019                    mContext.enforceCallingOrSelfPermission(
21020                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
21021                }
21022            }
21023            final PackageSetting ps = mSettings.getPackageLPr(packageName);
21024            if (ps != null
21025                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
21026                return;
21027            }
21028            int user = UserHandle.getCallingUserId();
21029            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
21030                scheduleWritePackageRestrictionsLocked(user);
21031            }
21032        }
21033    }
21034
21035    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
21036    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
21037        ArrayList<PreferredActivity> removed = null;
21038        boolean changed = false;
21039        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21040            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
21041            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21042            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
21043                continue;
21044            }
21045            Iterator<PreferredActivity> it = pir.filterIterator();
21046            while (it.hasNext()) {
21047                PreferredActivity pa = it.next();
21048                // Mark entry for removal only if it matches the package name
21049                // and the entry is of type "always".
21050                if (packageName == null ||
21051                        (pa.mPref.mComponent.getPackageName().equals(packageName)
21052                                && pa.mPref.mAlways)) {
21053                    if (removed == null) {
21054                        removed = new ArrayList<PreferredActivity>();
21055                    }
21056                    removed.add(pa);
21057                }
21058            }
21059            if (removed != null) {
21060                for (int j=0; j<removed.size(); j++) {
21061                    PreferredActivity pa = removed.get(j);
21062                    pir.removeFilter(pa);
21063                }
21064                changed = true;
21065            }
21066        }
21067        if (changed) {
21068            postPreferredActivityChangedBroadcast(userId);
21069        }
21070        return changed;
21071    }
21072
21073    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
21074    private void clearIntentFilterVerificationsLPw(int userId) {
21075        final int packageCount = mPackages.size();
21076        for (int i = 0; i < packageCount; i++) {
21077            PackageParser.Package pkg = mPackages.valueAt(i);
21078            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
21079        }
21080    }
21081
21082    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
21083    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
21084        if (userId == UserHandle.USER_ALL) {
21085            if (mSettings.removeIntentFilterVerificationLPw(packageName,
21086                    sUserManager.getUserIds())) {
21087                for (int oneUserId : sUserManager.getUserIds()) {
21088                    scheduleWritePackageRestrictionsLocked(oneUserId);
21089                }
21090            }
21091        } else {
21092            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
21093                scheduleWritePackageRestrictionsLocked(userId);
21094            }
21095        }
21096    }
21097
21098    /** Clears state for all users, and touches intent filter verification policy */
21099    void clearDefaultBrowserIfNeeded(String packageName) {
21100        for (int oneUserId : sUserManager.getUserIds()) {
21101            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
21102        }
21103    }
21104
21105    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
21106        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
21107        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
21108            if (packageName.equals(defaultBrowserPackageName)) {
21109                setDefaultBrowserPackageName(null, userId);
21110            }
21111        }
21112    }
21113
21114    @Override
21115    public void resetApplicationPreferences(int userId) {
21116        mContext.enforceCallingOrSelfPermission(
21117                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
21118        final long identity = Binder.clearCallingIdentity();
21119        // writer
21120        try {
21121            synchronized (mPackages) {
21122                clearPackagePreferredActivitiesLPw(null, userId);
21123                mSettings.applyDefaultPreferredAppsLPw(this, userId);
21124                // TODO: We have to reset the default SMS and Phone. This requires
21125                // significant refactoring to keep all default apps in the package
21126                // manager (cleaner but more work) or have the services provide
21127                // callbacks to the package manager to request a default app reset.
21128                applyFactoryDefaultBrowserLPw(userId);
21129                clearIntentFilterVerificationsLPw(userId);
21130                primeDomainVerificationsLPw(userId);
21131                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
21132                scheduleWritePackageRestrictionsLocked(userId);
21133            }
21134            resetNetworkPolicies(userId);
21135        } finally {
21136            Binder.restoreCallingIdentity(identity);
21137        }
21138    }
21139
21140    @Override
21141    public int getPreferredActivities(List<IntentFilter> outFilters,
21142            List<ComponentName> outActivities, String packageName) {
21143        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21144            return 0;
21145        }
21146        int num = 0;
21147        final int userId = UserHandle.getCallingUserId();
21148        // reader
21149        synchronized (mPackages) {
21150            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
21151            if (pir != null) {
21152                final Iterator<PreferredActivity> it = pir.filterIterator();
21153                while (it.hasNext()) {
21154                    final PreferredActivity pa = it.next();
21155                    if (packageName == null
21156                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
21157                                    && pa.mPref.mAlways)) {
21158                        if (outFilters != null) {
21159                            outFilters.add(new IntentFilter(pa));
21160                        }
21161                        if (outActivities != null) {
21162                            outActivities.add(pa.mPref.mComponent);
21163                        }
21164                    }
21165                }
21166            }
21167        }
21168
21169        return num;
21170    }
21171
21172    @Override
21173    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
21174            int userId) {
21175        int callingUid = Binder.getCallingUid();
21176        if (callingUid != Process.SYSTEM_UID) {
21177            throw new SecurityException(
21178                    "addPersistentPreferredActivity can only be run by the system");
21179        }
21180        if (filter.countActions() == 0) {
21181            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
21182            return;
21183        }
21184        synchronized (mPackages) {
21185            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
21186                    ":");
21187            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
21188            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
21189                    new PersistentPreferredActivity(filter, activity));
21190            scheduleWritePackageRestrictionsLocked(userId);
21191            postPreferredActivityChangedBroadcast(userId);
21192        }
21193    }
21194
21195    @Override
21196    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
21197        int callingUid = Binder.getCallingUid();
21198        if (callingUid != Process.SYSTEM_UID) {
21199            throw new SecurityException(
21200                    "clearPackagePersistentPreferredActivities can only be run by the system");
21201        }
21202        ArrayList<PersistentPreferredActivity> removed = null;
21203        boolean changed = false;
21204        synchronized (mPackages) {
21205            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
21206                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
21207                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
21208                        .valueAt(i);
21209                if (userId != thisUserId) {
21210                    continue;
21211                }
21212                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
21213                while (it.hasNext()) {
21214                    PersistentPreferredActivity ppa = it.next();
21215                    // Mark entry for removal only if it matches the package name.
21216                    if (ppa.mComponent.getPackageName().equals(packageName)) {
21217                        if (removed == null) {
21218                            removed = new ArrayList<PersistentPreferredActivity>();
21219                        }
21220                        removed.add(ppa);
21221                    }
21222                }
21223                if (removed != null) {
21224                    for (int j=0; j<removed.size(); j++) {
21225                        PersistentPreferredActivity ppa = removed.get(j);
21226                        ppir.removeFilter(ppa);
21227                    }
21228                    changed = true;
21229                }
21230            }
21231
21232            if (changed) {
21233                scheduleWritePackageRestrictionsLocked(userId);
21234                postPreferredActivityChangedBroadcast(userId);
21235            }
21236        }
21237    }
21238
21239    /**
21240     * Common machinery for picking apart a restored XML blob and passing
21241     * it to a caller-supplied functor to be applied to the running system.
21242     */
21243    private void restoreFromXml(XmlPullParser parser, int userId,
21244            String expectedStartTag, BlobXmlRestorer functor)
21245            throws IOException, XmlPullParserException {
21246        int type;
21247        while ((type = parser.next()) != XmlPullParser.START_TAG
21248                && type != XmlPullParser.END_DOCUMENT) {
21249        }
21250        if (type != XmlPullParser.START_TAG) {
21251            // oops didn't find a start tag?!
21252            if (DEBUG_BACKUP) {
21253                Slog.e(TAG, "Didn't find start tag during restore");
21254            }
21255            return;
21256        }
21257Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
21258        // this is supposed to be TAG_PREFERRED_BACKUP
21259        if (!expectedStartTag.equals(parser.getName())) {
21260            if (DEBUG_BACKUP) {
21261                Slog.e(TAG, "Found unexpected tag " + parser.getName());
21262            }
21263            return;
21264        }
21265
21266        // skip interfering stuff, then we're aligned with the backing implementation
21267        while ((type = parser.next()) == XmlPullParser.TEXT) { }
21268Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
21269        functor.apply(parser, userId);
21270    }
21271
21272    private interface BlobXmlRestorer {
21273        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
21274    }
21275
21276    /**
21277     * Non-Binder method, support for the backup/restore mechanism: write the
21278     * full set of preferred activities in its canonical XML format.  Returns the
21279     * XML output as a byte array, or null if there is none.
21280     */
21281    @Override
21282    public byte[] getPreferredActivityBackup(int userId) {
21283        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21284            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
21285        }
21286
21287        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21288        try {
21289            final XmlSerializer serializer = new FastXmlSerializer();
21290            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21291            serializer.startDocument(null, true);
21292            serializer.startTag(null, TAG_PREFERRED_BACKUP);
21293
21294            synchronized (mPackages) {
21295                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
21296            }
21297
21298            serializer.endTag(null, TAG_PREFERRED_BACKUP);
21299            serializer.endDocument();
21300            serializer.flush();
21301        } catch (Exception e) {
21302            if (DEBUG_BACKUP) {
21303                Slog.e(TAG, "Unable to write preferred activities for backup", e);
21304            }
21305            return null;
21306        }
21307
21308        return dataStream.toByteArray();
21309    }
21310
21311    @Override
21312    public void restorePreferredActivities(byte[] backup, int userId) {
21313        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21314            throw new SecurityException("Only the system may call restorePreferredActivities()");
21315        }
21316
21317        try {
21318            final XmlPullParser parser = Xml.newPullParser();
21319            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21320            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
21321                    new BlobXmlRestorer() {
21322                        @Override
21323                        public void apply(XmlPullParser parser, int userId)
21324                                throws XmlPullParserException, IOException {
21325                            synchronized (mPackages) {
21326                                mSettings.readPreferredActivitiesLPw(parser, userId);
21327                            }
21328                        }
21329                    } );
21330        } catch (Exception e) {
21331            if (DEBUG_BACKUP) {
21332                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21333            }
21334        }
21335    }
21336
21337    /**
21338     * Non-Binder method, support for the backup/restore mechanism: write the
21339     * default browser (etc) settings in its canonical XML format.  Returns the default
21340     * browser XML representation as a byte array, or null if there is none.
21341     */
21342    @Override
21343    public byte[] getDefaultAppsBackup(int userId) {
21344        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21345            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
21346        }
21347
21348        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21349        try {
21350            final XmlSerializer serializer = new FastXmlSerializer();
21351            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21352            serializer.startDocument(null, true);
21353            serializer.startTag(null, TAG_DEFAULT_APPS);
21354
21355            synchronized (mPackages) {
21356                mSettings.writeDefaultAppsLPr(serializer, userId);
21357            }
21358
21359            serializer.endTag(null, TAG_DEFAULT_APPS);
21360            serializer.endDocument();
21361            serializer.flush();
21362        } catch (Exception e) {
21363            if (DEBUG_BACKUP) {
21364                Slog.e(TAG, "Unable to write default apps for backup", e);
21365            }
21366            return null;
21367        }
21368
21369        return dataStream.toByteArray();
21370    }
21371
21372    @Override
21373    public void restoreDefaultApps(byte[] backup, int userId) {
21374        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21375            throw new SecurityException("Only the system may call restoreDefaultApps()");
21376        }
21377
21378        try {
21379            final XmlPullParser parser = Xml.newPullParser();
21380            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21381            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
21382                    new BlobXmlRestorer() {
21383                        @Override
21384                        public void apply(XmlPullParser parser, int userId)
21385                                throws XmlPullParserException, IOException {
21386                            synchronized (mPackages) {
21387                                mSettings.readDefaultAppsLPw(parser, userId);
21388                            }
21389                        }
21390                    } );
21391        } catch (Exception e) {
21392            if (DEBUG_BACKUP) {
21393                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
21394            }
21395        }
21396    }
21397
21398    @Override
21399    public byte[] getIntentFilterVerificationBackup(int userId) {
21400        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21401            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
21402        }
21403
21404        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21405        try {
21406            final XmlSerializer serializer = new FastXmlSerializer();
21407            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21408            serializer.startDocument(null, true);
21409            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
21410
21411            synchronized (mPackages) {
21412                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
21413            }
21414
21415            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
21416            serializer.endDocument();
21417            serializer.flush();
21418        } catch (Exception e) {
21419            if (DEBUG_BACKUP) {
21420                Slog.e(TAG, "Unable to write default apps for backup", e);
21421            }
21422            return null;
21423        }
21424
21425        return dataStream.toByteArray();
21426    }
21427
21428    @Override
21429    public void restoreIntentFilterVerification(byte[] backup, int userId) {
21430        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21431            throw new SecurityException("Only the system may call restorePreferredActivities()");
21432        }
21433
21434        try {
21435            final XmlPullParser parser = Xml.newPullParser();
21436            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21437            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
21438                    new BlobXmlRestorer() {
21439                        @Override
21440                        public void apply(XmlPullParser parser, int userId)
21441                                throws XmlPullParserException, IOException {
21442                            synchronized (mPackages) {
21443                                mSettings.readAllDomainVerificationsLPr(parser, userId);
21444                                mSettings.writeLPr();
21445                            }
21446                        }
21447                    } );
21448        } catch (Exception e) {
21449            if (DEBUG_BACKUP) {
21450                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21451            }
21452        }
21453    }
21454
21455    @Override
21456    public byte[] getPermissionGrantBackup(int userId) {
21457        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21458            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
21459        }
21460
21461        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21462        try {
21463            final XmlSerializer serializer = new FastXmlSerializer();
21464            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21465            serializer.startDocument(null, true);
21466            serializer.startTag(null, TAG_PERMISSION_BACKUP);
21467
21468            synchronized (mPackages) {
21469                serializeRuntimePermissionGrantsLPr(serializer, userId);
21470            }
21471
21472            serializer.endTag(null, TAG_PERMISSION_BACKUP);
21473            serializer.endDocument();
21474            serializer.flush();
21475        } catch (Exception e) {
21476            if (DEBUG_BACKUP) {
21477                Slog.e(TAG, "Unable to write default apps for backup", e);
21478            }
21479            return null;
21480        }
21481
21482        return dataStream.toByteArray();
21483    }
21484
21485    @Override
21486    public void restorePermissionGrants(byte[] backup, int userId) {
21487        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21488            throw new SecurityException("Only the system may call restorePermissionGrants()");
21489        }
21490
21491        try {
21492            final XmlPullParser parser = Xml.newPullParser();
21493            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21494            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
21495                    new BlobXmlRestorer() {
21496                        @Override
21497                        public void apply(XmlPullParser parser, int userId)
21498                                throws XmlPullParserException, IOException {
21499                            synchronized (mPackages) {
21500                                processRestoredPermissionGrantsLPr(parser, userId);
21501                            }
21502                        }
21503                    } );
21504        } catch (Exception e) {
21505            if (DEBUG_BACKUP) {
21506                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21507            }
21508        }
21509    }
21510
21511    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
21512            throws IOException {
21513        serializer.startTag(null, TAG_ALL_GRANTS);
21514
21515        final int N = mSettings.mPackages.size();
21516        for (int i = 0; i < N; i++) {
21517            final PackageSetting ps = mSettings.mPackages.valueAt(i);
21518            boolean pkgGrantsKnown = false;
21519
21520            PermissionsState packagePerms = ps.getPermissionsState();
21521
21522            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
21523                final int grantFlags = state.getFlags();
21524                // only look at grants that are not system/policy fixed
21525                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
21526                    final boolean isGranted = state.isGranted();
21527                    // And only back up the user-twiddled state bits
21528                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
21529                        final String packageName = mSettings.mPackages.keyAt(i);
21530                        if (!pkgGrantsKnown) {
21531                            serializer.startTag(null, TAG_GRANT);
21532                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
21533                            pkgGrantsKnown = true;
21534                        }
21535
21536                        final boolean userSet =
21537                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
21538                        final boolean userFixed =
21539                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
21540                        final boolean revoke =
21541                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
21542
21543                        serializer.startTag(null, TAG_PERMISSION);
21544                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
21545                        if (isGranted) {
21546                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
21547                        }
21548                        if (userSet) {
21549                            serializer.attribute(null, ATTR_USER_SET, "true");
21550                        }
21551                        if (userFixed) {
21552                            serializer.attribute(null, ATTR_USER_FIXED, "true");
21553                        }
21554                        if (revoke) {
21555                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
21556                        }
21557                        serializer.endTag(null, TAG_PERMISSION);
21558                    }
21559                }
21560            }
21561
21562            if (pkgGrantsKnown) {
21563                serializer.endTag(null, TAG_GRANT);
21564            }
21565        }
21566
21567        serializer.endTag(null, TAG_ALL_GRANTS);
21568    }
21569
21570    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
21571            throws XmlPullParserException, IOException {
21572        String pkgName = null;
21573        int outerDepth = parser.getDepth();
21574        int type;
21575        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
21576                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
21577            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
21578                continue;
21579            }
21580
21581            final String tagName = parser.getName();
21582            if (tagName.equals(TAG_GRANT)) {
21583                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
21584                if (DEBUG_BACKUP) {
21585                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
21586                }
21587            } else if (tagName.equals(TAG_PERMISSION)) {
21588
21589                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
21590                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
21591
21592                int newFlagSet = 0;
21593                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
21594                    newFlagSet |= FLAG_PERMISSION_USER_SET;
21595                }
21596                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
21597                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
21598                }
21599                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
21600                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
21601                }
21602                if (DEBUG_BACKUP) {
21603                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
21604                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
21605                }
21606                final PackageSetting ps = mSettings.mPackages.get(pkgName);
21607                if (ps != null) {
21608                    // Already installed so we apply the grant immediately
21609                    if (DEBUG_BACKUP) {
21610                        Slog.v(TAG, "        + already installed; applying");
21611                    }
21612                    PermissionsState perms = ps.getPermissionsState();
21613                    BasePermission bp = mSettings.mPermissions.get(permName);
21614                    if (bp != null) {
21615                        if (isGranted) {
21616                            perms.grantRuntimePermission(bp, userId);
21617                        }
21618                        if (newFlagSet != 0) {
21619                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
21620                        }
21621                    }
21622                } else {
21623                    // Need to wait for post-restore install to apply the grant
21624                    if (DEBUG_BACKUP) {
21625                        Slog.v(TAG, "        - not yet installed; saving for later");
21626                    }
21627                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
21628                            isGranted, newFlagSet, userId);
21629                }
21630            } else {
21631                PackageManagerService.reportSettingsProblem(Log.WARN,
21632                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
21633                XmlUtils.skipCurrentTag(parser);
21634            }
21635        }
21636
21637        scheduleWriteSettingsLocked();
21638        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
21639    }
21640
21641    @Override
21642    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
21643            int sourceUserId, int targetUserId, int flags) {
21644        mContext.enforceCallingOrSelfPermission(
21645                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21646        int callingUid = Binder.getCallingUid();
21647        enforceOwnerRights(ownerPackage, callingUid);
21648        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21649        if (intentFilter.countActions() == 0) {
21650            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
21651            return;
21652        }
21653        synchronized (mPackages) {
21654            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
21655                    ownerPackage, targetUserId, flags);
21656            CrossProfileIntentResolver resolver =
21657                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21658            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
21659            // We have all those whose filter is equal. Now checking if the rest is equal as well.
21660            if (existing != null) {
21661                int size = existing.size();
21662                for (int i = 0; i < size; i++) {
21663                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
21664                        return;
21665                    }
21666                }
21667            }
21668            resolver.addFilter(newFilter);
21669            scheduleWritePackageRestrictionsLocked(sourceUserId);
21670        }
21671    }
21672
21673    @Override
21674    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
21675        mContext.enforceCallingOrSelfPermission(
21676                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21677        final int callingUid = Binder.getCallingUid();
21678        enforceOwnerRights(ownerPackage, callingUid);
21679        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21680        synchronized (mPackages) {
21681            CrossProfileIntentResolver resolver =
21682                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21683            ArraySet<CrossProfileIntentFilter> set =
21684                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
21685            for (CrossProfileIntentFilter filter : set) {
21686                if (filter.getOwnerPackage().equals(ownerPackage)) {
21687                    resolver.removeFilter(filter);
21688                }
21689            }
21690            scheduleWritePackageRestrictionsLocked(sourceUserId);
21691        }
21692    }
21693
21694    // Enforcing that callingUid is owning pkg on userId
21695    private void enforceOwnerRights(String pkg, int callingUid) {
21696        // The system owns everything.
21697        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
21698            return;
21699        }
21700        final int callingUserId = UserHandle.getUserId(callingUid);
21701        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
21702        if (pi == null) {
21703            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
21704                    + callingUserId);
21705        }
21706        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
21707            throw new SecurityException("Calling uid " + callingUid
21708                    + " does not own package " + pkg);
21709        }
21710    }
21711
21712    @Override
21713    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
21714        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21715            return null;
21716        }
21717        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
21718    }
21719
21720    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
21721        UserManagerService ums = UserManagerService.getInstance();
21722        if (ums != null) {
21723            final UserInfo parent = ums.getProfileParent(userId);
21724            final int launcherUid = (parent != null) ? parent.id : userId;
21725            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
21726            if (launcherComponent != null) {
21727                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
21728                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
21729                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
21730                        .setPackage(launcherComponent.getPackageName());
21731                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
21732            }
21733        }
21734    }
21735
21736    /**
21737     * Report the 'Home' activity which is currently set as "always use this one". If non is set
21738     * then reports the most likely home activity or null if there are more than one.
21739     */
21740    private ComponentName getDefaultHomeActivity(int userId) {
21741        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
21742        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
21743        if (cn != null) {
21744            return cn;
21745        }
21746
21747        // Find the launcher with the highest priority and return that component if there are no
21748        // other home activity with the same priority.
21749        int lastPriority = Integer.MIN_VALUE;
21750        ComponentName lastComponent = null;
21751        final int size = allHomeCandidates.size();
21752        for (int i = 0; i < size; i++) {
21753            final ResolveInfo ri = allHomeCandidates.get(i);
21754            if (ri.priority > lastPriority) {
21755                lastComponent = ri.activityInfo.getComponentName();
21756                lastPriority = ri.priority;
21757            } else if (ri.priority == lastPriority) {
21758                // Two components found with same priority.
21759                lastComponent = null;
21760            }
21761        }
21762        return lastComponent;
21763    }
21764
21765    private Intent getHomeIntent() {
21766        Intent intent = new Intent(Intent.ACTION_MAIN);
21767        intent.addCategory(Intent.CATEGORY_HOME);
21768        intent.addCategory(Intent.CATEGORY_DEFAULT);
21769        return intent;
21770    }
21771
21772    private IntentFilter getHomeFilter() {
21773        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
21774        filter.addCategory(Intent.CATEGORY_HOME);
21775        filter.addCategory(Intent.CATEGORY_DEFAULT);
21776        return filter;
21777    }
21778
21779    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21780            int userId) {
21781        Intent intent  = getHomeIntent();
21782        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
21783                PackageManager.GET_META_DATA, userId);
21784        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
21785                true, false, false, userId);
21786
21787        allHomeCandidates.clear();
21788        if (list != null) {
21789            for (ResolveInfo ri : list) {
21790                allHomeCandidates.add(ri);
21791            }
21792        }
21793        return (preferred == null || preferred.activityInfo == null)
21794                ? null
21795                : new ComponentName(preferred.activityInfo.packageName,
21796                        preferred.activityInfo.name);
21797    }
21798
21799    @Override
21800    public void setHomeActivity(ComponentName comp, int userId) {
21801        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21802            return;
21803        }
21804        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21805        getHomeActivitiesAsUser(homeActivities, userId);
21806
21807        boolean found = false;
21808
21809        final int size = homeActivities.size();
21810        final ComponentName[] set = new ComponentName[size];
21811        for (int i = 0; i < size; i++) {
21812            final ResolveInfo candidate = homeActivities.get(i);
21813            final ActivityInfo info = candidate.activityInfo;
21814            final ComponentName activityName = new ComponentName(info.packageName, info.name);
21815            set[i] = activityName;
21816            if (!found && activityName.equals(comp)) {
21817                found = true;
21818            }
21819        }
21820        if (!found) {
21821            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21822                    + userId);
21823        }
21824        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21825                set, comp, userId);
21826    }
21827
21828    private @Nullable String getSetupWizardPackageName() {
21829        final Intent intent = new Intent(Intent.ACTION_MAIN);
21830        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21831
21832        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21833                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21834                        | MATCH_DISABLED_COMPONENTS,
21835                UserHandle.myUserId());
21836        if (matches.size() == 1) {
21837            return matches.get(0).getComponentInfo().packageName;
21838        } else {
21839            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21840                    + ": matches=" + matches);
21841            return null;
21842        }
21843    }
21844
21845    private @Nullable String getStorageManagerPackageName() {
21846        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21847
21848        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21849                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21850                        | MATCH_DISABLED_COMPONENTS,
21851                UserHandle.myUserId());
21852        if (matches.size() == 1) {
21853            return matches.get(0).getComponentInfo().packageName;
21854        } else {
21855            Slog.e(TAG, "There should probably be exactly one storage manager; found "
21856                    + matches.size() + ": matches=" + matches);
21857            return null;
21858        }
21859    }
21860
21861    @Override
21862    public void setApplicationEnabledSetting(String appPackageName,
21863            int newState, int flags, int userId, String callingPackage) {
21864        if (!sUserManager.exists(userId)) return;
21865        if (callingPackage == null) {
21866            callingPackage = Integer.toString(Binder.getCallingUid());
21867        }
21868        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21869    }
21870
21871    @Override
21872    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21873        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21874        synchronized (mPackages) {
21875            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21876            if (pkgSetting != null) {
21877                pkgSetting.setUpdateAvailable(updateAvailable);
21878            }
21879        }
21880    }
21881
21882    @Override
21883    public void setComponentEnabledSetting(ComponentName componentName,
21884            int newState, int flags, int userId) {
21885        if (!sUserManager.exists(userId)) return;
21886        setEnabledSetting(componentName.getPackageName(),
21887                componentName.getClassName(), newState, flags, userId, null);
21888    }
21889
21890    private void setEnabledSetting(final String packageName, String className, int newState,
21891            final int flags, int userId, String callingPackage) {
21892        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21893              || newState == COMPONENT_ENABLED_STATE_ENABLED
21894              || newState == COMPONENT_ENABLED_STATE_DISABLED
21895              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21896              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21897            throw new IllegalArgumentException("Invalid new component state: "
21898                    + newState);
21899        }
21900        PackageSetting pkgSetting;
21901        final int callingUid = Binder.getCallingUid();
21902        final int permission;
21903        if (callingUid == Process.SYSTEM_UID) {
21904            permission = PackageManager.PERMISSION_GRANTED;
21905        } else {
21906            permission = mContext.checkCallingOrSelfPermission(
21907                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21908        }
21909        enforceCrossUserPermission(callingUid, userId,
21910                false /* requireFullPermission */, true /* checkShell */, "set enabled");
21911        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21912        boolean sendNow = false;
21913        boolean isApp = (className == null);
21914        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21915        String componentName = isApp ? packageName : className;
21916        int packageUid = -1;
21917        ArrayList<String> components;
21918
21919        // reader
21920        synchronized (mPackages) {
21921            pkgSetting = mSettings.mPackages.get(packageName);
21922            if (pkgSetting == null) {
21923                if (!isCallerInstantApp) {
21924                    if (className == null) {
21925                        throw new IllegalArgumentException("Unknown package: " + packageName);
21926                    }
21927                    throw new IllegalArgumentException(
21928                            "Unknown component: " + packageName + "/" + className);
21929                } else {
21930                    // throw SecurityException to prevent leaking package information
21931                    throw new SecurityException(
21932                            "Attempt to change component state; "
21933                            + "pid=" + Binder.getCallingPid()
21934                            + ", uid=" + callingUid
21935                            + (className == null
21936                                    ? ", package=" + packageName
21937                                    : ", component=" + packageName + "/" + className));
21938                }
21939            }
21940        }
21941
21942        // Limit who can change which apps
21943        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21944            // Don't allow apps that don't have permission to modify other apps
21945            if (!allowedByPermission
21946                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21947                throw new SecurityException(
21948                        "Attempt to change component state; "
21949                        + "pid=" + Binder.getCallingPid()
21950                        + ", uid=" + callingUid
21951                        + (className == null
21952                                ? ", package=" + packageName
21953                                : ", component=" + packageName + "/" + className));
21954            }
21955            // Don't allow changing protected packages.
21956            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21957                throw new SecurityException("Cannot disable a protected package: " + packageName);
21958            }
21959        }
21960
21961        synchronized (mPackages) {
21962            if (callingUid == Process.SHELL_UID
21963                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21964                // Shell can only change whole packages between ENABLED and DISABLED_USER states
21965                // unless it is a test package.
21966                int oldState = pkgSetting.getEnabled(userId);
21967                if (className == null
21968                        &&
21969                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21970                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21971                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21972                        &&
21973                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21974                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
21975                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21976                    // ok
21977                } else {
21978                    throw new SecurityException(
21979                            "Shell cannot change component state for " + packageName + "/"
21980                                    + className + " to " + newState);
21981                }
21982            }
21983        }
21984        if (className == null) {
21985            // We're dealing with an application/package level state change
21986            synchronized (mPackages) {
21987                if (pkgSetting.getEnabled(userId) == newState) {
21988                    // Nothing to do
21989                    return;
21990                }
21991            }
21992            // If we're enabling a system stub, there's a little more work to do.
21993            // Prior to enabling the package, we need to decompress the APK(s) to the
21994            // data partition and then replace the version on the system partition.
21995            final PackageParser.Package deletedPkg = pkgSetting.pkg;
21996            final boolean isSystemStub = deletedPkg.isStub
21997                    && deletedPkg.isSystemApp();
21998            if (isSystemStub
21999                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
22000                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
22001                final File codePath = decompressPackage(deletedPkg);
22002                if (codePath == null) {
22003                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
22004                    return;
22005                }
22006                // TODO remove direct parsing of the package object during internal cleanup
22007                // of scan package
22008                // We need to call parse directly here for no other reason than we need
22009                // the new package in order to disable the old one [we use the information
22010                // for some internal optimization to optionally create a new package setting
22011                // object on replace]. However, we can't get the package from the scan
22012                // because the scan modifies live structures and we need to remove the
22013                // old [system] package from the system before a scan can be attempted.
22014                // Once scan is indempotent we can remove this parse and use the package
22015                // object we scanned, prior to adding it to package settings.
22016                final PackageParser pp = new PackageParser();
22017                pp.setSeparateProcesses(mSeparateProcesses);
22018                pp.setDisplayMetrics(mMetrics);
22019                pp.setCallback(mPackageParserCallback);
22020                final PackageParser.Package tmpPkg;
22021                try {
22022                    final int parseFlags = mDefParseFlags
22023                            | PackageParser.PARSE_MUST_BE_APK
22024                            | PackageParser.PARSE_IS_SYSTEM
22025                            | PackageParser.PARSE_IS_SYSTEM_DIR;
22026                    tmpPkg = pp.parsePackage(codePath, parseFlags);
22027                } catch (PackageParserException e) {
22028                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
22029                    return;
22030                }
22031                synchronized (mInstallLock) {
22032                    // Disable the stub and remove any package entries
22033                    removePackageLI(deletedPkg, true);
22034                    synchronized (mPackages) {
22035                        disableSystemPackageLPw(deletedPkg, tmpPkg);
22036                    }
22037                    final PackageParser.Package newPkg;
22038                    try (PackageFreezer freezer =
22039                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
22040                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
22041                                | PackageParser.PARSE_ENFORCE_CODE;
22042                        newPkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
22043                                0 /*currentTime*/, null /*user*/);
22044                        prepareAppDataAfterInstallLIF(newPkg);
22045                        synchronized (mPackages) {
22046                            try {
22047                                updateSharedLibrariesLPr(newPkg, null);
22048                            } catch (PackageManagerException e) {
22049                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
22050                            }
22051                            updatePermissionsLPw(newPkg.packageName, newPkg,
22052                                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
22053                            mSettings.writeLPr();
22054                        }
22055                    } catch (PackageManagerException e) {
22056                        // Whoops! Something went wrong; try to roll back to the stub
22057                        Slog.w(TAG, "Failed to install compressed system package:"
22058                                + pkgSetting.name, e);
22059                        // Remove the failed install
22060                        removeCodePathLI(codePath);
22061
22062                        // Install the system package
22063                        try (PackageFreezer freezer =
22064                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
22065                            synchronized (mPackages) {
22066                                // NOTE: The system package always needs to be enabled; even
22067                                // if it's for a compressed stub. If we don't, installing the
22068                                // system package fails during scan [scanning checks the disabled
22069                                // packages]. We will reverse this later, after we've "installed"
22070                                // the stub.
22071                                // This leaves us in a fragile state; the stub should never be
22072                                // enabled, so, cross your fingers and hope nothing goes wrong
22073                                // until we can disable the package later.
22074                                enableSystemPackageLPw(deletedPkg);
22075                            }
22076                            installPackageFromSystemLIF(new File(deletedPkg.codePath),
22077                                    false /*isPrivileged*/, null /*allUserHandles*/,
22078                                    null /*origUserHandles*/, null /*origPermissionsState*/,
22079                                    true /*writeSettings*/);
22080                        } catch (PackageManagerException pme) {
22081                            Slog.w(TAG, "Failed to restore system package:"
22082                                    + deletedPkg.packageName, pme);
22083                        } finally {
22084                            synchronized (mPackages) {
22085                                mSettings.disableSystemPackageLPw(
22086                                        deletedPkg.packageName, true /*replaced*/);
22087                                mSettings.writeLPr();
22088                            }
22089                        }
22090                        return;
22091                    }
22092                    clearAppDataLIF(newPkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
22093                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
22094                    clearAppProfilesLIF(newPkg, UserHandle.USER_ALL);
22095                    mDexManager.notifyPackageUpdated(newPkg.packageName,
22096                            newPkg.baseCodePath, newPkg.splitCodePaths);
22097                }
22098            }
22099            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
22100                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
22101                // Don't care about who enables an app.
22102                callingPackage = null;
22103            }
22104            synchronized (mPackages) {
22105                pkgSetting.setEnabled(newState, userId, callingPackage);
22106            }
22107        } else {
22108            synchronized (mPackages) {
22109                // We're dealing with a component level state change
22110                // First, verify that this is a valid class name.
22111                PackageParser.Package pkg = pkgSetting.pkg;
22112                if (pkg == null || !pkg.hasComponentClassName(className)) {
22113                    if (pkg != null &&
22114                            pkg.applicationInfo.targetSdkVersion >=
22115                                    Build.VERSION_CODES.JELLY_BEAN) {
22116                        throw new IllegalArgumentException("Component class " + className
22117                                + " does not exist in " + packageName);
22118                    } else {
22119                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
22120                                + className + " does not exist in " + packageName);
22121                    }
22122                }
22123                switch (newState) {
22124                    case COMPONENT_ENABLED_STATE_ENABLED:
22125                        if (!pkgSetting.enableComponentLPw(className, userId)) {
22126                            return;
22127                        }
22128                        break;
22129                    case COMPONENT_ENABLED_STATE_DISABLED:
22130                        if (!pkgSetting.disableComponentLPw(className, userId)) {
22131                            return;
22132                        }
22133                        break;
22134                    case COMPONENT_ENABLED_STATE_DEFAULT:
22135                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
22136                            return;
22137                        }
22138                        break;
22139                    default:
22140                        Slog.e(TAG, "Invalid new component state: " + newState);
22141                        return;
22142                }
22143            }
22144        }
22145        synchronized (mPackages) {
22146            scheduleWritePackageRestrictionsLocked(userId);
22147            updateSequenceNumberLP(pkgSetting, new int[] { userId });
22148            final long callingId = Binder.clearCallingIdentity();
22149            try {
22150                updateInstantAppInstallerLocked(packageName);
22151            } finally {
22152                Binder.restoreCallingIdentity(callingId);
22153            }
22154            components = mPendingBroadcasts.get(userId, packageName);
22155            final boolean newPackage = components == null;
22156            if (newPackage) {
22157                components = new ArrayList<String>();
22158            }
22159            if (!components.contains(componentName)) {
22160                components.add(componentName);
22161            }
22162            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
22163                sendNow = true;
22164                // Purge entry from pending broadcast list if another one exists already
22165                // since we are sending one right away.
22166                mPendingBroadcasts.remove(userId, packageName);
22167            } else {
22168                if (newPackage) {
22169                    mPendingBroadcasts.put(userId, packageName, components);
22170                }
22171                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
22172                    // Schedule a message
22173                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
22174                }
22175            }
22176        }
22177
22178        long callingId = Binder.clearCallingIdentity();
22179        try {
22180            if (sendNow) {
22181                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
22182                sendPackageChangedBroadcast(packageName,
22183                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
22184            }
22185        } finally {
22186            Binder.restoreCallingIdentity(callingId);
22187        }
22188    }
22189
22190    @Override
22191    public void flushPackageRestrictionsAsUser(int userId) {
22192        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
22193            return;
22194        }
22195        if (!sUserManager.exists(userId)) {
22196            return;
22197        }
22198        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
22199                false /* checkShell */, "flushPackageRestrictions");
22200        synchronized (mPackages) {
22201            mSettings.writePackageRestrictionsLPr(userId);
22202            mDirtyUsers.remove(userId);
22203            if (mDirtyUsers.isEmpty()) {
22204                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
22205            }
22206        }
22207    }
22208
22209    private void sendPackageChangedBroadcast(String packageName,
22210            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
22211        if (DEBUG_INSTALL)
22212            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
22213                    + componentNames);
22214        Bundle extras = new Bundle(4);
22215        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
22216        String nameList[] = new String[componentNames.size()];
22217        componentNames.toArray(nameList);
22218        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
22219        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
22220        extras.putInt(Intent.EXTRA_UID, packageUid);
22221        // If this is not reporting a change of the overall package, then only send it
22222        // to registered receivers.  We don't want to launch a swath of apps for every
22223        // little component state change.
22224        final int flags = !componentNames.contains(packageName)
22225                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
22226        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
22227                new int[] {UserHandle.getUserId(packageUid)});
22228    }
22229
22230    @Override
22231    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
22232        if (!sUserManager.exists(userId)) return;
22233        final int callingUid = Binder.getCallingUid();
22234        if (getInstantAppPackageName(callingUid) != null) {
22235            return;
22236        }
22237        final int permission = mContext.checkCallingOrSelfPermission(
22238                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
22239        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
22240        enforceCrossUserPermission(callingUid, userId,
22241                true /* requireFullPermission */, true /* checkShell */, "stop package");
22242        // writer
22243        synchronized (mPackages) {
22244            final PackageSetting ps = mSettings.mPackages.get(packageName);
22245            if (!filterAppAccessLPr(ps, callingUid, userId)
22246                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
22247                            allowedByPermission, callingUid, userId)) {
22248                scheduleWritePackageRestrictionsLocked(userId);
22249            }
22250        }
22251    }
22252
22253    @Override
22254    public String getInstallerPackageName(String packageName) {
22255        final int callingUid = Binder.getCallingUid();
22256        if (getInstantAppPackageName(callingUid) != null) {
22257            return null;
22258        }
22259        // reader
22260        synchronized (mPackages) {
22261            final PackageSetting ps = mSettings.mPackages.get(packageName);
22262            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
22263                return null;
22264            }
22265            return mSettings.getInstallerPackageNameLPr(packageName);
22266        }
22267    }
22268
22269    public boolean isOrphaned(String packageName) {
22270        // reader
22271        synchronized (mPackages) {
22272            return mSettings.isOrphaned(packageName);
22273        }
22274    }
22275
22276    @Override
22277    public int getApplicationEnabledSetting(String packageName, int userId) {
22278        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
22279        int callingUid = Binder.getCallingUid();
22280        enforceCrossUserPermission(callingUid, userId,
22281                false /* requireFullPermission */, false /* checkShell */, "get enabled");
22282        // reader
22283        synchronized (mPackages) {
22284            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
22285                return COMPONENT_ENABLED_STATE_DISABLED;
22286            }
22287            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
22288        }
22289    }
22290
22291    @Override
22292    public int getComponentEnabledSetting(ComponentName component, int userId) {
22293        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
22294        int callingUid = Binder.getCallingUid();
22295        enforceCrossUserPermission(callingUid, userId,
22296                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
22297        synchronized (mPackages) {
22298            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
22299                    component, TYPE_UNKNOWN, userId)) {
22300                return COMPONENT_ENABLED_STATE_DISABLED;
22301            }
22302            return mSettings.getComponentEnabledSettingLPr(component, userId);
22303        }
22304    }
22305
22306    @Override
22307    public void enterSafeMode() {
22308        enforceSystemOrRoot("Only the system can request entering safe mode");
22309
22310        if (!mSystemReady) {
22311            mSafeMode = true;
22312        }
22313    }
22314
22315    @Override
22316    public void systemReady() {
22317        enforceSystemOrRoot("Only the system can claim the system is ready");
22318
22319        mSystemReady = true;
22320        final ContentResolver resolver = mContext.getContentResolver();
22321        ContentObserver co = new ContentObserver(mHandler) {
22322            @Override
22323            public void onChange(boolean selfChange) {
22324                mEphemeralAppsDisabled =
22325                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
22326                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
22327            }
22328        };
22329        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
22330                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
22331                false, co, UserHandle.USER_SYSTEM);
22332        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
22333                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
22334        co.onChange(true);
22335
22336        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
22337        // disabled after already being started.
22338        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
22339                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
22340
22341        // Read the compatibilty setting when the system is ready.
22342        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
22343                mContext.getContentResolver(),
22344                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
22345        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
22346        if (DEBUG_SETTINGS) {
22347            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
22348        }
22349
22350        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
22351
22352        synchronized (mPackages) {
22353            // Verify that all of the preferred activity components actually
22354            // exist.  It is possible for applications to be updated and at
22355            // that point remove a previously declared activity component that
22356            // had been set as a preferred activity.  We try to clean this up
22357            // the next time we encounter that preferred activity, but it is
22358            // possible for the user flow to never be able to return to that
22359            // situation so here we do a sanity check to make sure we haven't
22360            // left any junk around.
22361            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
22362            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22363                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22364                removed.clear();
22365                for (PreferredActivity pa : pir.filterSet()) {
22366                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
22367                        removed.add(pa);
22368                    }
22369                }
22370                if (removed.size() > 0) {
22371                    for (int r=0; r<removed.size(); r++) {
22372                        PreferredActivity pa = removed.get(r);
22373                        Slog.w(TAG, "Removing dangling preferred activity: "
22374                                + pa.mPref.mComponent);
22375                        pir.removeFilter(pa);
22376                    }
22377                    mSettings.writePackageRestrictionsLPr(
22378                            mSettings.mPreferredActivities.keyAt(i));
22379                }
22380            }
22381
22382            for (int userId : UserManagerService.getInstance().getUserIds()) {
22383                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
22384                    grantPermissionsUserIds = ArrayUtils.appendInt(
22385                            grantPermissionsUserIds, userId);
22386                }
22387            }
22388        }
22389        sUserManager.systemReady();
22390
22391        // If we upgraded grant all default permissions before kicking off.
22392        for (int userId : grantPermissionsUserIds) {
22393            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22394        }
22395
22396        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
22397            // If we did not grant default permissions, we preload from this the
22398            // default permission exceptions lazily to ensure we don't hit the
22399            // disk on a new user creation.
22400            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
22401        }
22402
22403        // Now that we've scanned all packages, and granted any default
22404        // permissions, ensure permissions are updated. Beware of dragons if you
22405        // try optimizing this.
22406        synchronized (mPackages) {
22407            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL,
22408                    UPDATE_PERMISSIONS_ALL);
22409        }
22410
22411        // Kick off any messages waiting for system ready
22412        if (mPostSystemReadyMessages != null) {
22413            for (Message msg : mPostSystemReadyMessages) {
22414                msg.sendToTarget();
22415            }
22416            mPostSystemReadyMessages = null;
22417        }
22418
22419        // Watch for external volumes that come and go over time
22420        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22421        storage.registerListener(mStorageListener);
22422
22423        mInstallerService.systemReady();
22424        mPackageDexOptimizer.systemReady();
22425
22426        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
22427                StorageManagerInternal.class);
22428        StorageManagerInternal.addExternalStoragePolicy(
22429                new StorageManagerInternal.ExternalStorageMountPolicy() {
22430            @Override
22431            public int getMountMode(int uid, String packageName) {
22432                if (Process.isIsolated(uid)) {
22433                    return Zygote.MOUNT_EXTERNAL_NONE;
22434                }
22435                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
22436                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
22437                }
22438                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
22439                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
22440                }
22441                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
22442                    return Zygote.MOUNT_EXTERNAL_READ;
22443                }
22444                return Zygote.MOUNT_EXTERNAL_WRITE;
22445            }
22446
22447            @Override
22448            public boolean hasExternalStorage(int uid, String packageName) {
22449                return true;
22450            }
22451        });
22452
22453        // Now that we're mostly running, clean up stale users and apps
22454        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
22455        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
22456
22457        if (mPrivappPermissionsViolations != null) {
22458            Slog.wtf(TAG,"Signature|privileged permissions not in "
22459                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
22460            mPrivappPermissionsViolations = null;
22461        }
22462    }
22463
22464    public void waitForAppDataPrepared() {
22465        if (mPrepareAppDataFuture == null) {
22466            return;
22467        }
22468        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
22469        mPrepareAppDataFuture = null;
22470    }
22471
22472    @Override
22473    public boolean isSafeMode() {
22474        // allow instant applications
22475        return mSafeMode;
22476    }
22477
22478    @Override
22479    public boolean hasSystemUidErrors() {
22480        // allow instant applications
22481        return mHasSystemUidErrors;
22482    }
22483
22484    static String arrayToString(int[] array) {
22485        StringBuffer buf = new StringBuffer(128);
22486        buf.append('[');
22487        if (array != null) {
22488            for (int i=0; i<array.length; i++) {
22489                if (i > 0) buf.append(", ");
22490                buf.append(array[i]);
22491            }
22492        }
22493        buf.append(']');
22494        return buf.toString();
22495    }
22496
22497    static class DumpState {
22498        public static final int DUMP_LIBS = 1 << 0;
22499        public static final int DUMP_FEATURES = 1 << 1;
22500        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
22501        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
22502        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
22503        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
22504        public static final int DUMP_PERMISSIONS = 1 << 6;
22505        public static final int DUMP_PACKAGES = 1 << 7;
22506        public static final int DUMP_SHARED_USERS = 1 << 8;
22507        public static final int DUMP_MESSAGES = 1 << 9;
22508        public static final int DUMP_PROVIDERS = 1 << 10;
22509        public static final int DUMP_VERIFIERS = 1 << 11;
22510        public static final int DUMP_PREFERRED = 1 << 12;
22511        public static final int DUMP_PREFERRED_XML = 1 << 13;
22512        public static final int DUMP_KEYSETS = 1 << 14;
22513        public static final int DUMP_VERSION = 1 << 15;
22514        public static final int DUMP_INSTALLS = 1 << 16;
22515        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
22516        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
22517        public static final int DUMP_FROZEN = 1 << 19;
22518        public static final int DUMP_DEXOPT = 1 << 20;
22519        public static final int DUMP_COMPILER_STATS = 1 << 21;
22520        public static final int DUMP_CHANGES = 1 << 22;
22521        public static final int DUMP_VOLUMES = 1 << 23;
22522
22523        public static final int OPTION_SHOW_FILTERS = 1 << 0;
22524
22525        private int mTypes;
22526
22527        private int mOptions;
22528
22529        private boolean mTitlePrinted;
22530
22531        private SharedUserSetting mSharedUser;
22532
22533        public boolean isDumping(int type) {
22534            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
22535                return true;
22536            }
22537
22538            return (mTypes & type) != 0;
22539        }
22540
22541        public void setDump(int type) {
22542            mTypes |= type;
22543        }
22544
22545        public boolean isOptionEnabled(int option) {
22546            return (mOptions & option) != 0;
22547        }
22548
22549        public void setOptionEnabled(int option) {
22550            mOptions |= option;
22551        }
22552
22553        public boolean onTitlePrinted() {
22554            final boolean printed = mTitlePrinted;
22555            mTitlePrinted = true;
22556            return printed;
22557        }
22558
22559        public boolean getTitlePrinted() {
22560            return mTitlePrinted;
22561        }
22562
22563        public void setTitlePrinted(boolean enabled) {
22564            mTitlePrinted = enabled;
22565        }
22566
22567        public SharedUserSetting getSharedUser() {
22568            return mSharedUser;
22569        }
22570
22571        public void setSharedUser(SharedUserSetting user) {
22572            mSharedUser = user;
22573        }
22574    }
22575
22576    @Override
22577    public void onShellCommand(FileDescriptor in, FileDescriptor out,
22578            FileDescriptor err, String[] args, ShellCallback callback,
22579            ResultReceiver resultReceiver) {
22580        (new PackageManagerShellCommand(this)).exec(
22581                this, in, out, err, args, callback, resultReceiver);
22582    }
22583
22584    @Override
22585    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
22586        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
22587
22588        DumpState dumpState = new DumpState();
22589        boolean fullPreferred = false;
22590        boolean checkin = false;
22591
22592        String packageName = null;
22593        ArraySet<String> permissionNames = null;
22594
22595        int opti = 0;
22596        while (opti < args.length) {
22597            String opt = args[opti];
22598            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
22599                break;
22600            }
22601            opti++;
22602
22603            if ("-a".equals(opt)) {
22604                // Right now we only know how to print all.
22605            } else if ("-h".equals(opt)) {
22606                pw.println("Package manager dump options:");
22607                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
22608                pw.println("    --checkin: dump for a checkin");
22609                pw.println("    -f: print details of intent filters");
22610                pw.println("    -h: print this help");
22611                pw.println("  cmd may be one of:");
22612                pw.println("    l[ibraries]: list known shared libraries");
22613                pw.println("    f[eatures]: list device features");
22614                pw.println("    k[eysets]: print known keysets");
22615                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
22616                pw.println("    perm[issions]: dump permissions");
22617                pw.println("    permission [name ...]: dump declaration and use of given permission");
22618                pw.println("    pref[erred]: print preferred package settings");
22619                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
22620                pw.println("    prov[iders]: dump content providers");
22621                pw.println("    p[ackages]: dump installed packages");
22622                pw.println("    s[hared-users]: dump shared user IDs");
22623                pw.println("    m[essages]: print collected runtime messages");
22624                pw.println("    v[erifiers]: print package verifier info");
22625                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
22626                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
22627                pw.println("    version: print database version info");
22628                pw.println("    write: write current settings now");
22629                pw.println("    installs: details about install sessions");
22630                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
22631                pw.println("    dexopt: dump dexopt state");
22632                pw.println("    compiler-stats: dump compiler statistics");
22633                pw.println("    enabled-overlays: dump list of enabled overlay packages");
22634                pw.println("    <package.name>: info about given package");
22635                return;
22636            } else if ("--checkin".equals(opt)) {
22637                checkin = true;
22638            } else if ("-f".equals(opt)) {
22639                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
22640            } else if ("--proto".equals(opt)) {
22641                dumpProto(fd);
22642                return;
22643            } else {
22644                pw.println("Unknown argument: " + opt + "; use -h for help");
22645            }
22646        }
22647
22648        // Is the caller requesting to dump a particular piece of data?
22649        if (opti < args.length) {
22650            String cmd = args[opti];
22651            opti++;
22652            // Is this a package name?
22653            if ("android".equals(cmd) || cmd.contains(".")) {
22654                packageName = cmd;
22655                // When dumping a single package, we always dump all of its
22656                // filter information since the amount of data will be reasonable.
22657                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
22658            } else if ("check-permission".equals(cmd)) {
22659                if (opti >= args.length) {
22660                    pw.println("Error: check-permission missing permission argument");
22661                    return;
22662                }
22663                String perm = args[opti];
22664                opti++;
22665                if (opti >= args.length) {
22666                    pw.println("Error: check-permission missing package argument");
22667                    return;
22668                }
22669
22670                String pkg = args[opti];
22671                opti++;
22672                int user = UserHandle.getUserId(Binder.getCallingUid());
22673                if (opti < args.length) {
22674                    try {
22675                        user = Integer.parseInt(args[opti]);
22676                    } catch (NumberFormatException e) {
22677                        pw.println("Error: check-permission user argument is not a number: "
22678                                + args[opti]);
22679                        return;
22680                    }
22681                }
22682
22683                // Normalize package name to handle renamed packages and static libs
22684                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
22685
22686                pw.println(checkPermission(perm, pkg, user));
22687                return;
22688            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
22689                dumpState.setDump(DumpState.DUMP_LIBS);
22690            } else if ("f".equals(cmd) || "features".equals(cmd)) {
22691                dumpState.setDump(DumpState.DUMP_FEATURES);
22692            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
22693                if (opti >= args.length) {
22694                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
22695                            | DumpState.DUMP_SERVICE_RESOLVERS
22696                            | DumpState.DUMP_RECEIVER_RESOLVERS
22697                            | DumpState.DUMP_CONTENT_RESOLVERS);
22698                } else {
22699                    while (opti < args.length) {
22700                        String name = args[opti];
22701                        if ("a".equals(name) || "activity".equals(name)) {
22702                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
22703                        } else if ("s".equals(name) || "service".equals(name)) {
22704                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
22705                        } else if ("r".equals(name) || "receiver".equals(name)) {
22706                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
22707                        } else if ("c".equals(name) || "content".equals(name)) {
22708                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
22709                        } else {
22710                            pw.println("Error: unknown resolver table type: " + name);
22711                            return;
22712                        }
22713                        opti++;
22714                    }
22715                }
22716            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
22717                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
22718            } else if ("permission".equals(cmd)) {
22719                if (opti >= args.length) {
22720                    pw.println("Error: permission requires permission name");
22721                    return;
22722                }
22723                permissionNames = new ArraySet<>();
22724                while (opti < args.length) {
22725                    permissionNames.add(args[opti]);
22726                    opti++;
22727                }
22728                dumpState.setDump(DumpState.DUMP_PERMISSIONS
22729                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
22730            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
22731                dumpState.setDump(DumpState.DUMP_PREFERRED);
22732            } else if ("preferred-xml".equals(cmd)) {
22733                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
22734                if (opti < args.length && "--full".equals(args[opti])) {
22735                    fullPreferred = true;
22736                    opti++;
22737                }
22738            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
22739                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
22740            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
22741                dumpState.setDump(DumpState.DUMP_PACKAGES);
22742            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
22743                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
22744            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
22745                dumpState.setDump(DumpState.DUMP_PROVIDERS);
22746            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
22747                dumpState.setDump(DumpState.DUMP_MESSAGES);
22748            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
22749                dumpState.setDump(DumpState.DUMP_VERIFIERS);
22750            } else if ("i".equals(cmd) || "ifv".equals(cmd)
22751                    || "intent-filter-verifiers".equals(cmd)) {
22752                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
22753            } else if ("version".equals(cmd)) {
22754                dumpState.setDump(DumpState.DUMP_VERSION);
22755            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
22756                dumpState.setDump(DumpState.DUMP_KEYSETS);
22757            } else if ("installs".equals(cmd)) {
22758                dumpState.setDump(DumpState.DUMP_INSTALLS);
22759            } else if ("frozen".equals(cmd)) {
22760                dumpState.setDump(DumpState.DUMP_FROZEN);
22761            } else if ("volumes".equals(cmd)) {
22762                dumpState.setDump(DumpState.DUMP_VOLUMES);
22763            } else if ("dexopt".equals(cmd)) {
22764                dumpState.setDump(DumpState.DUMP_DEXOPT);
22765            } else if ("compiler-stats".equals(cmd)) {
22766                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
22767            } else if ("changes".equals(cmd)) {
22768                dumpState.setDump(DumpState.DUMP_CHANGES);
22769            } else if ("write".equals(cmd)) {
22770                synchronized (mPackages) {
22771                    mSettings.writeLPr();
22772                    pw.println("Settings written.");
22773                    return;
22774                }
22775            }
22776        }
22777
22778        if (checkin) {
22779            pw.println("vers,1");
22780        }
22781
22782        // reader
22783        synchronized (mPackages) {
22784            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
22785                if (!checkin) {
22786                    if (dumpState.onTitlePrinted())
22787                        pw.println();
22788                    pw.println("Database versions:");
22789                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
22790                }
22791            }
22792
22793            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
22794                if (!checkin) {
22795                    if (dumpState.onTitlePrinted())
22796                        pw.println();
22797                    pw.println("Verifiers:");
22798                    pw.print("  Required: ");
22799                    pw.print(mRequiredVerifierPackage);
22800                    pw.print(" (uid=");
22801                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22802                            UserHandle.USER_SYSTEM));
22803                    pw.println(")");
22804                } else if (mRequiredVerifierPackage != null) {
22805                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
22806                    pw.print(",");
22807                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22808                            UserHandle.USER_SYSTEM));
22809                }
22810            }
22811
22812            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
22813                    packageName == null) {
22814                if (mIntentFilterVerifierComponent != null) {
22815                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22816                    if (!checkin) {
22817                        if (dumpState.onTitlePrinted())
22818                            pw.println();
22819                        pw.println("Intent Filter Verifier:");
22820                        pw.print("  Using: ");
22821                        pw.print(verifierPackageName);
22822                        pw.print(" (uid=");
22823                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22824                                UserHandle.USER_SYSTEM));
22825                        pw.println(")");
22826                    } else if (verifierPackageName != null) {
22827                        pw.print("ifv,"); pw.print(verifierPackageName);
22828                        pw.print(",");
22829                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22830                                UserHandle.USER_SYSTEM));
22831                    }
22832                } else {
22833                    pw.println();
22834                    pw.println("No Intent Filter Verifier available!");
22835                }
22836            }
22837
22838            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
22839                boolean printedHeader = false;
22840                final Iterator<String> it = mSharedLibraries.keySet().iterator();
22841                while (it.hasNext()) {
22842                    String libName = it.next();
22843                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22844                    if (versionedLib == null) {
22845                        continue;
22846                    }
22847                    final int versionCount = versionedLib.size();
22848                    for (int i = 0; i < versionCount; i++) {
22849                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
22850                        if (!checkin) {
22851                            if (!printedHeader) {
22852                                if (dumpState.onTitlePrinted())
22853                                    pw.println();
22854                                pw.println("Libraries:");
22855                                printedHeader = true;
22856                            }
22857                            pw.print("  ");
22858                        } else {
22859                            pw.print("lib,");
22860                        }
22861                        pw.print(libEntry.info.getName());
22862                        if (libEntry.info.isStatic()) {
22863                            pw.print(" version=" + libEntry.info.getVersion());
22864                        }
22865                        if (!checkin) {
22866                            pw.print(" -> ");
22867                        }
22868                        if (libEntry.path != null) {
22869                            pw.print(" (jar) ");
22870                            pw.print(libEntry.path);
22871                        } else {
22872                            pw.print(" (apk) ");
22873                            pw.print(libEntry.apk);
22874                        }
22875                        pw.println();
22876                    }
22877                }
22878            }
22879
22880            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
22881                if (dumpState.onTitlePrinted())
22882                    pw.println();
22883                if (!checkin) {
22884                    pw.println("Features:");
22885                }
22886
22887                synchronized (mAvailableFeatures) {
22888                    for (FeatureInfo feat : mAvailableFeatures.values()) {
22889                        if (checkin) {
22890                            pw.print("feat,");
22891                            pw.print(feat.name);
22892                            pw.print(",");
22893                            pw.println(feat.version);
22894                        } else {
22895                            pw.print("  ");
22896                            pw.print(feat.name);
22897                            if (feat.version > 0) {
22898                                pw.print(" version=");
22899                                pw.print(feat.version);
22900                            }
22901                            pw.println();
22902                        }
22903                    }
22904                }
22905            }
22906
22907            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
22908                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
22909                        : "Activity Resolver Table:", "  ", packageName,
22910                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22911                    dumpState.setTitlePrinted(true);
22912                }
22913            }
22914            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
22915                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
22916                        : "Receiver Resolver Table:", "  ", packageName,
22917                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22918                    dumpState.setTitlePrinted(true);
22919                }
22920            }
22921            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
22922                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
22923                        : "Service Resolver Table:", "  ", packageName,
22924                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22925                    dumpState.setTitlePrinted(true);
22926                }
22927            }
22928            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
22929                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
22930                        : "Provider Resolver Table:", "  ", packageName,
22931                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22932                    dumpState.setTitlePrinted(true);
22933                }
22934            }
22935
22936            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22937                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22938                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22939                    int user = mSettings.mPreferredActivities.keyAt(i);
22940                    if (pir.dump(pw,
22941                            dumpState.getTitlePrinted()
22942                                ? "\nPreferred Activities User " + user + ":"
22943                                : "Preferred Activities User " + user + ":", "  ",
22944                            packageName, true, false)) {
22945                        dumpState.setTitlePrinted(true);
22946                    }
22947                }
22948            }
22949
22950            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22951                pw.flush();
22952                FileOutputStream fout = new FileOutputStream(fd);
22953                BufferedOutputStream str = new BufferedOutputStream(fout);
22954                XmlSerializer serializer = new FastXmlSerializer();
22955                try {
22956                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
22957                    serializer.startDocument(null, true);
22958                    serializer.setFeature(
22959                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22960                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22961                    serializer.endDocument();
22962                    serializer.flush();
22963                } catch (IllegalArgumentException e) {
22964                    pw.println("Failed writing: " + e);
22965                } catch (IllegalStateException e) {
22966                    pw.println("Failed writing: " + e);
22967                } catch (IOException e) {
22968                    pw.println("Failed writing: " + e);
22969                }
22970            }
22971
22972            if (!checkin
22973                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22974                    && packageName == null) {
22975                pw.println();
22976                int count = mSettings.mPackages.size();
22977                if (count == 0) {
22978                    pw.println("No applications!");
22979                    pw.println();
22980                } else {
22981                    final String prefix = "  ";
22982                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22983                    if (allPackageSettings.size() == 0) {
22984                        pw.println("No domain preferred apps!");
22985                        pw.println();
22986                    } else {
22987                        pw.println("App verification status:");
22988                        pw.println();
22989                        count = 0;
22990                        for (PackageSetting ps : allPackageSettings) {
22991                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22992                            if (ivi == null || ivi.getPackageName() == null) continue;
22993                            pw.println(prefix + "Package: " + ivi.getPackageName());
22994                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
22995                            pw.println(prefix + "Status:  " + ivi.getStatusString());
22996                            pw.println();
22997                            count++;
22998                        }
22999                        if (count == 0) {
23000                            pw.println(prefix + "No app verification established.");
23001                            pw.println();
23002                        }
23003                        for (int userId : sUserManager.getUserIds()) {
23004                            pw.println("App linkages for user " + userId + ":");
23005                            pw.println();
23006                            count = 0;
23007                            for (PackageSetting ps : allPackageSettings) {
23008                                final long status = ps.getDomainVerificationStatusForUser(userId);
23009                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
23010                                        && !DEBUG_DOMAIN_VERIFICATION) {
23011                                    continue;
23012                                }
23013                                pw.println(prefix + "Package: " + ps.name);
23014                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
23015                                String statusStr = IntentFilterVerificationInfo.
23016                                        getStatusStringFromValue(status);
23017                                pw.println(prefix + "Status:  " + statusStr);
23018                                pw.println();
23019                                count++;
23020                            }
23021                            if (count == 0) {
23022                                pw.println(prefix + "No configured app linkages.");
23023                                pw.println();
23024                            }
23025                        }
23026                    }
23027                }
23028            }
23029
23030            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
23031                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
23032                if (packageName == null && permissionNames == null) {
23033                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
23034                        if (iperm == 0) {
23035                            if (dumpState.onTitlePrinted())
23036                                pw.println();
23037                            pw.println("AppOp Permissions:");
23038                        }
23039                        pw.print("  AppOp Permission ");
23040                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
23041                        pw.println(":");
23042                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
23043                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
23044                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
23045                        }
23046                    }
23047                }
23048            }
23049
23050            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
23051                boolean printedSomething = false;
23052                for (PackageParser.Provider p : mProviders.mProviders.values()) {
23053                    if (packageName != null && !packageName.equals(p.info.packageName)) {
23054                        continue;
23055                    }
23056                    if (!printedSomething) {
23057                        if (dumpState.onTitlePrinted())
23058                            pw.println();
23059                        pw.println("Registered ContentProviders:");
23060                        printedSomething = true;
23061                    }
23062                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
23063                    pw.print("    "); pw.println(p.toString());
23064                }
23065                printedSomething = false;
23066                for (Map.Entry<String, PackageParser.Provider> entry :
23067                        mProvidersByAuthority.entrySet()) {
23068                    PackageParser.Provider p = entry.getValue();
23069                    if (packageName != null && !packageName.equals(p.info.packageName)) {
23070                        continue;
23071                    }
23072                    if (!printedSomething) {
23073                        if (dumpState.onTitlePrinted())
23074                            pw.println();
23075                        pw.println("ContentProvider Authorities:");
23076                        printedSomething = true;
23077                    }
23078                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
23079                    pw.print("    "); pw.println(p.toString());
23080                    if (p.info != null && p.info.applicationInfo != null) {
23081                        final String appInfo = p.info.applicationInfo.toString();
23082                        pw.print("      applicationInfo="); pw.println(appInfo);
23083                    }
23084                }
23085            }
23086
23087            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
23088                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
23089            }
23090
23091            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
23092                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
23093            }
23094
23095            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
23096                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
23097            }
23098
23099            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
23100                if (dumpState.onTitlePrinted()) pw.println();
23101                pw.println("Package Changes:");
23102                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
23103                final int K = mChangedPackages.size();
23104                for (int i = 0; i < K; i++) {
23105                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
23106                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
23107                    final int N = changes.size();
23108                    if (N == 0) {
23109                        pw.print("    "); pw.println("No packages changed");
23110                    } else {
23111                        for (int j = 0; j < N; j++) {
23112                            final String pkgName = changes.valueAt(j);
23113                            final int sequenceNumber = changes.keyAt(j);
23114                            pw.print("    ");
23115                            pw.print("seq=");
23116                            pw.print(sequenceNumber);
23117                            pw.print(", package=");
23118                            pw.println(pkgName);
23119                        }
23120                    }
23121                }
23122            }
23123
23124            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
23125                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
23126            }
23127
23128            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
23129                // XXX should handle packageName != null by dumping only install data that
23130                // the given package is involved with.
23131                if (dumpState.onTitlePrinted()) pw.println();
23132
23133                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
23134                ipw.println();
23135                ipw.println("Frozen packages:");
23136                ipw.increaseIndent();
23137                if (mFrozenPackages.size() == 0) {
23138                    ipw.println("(none)");
23139                } else {
23140                    for (int i = 0; i < mFrozenPackages.size(); i++) {
23141                        ipw.println(mFrozenPackages.valueAt(i));
23142                    }
23143                }
23144                ipw.decreaseIndent();
23145            }
23146
23147            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
23148                if (dumpState.onTitlePrinted()) pw.println();
23149
23150                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
23151                ipw.println();
23152                ipw.println("Loaded volumes:");
23153                ipw.increaseIndent();
23154                if (mLoadedVolumes.size() == 0) {
23155                    ipw.println("(none)");
23156                } else {
23157                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
23158                        ipw.println(mLoadedVolumes.valueAt(i));
23159                    }
23160                }
23161                ipw.decreaseIndent();
23162            }
23163
23164            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
23165                if (dumpState.onTitlePrinted()) pw.println();
23166                dumpDexoptStateLPr(pw, packageName);
23167            }
23168
23169            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
23170                if (dumpState.onTitlePrinted()) pw.println();
23171                dumpCompilerStatsLPr(pw, packageName);
23172            }
23173
23174            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
23175                if (dumpState.onTitlePrinted()) pw.println();
23176                mSettings.dumpReadMessagesLPr(pw, dumpState);
23177
23178                pw.println();
23179                pw.println("Package warning messages:");
23180                BufferedReader in = null;
23181                String line = null;
23182                try {
23183                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
23184                    while ((line = in.readLine()) != null) {
23185                        if (line.contains("ignored: updated version")) continue;
23186                        pw.println(line);
23187                    }
23188                } catch (IOException ignored) {
23189                } finally {
23190                    IoUtils.closeQuietly(in);
23191                }
23192            }
23193
23194            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
23195                BufferedReader in = null;
23196                String line = null;
23197                try {
23198                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
23199                    while ((line = in.readLine()) != null) {
23200                        if (line.contains("ignored: updated version")) continue;
23201                        pw.print("msg,");
23202                        pw.println(line);
23203                    }
23204                } catch (IOException ignored) {
23205                } finally {
23206                    IoUtils.closeQuietly(in);
23207                }
23208            }
23209        }
23210
23211        // PackageInstaller should be called outside of mPackages lock
23212        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
23213            // XXX should handle packageName != null by dumping only install data that
23214            // the given package is involved with.
23215            if (dumpState.onTitlePrinted()) pw.println();
23216            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
23217        }
23218    }
23219
23220    private void dumpProto(FileDescriptor fd) {
23221        final ProtoOutputStream proto = new ProtoOutputStream(fd);
23222
23223        synchronized (mPackages) {
23224            final long requiredVerifierPackageToken =
23225                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
23226            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
23227            proto.write(
23228                    PackageServiceDumpProto.PackageShortProto.UID,
23229                    getPackageUid(
23230                            mRequiredVerifierPackage,
23231                            MATCH_DEBUG_TRIAGED_MISSING,
23232                            UserHandle.USER_SYSTEM));
23233            proto.end(requiredVerifierPackageToken);
23234
23235            if (mIntentFilterVerifierComponent != null) {
23236                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
23237                final long verifierPackageToken =
23238                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
23239                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
23240                proto.write(
23241                        PackageServiceDumpProto.PackageShortProto.UID,
23242                        getPackageUid(
23243                                verifierPackageName,
23244                                MATCH_DEBUG_TRIAGED_MISSING,
23245                                UserHandle.USER_SYSTEM));
23246                proto.end(verifierPackageToken);
23247            }
23248
23249            dumpSharedLibrariesProto(proto);
23250            dumpFeaturesProto(proto);
23251            mSettings.dumpPackagesProto(proto);
23252            mSettings.dumpSharedUsersProto(proto);
23253            dumpMessagesProto(proto);
23254        }
23255        proto.flush();
23256    }
23257
23258    private void dumpMessagesProto(ProtoOutputStream proto) {
23259        BufferedReader in = null;
23260        String line = null;
23261        try {
23262            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
23263            while ((line = in.readLine()) != null) {
23264                if (line.contains("ignored: updated version")) continue;
23265                proto.write(PackageServiceDumpProto.MESSAGES, line);
23266            }
23267        } catch (IOException ignored) {
23268        } finally {
23269            IoUtils.closeQuietly(in);
23270        }
23271    }
23272
23273    private void dumpFeaturesProto(ProtoOutputStream proto) {
23274        synchronized (mAvailableFeatures) {
23275            final int count = mAvailableFeatures.size();
23276            for (int i = 0; i < count; i++) {
23277                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
23278                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
23279                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
23280                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
23281                proto.end(featureToken);
23282            }
23283        }
23284    }
23285
23286    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
23287        final int count = mSharedLibraries.size();
23288        for (int i = 0; i < count; i++) {
23289            final String libName = mSharedLibraries.keyAt(i);
23290            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
23291            if (versionedLib == null) {
23292                continue;
23293            }
23294            final int versionCount = versionedLib.size();
23295            for (int j = 0; j < versionCount; j++) {
23296                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
23297                final long sharedLibraryToken =
23298                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
23299                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
23300                final boolean isJar = (libEntry.path != null);
23301                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
23302                if (isJar) {
23303                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
23304                } else {
23305                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
23306                }
23307                proto.end(sharedLibraryToken);
23308            }
23309        }
23310    }
23311
23312    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
23313        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
23314        ipw.println();
23315        ipw.println("Dexopt state:");
23316        ipw.increaseIndent();
23317        Collection<PackageParser.Package> packages = null;
23318        if (packageName != null) {
23319            PackageParser.Package targetPackage = mPackages.get(packageName);
23320            if (targetPackage != null) {
23321                packages = Collections.singletonList(targetPackage);
23322            } else {
23323                ipw.println("Unable to find package: " + packageName);
23324                return;
23325            }
23326        } else {
23327            packages = mPackages.values();
23328        }
23329
23330        for (PackageParser.Package pkg : packages) {
23331            ipw.println("[" + pkg.packageName + "]");
23332            ipw.increaseIndent();
23333            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
23334                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
23335            ipw.decreaseIndent();
23336        }
23337    }
23338
23339    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
23340        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
23341        ipw.println();
23342        ipw.println("Compiler stats:");
23343        ipw.increaseIndent();
23344        Collection<PackageParser.Package> packages = null;
23345        if (packageName != null) {
23346            PackageParser.Package targetPackage = mPackages.get(packageName);
23347            if (targetPackage != null) {
23348                packages = Collections.singletonList(targetPackage);
23349            } else {
23350                ipw.println("Unable to find package: " + packageName);
23351                return;
23352            }
23353        } else {
23354            packages = mPackages.values();
23355        }
23356
23357        for (PackageParser.Package pkg : packages) {
23358            ipw.println("[" + pkg.packageName + "]");
23359            ipw.increaseIndent();
23360
23361            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
23362            if (stats == null) {
23363                ipw.println("(No recorded stats)");
23364            } else {
23365                stats.dump(ipw);
23366            }
23367            ipw.decreaseIndent();
23368        }
23369    }
23370
23371    private String dumpDomainString(String packageName) {
23372        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
23373                .getList();
23374        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
23375
23376        ArraySet<String> result = new ArraySet<>();
23377        if (iviList.size() > 0) {
23378            for (IntentFilterVerificationInfo ivi : iviList) {
23379                for (String host : ivi.getDomains()) {
23380                    result.add(host);
23381                }
23382            }
23383        }
23384        if (filters != null && filters.size() > 0) {
23385            for (IntentFilter filter : filters) {
23386                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
23387                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
23388                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
23389                    result.addAll(filter.getHostsList());
23390                }
23391            }
23392        }
23393
23394        StringBuilder sb = new StringBuilder(result.size() * 16);
23395        for (String domain : result) {
23396            if (sb.length() > 0) sb.append(" ");
23397            sb.append(domain);
23398        }
23399        return sb.toString();
23400    }
23401
23402    // ------- apps on sdcard specific code -------
23403    static final boolean DEBUG_SD_INSTALL = false;
23404
23405    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
23406
23407    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
23408
23409    private boolean mMediaMounted = false;
23410
23411    static String getEncryptKey() {
23412        try {
23413            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
23414                    SD_ENCRYPTION_KEYSTORE_NAME);
23415            if (sdEncKey == null) {
23416                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
23417                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
23418                if (sdEncKey == null) {
23419                    Slog.e(TAG, "Failed to create encryption keys");
23420                    return null;
23421                }
23422            }
23423            return sdEncKey;
23424        } catch (NoSuchAlgorithmException nsae) {
23425            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
23426            return null;
23427        } catch (IOException ioe) {
23428            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
23429            return null;
23430        }
23431    }
23432
23433    /*
23434     * Update media status on PackageManager.
23435     */
23436    @Override
23437    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
23438        enforceSystemOrRoot("Media status can only be updated by the system");
23439        // reader; this apparently protects mMediaMounted, but should probably
23440        // be a different lock in that case.
23441        synchronized (mPackages) {
23442            Log.i(TAG, "Updating external media status from "
23443                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
23444                    + (mediaStatus ? "mounted" : "unmounted"));
23445            if (DEBUG_SD_INSTALL)
23446                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
23447                        + ", mMediaMounted=" + mMediaMounted);
23448            if (mediaStatus == mMediaMounted) {
23449                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
23450                        : 0, -1);
23451                mHandler.sendMessage(msg);
23452                return;
23453            }
23454            mMediaMounted = mediaStatus;
23455        }
23456        // Queue up an async operation since the package installation may take a
23457        // little while.
23458        mHandler.post(new Runnable() {
23459            public void run() {
23460                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
23461            }
23462        });
23463    }
23464
23465    /**
23466     * Called by StorageManagerService when the initial ASECs to scan are available.
23467     * Should block until all the ASEC containers are finished being scanned.
23468     */
23469    public void scanAvailableAsecs() {
23470        updateExternalMediaStatusInner(true, false, false);
23471    }
23472
23473    /*
23474     * Collect information of applications on external media, map them against
23475     * existing containers and update information based on current mount status.
23476     * Please note that we always have to report status if reportStatus has been
23477     * set to true especially when unloading packages.
23478     */
23479    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
23480            boolean externalStorage) {
23481        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
23482        int[] uidArr = EmptyArray.INT;
23483
23484        final String[] list = PackageHelper.getSecureContainerList();
23485        if (ArrayUtils.isEmpty(list)) {
23486            Log.i(TAG, "No secure containers found");
23487        } else {
23488            // Process list of secure containers and categorize them
23489            // as active or stale based on their package internal state.
23490
23491            // reader
23492            synchronized (mPackages) {
23493                for (String cid : list) {
23494                    // Leave stages untouched for now; installer service owns them
23495                    if (PackageInstallerService.isStageName(cid)) continue;
23496
23497                    if (DEBUG_SD_INSTALL)
23498                        Log.i(TAG, "Processing container " + cid);
23499                    String pkgName = getAsecPackageName(cid);
23500                    if (pkgName == null) {
23501                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
23502                        continue;
23503                    }
23504                    if (DEBUG_SD_INSTALL)
23505                        Log.i(TAG, "Looking for pkg : " + pkgName);
23506
23507                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
23508                    if (ps == null) {
23509                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
23510                        continue;
23511                    }
23512
23513                    /*
23514                     * Skip packages that are not external if we're unmounting
23515                     * external storage.
23516                     */
23517                    if (externalStorage && !isMounted && !isExternal(ps)) {
23518                        continue;
23519                    }
23520
23521                    final AsecInstallArgs args = new AsecInstallArgs(cid,
23522                            getAppDexInstructionSets(ps), ps.isForwardLocked());
23523                    // The package status is changed only if the code path
23524                    // matches between settings and the container id.
23525                    if (ps.codePathString != null
23526                            && ps.codePathString.startsWith(args.getCodePath())) {
23527                        if (DEBUG_SD_INSTALL) {
23528                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
23529                                    + " at code path: " + ps.codePathString);
23530                        }
23531
23532                        // We do have a valid package installed on sdcard
23533                        processCids.put(args, ps.codePathString);
23534                        final int uid = ps.appId;
23535                        if (uid != -1) {
23536                            uidArr = ArrayUtils.appendInt(uidArr, uid);
23537                        }
23538                    } else {
23539                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
23540                                + ps.codePathString);
23541                    }
23542                }
23543            }
23544
23545            Arrays.sort(uidArr);
23546        }
23547
23548        // Process packages with valid entries.
23549        if (isMounted) {
23550            if (DEBUG_SD_INSTALL)
23551                Log.i(TAG, "Loading packages");
23552            loadMediaPackages(processCids, uidArr, externalStorage);
23553            startCleaningPackages();
23554            mInstallerService.onSecureContainersAvailable();
23555        } else {
23556            if (DEBUG_SD_INSTALL)
23557                Log.i(TAG, "Unloading packages");
23558            unloadMediaPackages(processCids, uidArr, reportStatus);
23559        }
23560    }
23561
23562    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23563            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
23564        final int size = infos.size();
23565        final String[] packageNames = new String[size];
23566        final int[] packageUids = new int[size];
23567        for (int i = 0; i < size; i++) {
23568            final ApplicationInfo info = infos.get(i);
23569            packageNames[i] = info.packageName;
23570            packageUids[i] = info.uid;
23571        }
23572        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
23573                finishedReceiver);
23574    }
23575
23576    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23577            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
23578        sendResourcesChangedBroadcast(mediaStatus, replacing,
23579                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
23580    }
23581
23582    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23583            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
23584        int size = pkgList.length;
23585        if (size > 0) {
23586            // Send broadcasts here
23587            Bundle extras = new Bundle();
23588            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
23589            if (uidArr != null) {
23590                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
23591            }
23592            if (replacing) {
23593                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
23594            }
23595            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
23596                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
23597            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
23598        }
23599    }
23600
23601   /*
23602     * Look at potentially valid container ids from processCids If package
23603     * information doesn't match the one on record or package scanning fails,
23604     * the cid is added to list of removeCids. We currently don't delete stale
23605     * containers.
23606     */
23607    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
23608            boolean externalStorage) {
23609        ArrayList<String> pkgList = new ArrayList<String>();
23610        Set<AsecInstallArgs> keys = processCids.keySet();
23611
23612        for (AsecInstallArgs args : keys) {
23613            String codePath = processCids.get(args);
23614            if (DEBUG_SD_INSTALL)
23615                Log.i(TAG, "Loading container : " + args.cid);
23616            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
23617            try {
23618                // Make sure there are no container errors first.
23619                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
23620                    Slog.e(TAG, "Failed to mount cid : " + args.cid
23621                            + " when installing from sdcard");
23622                    continue;
23623                }
23624                // Check code path here.
23625                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
23626                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
23627                            + " does not match one in settings " + codePath);
23628                    continue;
23629                }
23630                // Parse package
23631                int parseFlags = mDefParseFlags;
23632                if (args.isExternalAsec()) {
23633                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
23634                }
23635                if (args.isFwdLocked()) {
23636                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
23637                }
23638
23639                synchronized (mInstallLock) {
23640                    PackageParser.Package pkg = null;
23641                    try {
23642                        // Sadly we don't know the package name yet to freeze it
23643                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
23644                                SCAN_IGNORE_FROZEN, 0, null);
23645                    } catch (PackageManagerException e) {
23646                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
23647                    }
23648                    // Scan the package
23649                    if (pkg != null) {
23650                        /*
23651                         * TODO why is the lock being held? doPostInstall is
23652                         * called in other places without the lock. This needs
23653                         * to be straightened out.
23654                         */
23655                        // writer
23656                        synchronized (mPackages) {
23657                            retCode = PackageManager.INSTALL_SUCCEEDED;
23658                            pkgList.add(pkg.packageName);
23659                            // Post process args
23660                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
23661                                    pkg.applicationInfo.uid);
23662                        }
23663                    } else {
23664                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
23665                    }
23666                }
23667
23668            } finally {
23669                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
23670                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
23671                }
23672            }
23673        }
23674        // writer
23675        synchronized (mPackages) {
23676            // If the platform SDK has changed since the last time we booted,
23677            // we need to re-grant app permission to catch any new ones that
23678            // appear. This is really a hack, and means that apps can in some
23679            // cases get permissions that the user didn't initially explicitly
23680            // allow... it would be nice to have some better way to handle
23681            // this situation.
23682            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
23683                    : mSettings.getInternalVersion();
23684            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
23685                    : StorageManager.UUID_PRIVATE_INTERNAL;
23686
23687            int updateFlags = UPDATE_PERMISSIONS_ALL;
23688            if (ver.sdkVersion != mSdkVersion) {
23689                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23690                        + mSdkVersion + "; regranting permissions for external");
23691                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23692            }
23693            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23694
23695            // Yay, everything is now upgraded
23696            ver.forceCurrent();
23697
23698            // can downgrade to reader
23699            // Persist settings
23700            mSettings.writeLPr();
23701        }
23702        // Send a broadcast to let everyone know we are done processing
23703        if (pkgList.size() > 0) {
23704            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
23705        }
23706    }
23707
23708   /*
23709     * Utility method to unload a list of specified containers
23710     */
23711    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
23712        // Just unmount all valid containers.
23713        for (AsecInstallArgs arg : cidArgs) {
23714            synchronized (mInstallLock) {
23715                arg.doPostDeleteLI(false);
23716           }
23717       }
23718   }
23719
23720    /*
23721     * Unload packages mounted on external media. This involves deleting package
23722     * data from internal structures, sending broadcasts about disabled packages,
23723     * gc'ing to free up references, unmounting all secure containers
23724     * corresponding to packages on external media, and posting a
23725     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
23726     * that we always have to post this message if status has been requested no
23727     * matter what.
23728     */
23729    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
23730            final boolean reportStatus) {
23731        if (DEBUG_SD_INSTALL)
23732            Log.i(TAG, "unloading media packages");
23733        ArrayList<String> pkgList = new ArrayList<String>();
23734        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
23735        final Set<AsecInstallArgs> keys = processCids.keySet();
23736        for (AsecInstallArgs args : keys) {
23737            String pkgName = args.getPackageName();
23738            if (DEBUG_SD_INSTALL)
23739                Log.i(TAG, "Trying to unload pkg : " + pkgName);
23740            // Delete package internally
23741            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23742            synchronized (mInstallLock) {
23743                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23744                final boolean res;
23745                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
23746                        "unloadMediaPackages")) {
23747                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
23748                            null);
23749                }
23750                if (res) {
23751                    pkgList.add(pkgName);
23752                } else {
23753                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
23754                    failedList.add(args);
23755                }
23756            }
23757        }
23758
23759        // reader
23760        synchronized (mPackages) {
23761            // We didn't update the settings after removing each package;
23762            // write them now for all packages.
23763            mSettings.writeLPr();
23764        }
23765
23766        // We have to absolutely send UPDATED_MEDIA_STATUS only
23767        // after confirming that all the receivers processed the ordered
23768        // broadcast when packages get disabled, force a gc to clean things up.
23769        // and unload all the containers.
23770        if (pkgList.size() > 0) {
23771            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
23772                    new IIntentReceiver.Stub() {
23773                public void performReceive(Intent intent, int resultCode, String data,
23774                        Bundle extras, boolean ordered, boolean sticky,
23775                        int sendingUser) throws RemoteException {
23776                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
23777                            reportStatus ? 1 : 0, 1, keys);
23778                    mHandler.sendMessage(msg);
23779                }
23780            });
23781        } else {
23782            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
23783                    keys);
23784            mHandler.sendMessage(msg);
23785        }
23786    }
23787
23788    private void loadPrivatePackages(final VolumeInfo vol) {
23789        mHandler.post(new Runnable() {
23790            @Override
23791            public void run() {
23792                loadPrivatePackagesInner(vol);
23793            }
23794        });
23795    }
23796
23797    private void loadPrivatePackagesInner(VolumeInfo vol) {
23798        final String volumeUuid = vol.fsUuid;
23799        if (TextUtils.isEmpty(volumeUuid)) {
23800            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
23801            return;
23802        }
23803
23804        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
23805        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
23806        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
23807
23808        final VersionInfo ver;
23809        final List<PackageSetting> packages;
23810        synchronized (mPackages) {
23811            ver = mSettings.findOrCreateVersion(volumeUuid);
23812            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23813        }
23814
23815        for (PackageSetting ps : packages) {
23816            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
23817            synchronized (mInstallLock) {
23818                final PackageParser.Package pkg;
23819                try {
23820                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
23821                    loaded.add(pkg.applicationInfo);
23822
23823                } catch (PackageManagerException e) {
23824                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
23825                }
23826
23827                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
23828                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
23829                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
23830                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
23831                }
23832            }
23833        }
23834
23835        // Reconcile app data for all started/unlocked users
23836        final StorageManager sm = mContext.getSystemService(StorageManager.class);
23837        final UserManager um = mContext.getSystemService(UserManager.class);
23838        UserManagerInternal umInternal = getUserManagerInternal();
23839        for (UserInfo user : um.getUsers()) {
23840            final int flags;
23841            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23842                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23843            } else if (umInternal.isUserRunning(user.id)) {
23844                flags = StorageManager.FLAG_STORAGE_DE;
23845            } else {
23846                continue;
23847            }
23848
23849            try {
23850                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
23851                synchronized (mInstallLock) {
23852                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
23853                }
23854            } catch (IllegalStateException e) {
23855                // Device was probably ejected, and we'll process that event momentarily
23856                Slog.w(TAG, "Failed to prepare storage: " + e);
23857            }
23858        }
23859
23860        synchronized (mPackages) {
23861            int updateFlags = UPDATE_PERMISSIONS_ALL;
23862            if (ver.sdkVersion != mSdkVersion) {
23863                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23864                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
23865                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23866            }
23867            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23868
23869            // Yay, everything is now upgraded
23870            ver.forceCurrent();
23871
23872            mSettings.writeLPr();
23873        }
23874
23875        for (PackageFreezer freezer : freezers) {
23876            freezer.close();
23877        }
23878
23879        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
23880        sendResourcesChangedBroadcast(true, false, loaded, null);
23881        mLoadedVolumes.add(vol.getId());
23882    }
23883
23884    private void unloadPrivatePackages(final VolumeInfo vol) {
23885        mHandler.post(new Runnable() {
23886            @Override
23887            public void run() {
23888                unloadPrivatePackagesInner(vol);
23889            }
23890        });
23891    }
23892
23893    private void unloadPrivatePackagesInner(VolumeInfo vol) {
23894        final String volumeUuid = vol.fsUuid;
23895        if (TextUtils.isEmpty(volumeUuid)) {
23896            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
23897            return;
23898        }
23899
23900        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
23901        synchronized (mInstallLock) {
23902        synchronized (mPackages) {
23903            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
23904            for (PackageSetting ps : packages) {
23905                if (ps.pkg == null) continue;
23906
23907                final ApplicationInfo info = ps.pkg.applicationInfo;
23908                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23909                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23910
23911                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
23912                        "unloadPrivatePackagesInner")) {
23913                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
23914                            false, null)) {
23915                        unloaded.add(info);
23916                    } else {
23917                        Slog.w(TAG, "Failed to unload " + ps.codePath);
23918                    }
23919                }
23920
23921                // Try very hard to release any references to this package
23922                // so we don't risk the system server being killed due to
23923                // open FDs
23924                AttributeCache.instance().removePackage(ps.name);
23925            }
23926
23927            mSettings.writeLPr();
23928        }
23929        }
23930
23931        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
23932        sendResourcesChangedBroadcast(false, false, unloaded, null);
23933        mLoadedVolumes.remove(vol.getId());
23934
23935        // Try very hard to release any references to this path so we don't risk
23936        // the system server being killed due to open FDs
23937        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
23938
23939        for (int i = 0; i < 3; i++) {
23940            System.gc();
23941            System.runFinalization();
23942        }
23943    }
23944
23945    private void assertPackageKnown(String volumeUuid, String packageName)
23946            throws PackageManagerException {
23947        synchronized (mPackages) {
23948            // Normalize package name to handle renamed packages
23949            packageName = normalizePackageNameLPr(packageName);
23950
23951            final PackageSetting ps = mSettings.mPackages.get(packageName);
23952            if (ps == null) {
23953                throw new PackageManagerException("Package " + packageName + " is unknown");
23954            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23955                throw new PackageManagerException(
23956                        "Package " + packageName + " found on unknown volume " + volumeUuid
23957                                + "; expected volume " + ps.volumeUuid);
23958            }
23959        }
23960    }
23961
23962    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23963            throws PackageManagerException {
23964        synchronized (mPackages) {
23965            // Normalize package name to handle renamed packages
23966            packageName = normalizePackageNameLPr(packageName);
23967
23968            final PackageSetting ps = mSettings.mPackages.get(packageName);
23969            if (ps == null) {
23970                throw new PackageManagerException("Package " + packageName + " is unknown");
23971            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23972                throw new PackageManagerException(
23973                        "Package " + packageName + " found on unknown volume " + volumeUuid
23974                                + "; expected volume " + ps.volumeUuid);
23975            } else if (!ps.getInstalled(userId)) {
23976                throw new PackageManagerException(
23977                        "Package " + packageName + " not installed for user " + userId);
23978            }
23979        }
23980    }
23981
23982    private List<String> collectAbsoluteCodePaths() {
23983        synchronized (mPackages) {
23984            List<String> codePaths = new ArrayList<>();
23985            final int packageCount = mSettings.mPackages.size();
23986            for (int i = 0; i < packageCount; i++) {
23987                final PackageSetting ps = mSettings.mPackages.valueAt(i);
23988                codePaths.add(ps.codePath.getAbsolutePath());
23989            }
23990            return codePaths;
23991        }
23992    }
23993
23994    /**
23995     * Examine all apps present on given mounted volume, and destroy apps that
23996     * aren't expected, either due to uninstallation or reinstallation on
23997     * another volume.
23998     */
23999    private void reconcileApps(String volumeUuid) {
24000        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
24001        List<File> filesToDelete = null;
24002
24003        final File[] files = FileUtils.listFilesOrEmpty(
24004                Environment.getDataAppDirectory(volumeUuid));
24005        for (File file : files) {
24006            final boolean isPackage = (isApkFile(file) || file.isDirectory())
24007                    && !PackageInstallerService.isStageName(file.getName());
24008            if (!isPackage) {
24009                // Ignore entries which are not packages
24010                continue;
24011            }
24012
24013            String absolutePath = file.getAbsolutePath();
24014
24015            boolean pathValid = false;
24016            final int absoluteCodePathCount = absoluteCodePaths.size();
24017            for (int i = 0; i < absoluteCodePathCount; i++) {
24018                String absoluteCodePath = absoluteCodePaths.get(i);
24019                if (absolutePath.startsWith(absoluteCodePath)) {
24020                    pathValid = true;
24021                    break;
24022                }
24023            }
24024
24025            if (!pathValid) {
24026                if (filesToDelete == null) {
24027                    filesToDelete = new ArrayList<>();
24028                }
24029                filesToDelete.add(file);
24030            }
24031        }
24032
24033        if (filesToDelete != null) {
24034            final int fileToDeleteCount = filesToDelete.size();
24035            for (int i = 0; i < fileToDeleteCount; i++) {
24036                File fileToDelete = filesToDelete.get(i);
24037                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
24038                synchronized (mInstallLock) {
24039                    removeCodePathLI(fileToDelete);
24040                }
24041            }
24042        }
24043    }
24044
24045    /**
24046     * Reconcile all app data for the given user.
24047     * <p>
24048     * Verifies that directories exist and that ownership and labeling is
24049     * correct for all installed apps on all mounted volumes.
24050     */
24051    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
24052        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24053        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
24054            final String volumeUuid = vol.getFsUuid();
24055            synchronized (mInstallLock) {
24056                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
24057            }
24058        }
24059    }
24060
24061    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
24062            boolean migrateAppData) {
24063        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
24064    }
24065
24066    /**
24067     * Reconcile all app data on given mounted volume.
24068     * <p>
24069     * Destroys app data that isn't expected, either due to uninstallation or
24070     * reinstallation on another volume.
24071     * <p>
24072     * Verifies that directories exist and that ownership and labeling is
24073     * correct for all installed apps.
24074     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
24075     */
24076    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
24077            boolean migrateAppData, boolean onlyCoreApps) {
24078        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
24079                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
24080        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
24081
24082        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
24083        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
24084
24085        // First look for stale data that doesn't belong, and check if things
24086        // have changed since we did our last restorecon
24087        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
24088            if (StorageManager.isFileEncryptedNativeOrEmulated()
24089                    && !StorageManager.isUserKeyUnlocked(userId)) {
24090                throw new RuntimeException(
24091                        "Yikes, someone asked us to reconcile CE storage while " + userId
24092                                + " was still locked; this would have caused massive data loss!");
24093            }
24094
24095            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
24096            for (File file : files) {
24097                final String packageName = file.getName();
24098                try {
24099                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
24100                } catch (PackageManagerException e) {
24101                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
24102                    try {
24103                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
24104                                StorageManager.FLAG_STORAGE_CE, 0);
24105                    } catch (InstallerException e2) {
24106                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
24107                    }
24108                }
24109            }
24110        }
24111        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
24112            final File[] files = FileUtils.listFilesOrEmpty(deDir);
24113            for (File file : files) {
24114                final String packageName = file.getName();
24115                try {
24116                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
24117                } catch (PackageManagerException e) {
24118                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
24119                    try {
24120                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
24121                                StorageManager.FLAG_STORAGE_DE, 0);
24122                    } catch (InstallerException e2) {
24123                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
24124                    }
24125                }
24126            }
24127        }
24128
24129        // Ensure that data directories are ready to roll for all packages
24130        // installed for this volume and user
24131        final List<PackageSetting> packages;
24132        synchronized (mPackages) {
24133            packages = mSettings.getVolumePackagesLPr(volumeUuid);
24134        }
24135        int preparedCount = 0;
24136        for (PackageSetting ps : packages) {
24137            final String packageName = ps.name;
24138            if (ps.pkg == null) {
24139                Slog.w(TAG, "Odd, missing scanned package " + packageName);
24140                // TODO: might be due to legacy ASEC apps; we should circle back
24141                // and reconcile again once they're scanned
24142                continue;
24143            }
24144            // Skip non-core apps if requested
24145            if (onlyCoreApps && !ps.pkg.coreApp) {
24146                result.add(packageName);
24147                continue;
24148            }
24149
24150            if (ps.getInstalled(userId)) {
24151                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
24152                preparedCount++;
24153            }
24154        }
24155
24156        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
24157        return result;
24158    }
24159
24160    /**
24161     * Prepare app data for the given app just after it was installed or
24162     * upgraded. This method carefully only touches users that it's installed
24163     * for, and it forces a restorecon to handle any seinfo changes.
24164     * <p>
24165     * Verifies that directories exist and that ownership and labeling is
24166     * correct for all installed apps. If there is an ownership mismatch, it
24167     * will try recovering system apps by wiping data; third-party app data is
24168     * left intact.
24169     * <p>
24170     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
24171     */
24172    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
24173        final PackageSetting ps;
24174        synchronized (mPackages) {
24175            ps = mSettings.mPackages.get(pkg.packageName);
24176            mSettings.writeKernelMappingLPr(ps);
24177        }
24178
24179        final UserManager um = mContext.getSystemService(UserManager.class);
24180        UserManagerInternal umInternal = getUserManagerInternal();
24181        for (UserInfo user : um.getUsers()) {
24182            final int flags;
24183            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
24184                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
24185            } else if (umInternal.isUserRunning(user.id)) {
24186                flags = StorageManager.FLAG_STORAGE_DE;
24187            } else {
24188                continue;
24189            }
24190
24191            if (ps.getInstalled(user.id)) {
24192                // TODO: when user data is locked, mark that we're still dirty
24193                prepareAppDataLIF(pkg, user.id, flags);
24194            }
24195        }
24196    }
24197
24198    /**
24199     * Prepare app data for the given app.
24200     * <p>
24201     * Verifies that directories exist and that ownership and labeling is
24202     * correct for all installed apps. If there is an ownership mismatch, this
24203     * will try recovering system apps by wiping data; third-party app data is
24204     * left intact.
24205     */
24206    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
24207        if (pkg == null) {
24208            Slog.wtf(TAG, "Package was null!", new Throwable());
24209            return;
24210        }
24211        prepareAppDataLeafLIF(pkg, userId, flags);
24212        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
24213        for (int i = 0; i < childCount; i++) {
24214            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
24215        }
24216    }
24217
24218    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
24219            boolean maybeMigrateAppData) {
24220        prepareAppDataLIF(pkg, userId, flags);
24221
24222        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
24223            // We may have just shuffled around app data directories, so
24224            // prepare them one more time
24225            prepareAppDataLIF(pkg, userId, flags);
24226        }
24227    }
24228
24229    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
24230        if (DEBUG_APP_DATA) {
24231            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
24232                    + Integer.toHexString(flags));
24233        }
24234
24235        final String volumeUuid = pkg.volumeUuid;
24236        final String packageName = pkg.packageName;
24237        final ApplicationInfo app = pkg.applicationInfo;
24238        final int appId = UserHandle.getAppId(app.uid);
24239
24240        Preconditions.checkNotNull(app.seInfo);
24241
24242        long ceDataInode = -1;
24243        try {
24244            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
24245                    appId, app.seInfo, app.targetSdkVersion);
24246        } catch (InstallerException e) {
24247            if (app.isSystemApp()) {
24248                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
24249                        + ", but trying to recover: " + e);
24250                destroyAppDataLeafLIF(pkg, userId, flags);
24251                try {
24252                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
24253                            appId, app.seInfo, app.targetSdkVersion);
24254                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
24255                } catch (InstallerException e2) {
24256                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
24257                }
24258            } else {
24259                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
24260            }
24261        }
24262
24263        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
24264            // TODO: mark this structure as dirty so we persist it!
24265            synchronized (mPackages) {
24266                final PackageSetting ps = mSettings.mPackages.get(packageName);
24267                if (ps != null) {
24268                    ps.setCeDataInode(ceDataInode, userId);
24269                }
24270            }
24271        }
24272
24273        prepareAppDataContentsLeafLIF(pkg, userId, flags);
24274    }
24275
24276    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
24277        if (pkg == null) {
24278            Slog.wtf(TAG, "Package was null!", new Throwable());
24279            return;
24280        }
24281        prepareAppDataContentsLeafLIF(pkg, userId, flags);
24282        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
24283        for (int i = 0; i < childCount; i++) {
24284            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
24285        }
24286    }
24287
24288    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
24289        final String volumeUuid = pkg.volumeUuid;
24290        final String packageName = pkg.packageName;
24291        final ApplicationInfo app = pkg.applicationInfo;
24292
24293        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
24294            // Create a native library symlink only if we have native libraries
24295            // and if the native libraries are 32 bit libraries. We do not provide
24296            // this symlink for 64 bit libraries.
24297            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
24298                final String nativeLibPath = app.nativeLibraryDir;
24299                try {
24300                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
24301                            nativeLibPath, userId);
24302                } catch (InstallerException e) {
24303                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
24304                }
24305            }
24306        }
24307    }
24308
24309    /**
24310     * For system apps on non-FBE devices, this method migrates any existing
24311     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
24312     * requested by the app.
24313     */
24314    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
24315        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
24316                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
24317            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
24318                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
24319            try {
24320                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
24321                        storageTarget);
24322            } catch (InstallerException e) {
24323                logCriticalInfo(Log.WARN,
24324                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
24325            }
24326            return true;
24327        } else {
24328            return false;
24329        }
24330    }
24331
24332    public PackageFreezer freezePackage(String packageName, String killReason) {
24333        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
24334    }
24335
24336    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
24337        return new PackageFreezer(packageName, userId, killReason);
24338    }
24339
24340    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
24341            String killReason) {
24342        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
24343    }
24344
24345    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
24346            String killReason) {
24347        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
24348            return new PackageFreezer();
24349        } else {
24350            return freezePackage(packageName, userId, killReason);
24351        }
24352    }
24353
24354    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
24355            String killReason) {
24356        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
24357    }
24358
24359    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
24360            String killReason) {
24361        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
24362            return new PackageFreezer();
24363        } else {
24364            return freezePackage(packageName, userId, killReason);
24365        }
24366    }
24367
24368    /**
24369     * Class that freezes and kills the given package upon creation, and
24370     * unfreezes it upon closing. This is typically used when doing surgery on
24371     * app code/data to prevent the app from running while you're working.
24372     */
24373    private class PackageFreezer implements AutoCloseable {
24374        private final String mPackageName;
24375        private final PackageFreezer[] mChildren;
24376
24377        private final boolean mWeFroze;
24378
24379        private final AtomicBoolean mClosed = new AtomicBoolean();
24380        private final CloseGuard mCloseGuard = CloseGuard.get();
24381
24382        /**
24383         * Create and return a stub freezer that doesn't actually do anything,
24384         * typically used when someone requested
24385         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
24386         * {@link PackageManager#DELETE_DONT_KILL_APP}.
24387         */
24388        public PackageFreezer() {
24389            mPackageName = null;
24390            mChildren = null;
24391            mWeFroze = false;
24392            mCloseGuard.open("close");
24393        }
24394
24395        public PackageFreezer(String packageName, int userId, String killReason) {
24396            synchronized (mPackages) {
24397                mPackageName = packageName;
24398                mWeFroze = mFrozenPackages.add(mPackageName);
24399
24400                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
24401                if (ps != null) {
24402                    killApplication(ps.name, ps.appId, userId, killReason);
24403                }
24404
24405                final PackageParser.Package p = mPackages.get(packageName);
24406                if (p != null && p.childPackages != null) {
24407                    final int N = p.childPackages.size();
24408                    mChildren = new PackageFreezer[N];
24409                    for (int i = 0; i < N; i++) {
24410                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
24411                                userId, killReason);
24412                    }
24413                } else {
24414                    mChildren = null;
24415                }
24416            }
24417            mCloseGuard.open("close");
24418        }
24419
24420        @Override
24421        protected void finalize() throws Throwable {
24422            try {
24423                if (mCloseGuard != null) {
24424                    mCloseGuard.warnIfOpen();
24425                }
24426
24427                close();
24428            } finally {
24429                super.finalize();
24430            }
24431        }
24432
24433        @Override
24434        public void close() {
24435            mCloseGuard.close();
24436            if (mClosed.compareAndSet(false, true)) {
24437                synchronized (mPackages) {
24438                    if (mWeFroze) {
24439                        mFrozenPackages.remove(mPackageName);
24440                    }
24441
24442                    if (mChildren != null) {
24443                        for (PackageFreezer freezer : mChildren) {
24444                            freezer.close();
24445                        }
24446                    }
24447                }
24448            }
24449        }
24450    }
24451
24452    /**
24453     * Verify that given package is currently frozen.
24454     */
24455    private void checkPackageFrozen(String packageName) {
24456        synchronized (mPackages) {
24457            if (!mFrozenPackages.contains(packageName)) {
24458                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
24459            }
24460        }
24461    }
24462
24463    @Override
24464    public int movePackage(final String packageName, final String volumeUuid) {
24465        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
24466
24467        final int callingUid = Binder.getCallingUid();
24468        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
24469        final int moveId = mNextMoveId.getAndIncrement();
24470        mHandler.post(new Runnable() {
24471            @Override
24472            public void run() {
24473                try {
24474                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
24475                } catch (PackageManagerException e) {
24476                    Slog.w(TAG, "Failed to move " + packageName, e);
24477                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
24478                }
24479            }
24480        });
24481        return moveId;
24482    }
24483
24484    private void movePackageInternal(final String packageName, final String volumeUuid,
24485            final int moveId, final int callingUid, UserHandle user)
24486                    throws PackageManagerException {
24487        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24488        final PackageManager pm = mContext.getPackageManager();
24489
24490        final boolean currentAsec;
24491        final String currentVolumeUuid;
24492        final File codeFile;
24493        final String installerPackageName;
24494        final String packageAbiOverride;
24495        final int appId;
24496        final String seinfo;
24497        final String label;
24498        final int targetSdkVersion;
24499        final PackageFreezer freezer;
24500        final int[] installedUserIds;
24501
24502        // reader
24503        synchronized (mPackages) {
24504            final PackageParser.Package pkg = mPackages.get(packageName);
24505            final PackageSetting ps = mSettings.mPackages.get(packageName);
24506            if (pkg == null
24507                    || ps == null
24508                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
24509                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
24510            }
24511            if (pkg.applicationInfo.isSystemApp()) {
24512                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
24513                        "Cannot move system application");
24514            }
24515
24516            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
24517            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
24518                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
24519            if (isInternalStorage && !allow3rdPartyOnInternal) {
24520                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
24521                        "3rd party apps are not allowed on internal storage");
24522            }
24523
24524            if (pkg.applicationInfo.isExternalAsec()) {
24525                currentAsec = true;
24526                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
24527            } else if (pkg.applicationInfo.isForwardLocked()) {
24528                currentAsec = true;
24529                currentVolumeUuid = "forward_locked";
24530            } else {
24531                currentAsec = false;
24532                currentVolumeUuid = ps.volumeUuid;
24533
24534                final File probe = new File(pkg.codePath);
24535                final File probeOat = new File(probe, "oat");
24536                if (!probe.isDirectory() || !probeOat.isDirectory()) {
24537                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24538                            "Move only supported for modern cluster style installs");
24539                }
24540            }
24541
24542            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
24543                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24544                        "Package already moved to " + volumeUuid);
24545            }
24546            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
24547                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
24548                        "Device admin cannot be moved");
24549            }
24550
24551            if (mFrozenPackages.contains(packageName)) {
24552                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
24553                        "Failed to move already frozen package");
24554            }
24555
24556            codeFile = new File(pkg.codePath);
24557            installerPackageName = ps.installerPackageName;
24558            packageAbiOverride = ps.cpuAbiOverrideString;
24559            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
24560            seinfo = pkg.applicationInfo.seInfo;
24561            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
24562            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
24563            freezer = freezePackage(packageName, "movePackageInternal");
24564            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
24565        }
24566
24567        final Bundle extras = new Bundle();
24568        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
24569        extras.putString(Intent.EXTRA_TITLE, label);
24570        mMoveCallbacks.notifyCreated(moveId, extras);
24571
24572        int installFlags;
24573        final boolean moveCompleteApp;
24574        final File measurePath;
24575
24576        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
24577            installFlags = INSTALL_INTERNAL;
24578            moveCompleteApp = !currentAsec;
24579            measurePath = Environment.getDataAppDirectory(volumeUuid);
24580        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
24581            installFlags = INSTALL_EXTERNAL;
24582            moveCompleteApp = false;
24583            measurePath = storage.getPrimaryPhysicalVolume().getPath();
24584        } else {
24585            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
24586            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
24587                    || !volume.isMountedWritable()) {
24588                freezer.close();
24589                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24590                        "Move location not mounted private volume");
24591            }
24592
24593            Preconditions.checkState(!currentAsec);
24594
24595            installFlags = INSTALL_INTERNAL;
24596            moveCompleteApp = true;
24597            measurePath = Environment.getDataAppDirectory(volumeUuid);
24598        }
24599
24600        // If we're moving app data around, we need all the users unlocked
24601        if (moveCompleteApp) {
24602            for (int userId : installedUserIds) {
24603                if (StorageManager.isFileEncryptedNativeOrEmulated()
24604                        && !StorageManager.isUserKeyUnlocked(userId)) {
24605                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
24606                            "User " + userId + " must be unlocked");
24607                }
24608            }
24609        }
24610
24611        final PackageStats stats = new PackageStats(null, -1);
24612        synchronized (mInstaller) {
24613            for (int userId : installedUserIds) {
24614                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
24615                    freezer.close();
24616                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24617                            "Failed to measure package size");
24618                }
24619            }
24620        }
24621
24622        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
24623                + stats.dataSize);
24624
24625        final long startFreeBytes = measurePath.getUsableSpace();
24626        final long sizeBytes;
24627        if (moveCompleteApp) {
24628            sizeBytes = stats.codeSize + stats.dataSize;
24629        } else {
24630            sizeBytes = stats.codeSize;
24631        }
24632
24633        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
24634            freezer.close();
24635            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24636                    "Not enough free space to move");
24637        }
24638
24639        mMoveCallbacks.notifyStatusChanged(moveId, 10);
24640
24641        final CountDownLatch installedLatch = new CountDownLatch(1);
24642        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
24643            @Override
24644            public void onUserActionRequired(Intent intent) throws RemoteException {
24645                throw new IllegalStateException();
24646            }
24647
24648            @Override
24649            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
24650                    Bundle extras) throws RemoteException {
24651                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
24652                        + PackageManager.installStatusToString(returnCode, msg));
24653
24654                installedLatch.countDown();
24655                freezer.close();
24656
24657                final int status = PackageManager.installStatusToPublicStatus(returnCode);
24658                switch (status) {
24659                    case PackageInstaller.STATUS_SUCCESS:
24660                        mMoveCallbacks.notifyStatusChanged(moveId,
24661                                PackageManager.MOVE_SUCCEEDED);
24662                        break;
24663                    case PackageInstaller.STATUS_FAILURE_STORAGE:
24664                        mMoveCallbacks.notifyStatusChanged(moveId,
24665                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
24666                        break;
24667                    default:
24668                        mMoveCallbacks.notifyStatusChanged(moveId,
24669                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
24670                        break;
24671                }
24672            }
24673        };
24674
24675        final MoveInfo move;
24676        if (moveCompleteApp) {
24677            // Kick off a thread to report progress estimates
24678            new Thread() {
24679                @Override
24680                public void run() {
24681                    while (true) {
24682                        try {
24683                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
24684                                break;
24685                            }
24686                        } catch (InterruptedException ignored) {
24687                        }
24688
24689                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
24690                        final int progress = 10 + (int) MathUtils.constrain(
24691                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
24692                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
24693                    }
24694                }
24695            }.start();
24696
24697            final String dataAppName = codeFile.getName();
24698            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
24699                    dataAppName, appId, seinfo, targetSdkVersion);
24700        } else {
24701            move = null;
24702        }
24703
24704        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
24705
24706        final Message msg = mHandler.obtainMessage(INIT_COPY);
24707        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
24708        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
24709                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
24710                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
24711                PackageManager.INSTALL_REASON_UNKNOWN);
24712        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
24713        msg.obj = params;
24714
24715        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
24716                System.identityHashCode(msg.obj));
24717        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
24718                System.identityHashCode(msg.obj));
24719
24720        mHandler.sendMessage(msg);
24721    }
24722
24723    @Override
24724    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
24725        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
24726
24727        final int realMoveId = mNextMoveId.getAndIncrement();
24728        final Bundle extras = new Bundle();
24729        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
24730        mMoveCallbacks.notifyCreated(realMoveId, extras);
24731
24732        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
24733            @Override
24734            public void onCreated(int moveId, Bundle extras) {
24735                // Ignored
24736            }
24737
24738            @Override
24739            public void onStatusChanged(int moveId, int status, long estMillis) {
24740                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
24741            }
24742        };
24743
24744        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24745        storage.setPrimaryStorageUuid(volumeUuid, callback);
24746        return realMoveId;
24747    }
24748
24749    @Override
24750    public int getMoveStatus(int moveId) {
24751        mContext.enforceCallingOrSelfPermission(
24752                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24753        return mMoveCallbacks.mLastStatus.get(moveId);
24754    }
24755
24756    @Override
24757    public void registerMoveCallback(IPackageMoveObserver callback) {
24758        mContext.enforceCallingOrSelfPermission(
24759                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24760        mMoveCallbacks.register(callback);
24761    }
24762
24763    @Override
24764    public void unregisterMoveCallback(IPackageMoveObserver callback) {
24765        mContext.enforceCallingOrSelfPermission(
24766                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24767        mMoveCallbacks.unregister(callback);
24768    }
24769
24770    @Override
24771    public boolean setInstallLocation(int loc) {
24772        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
24773                null);
24774        if (getInstallLocation() == loc) {
24775            return true;
24776        }
24777        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
24778                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
24779            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
24780                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
24781            return true;
24782        }
24783        return false;
24784   }
24785
24786    @Override
24787    public int getInstallLocation() {
24788        // allow instant app access
24789        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
24790                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
24791                PackageHelper.APP_INSTALL_AUTO);
24792    }
24793
24794    /** Called by UserManagerService */
24795    void cleanUpUser(UserManagerService userManager, int userHandle) {
24796        synchronized (mPackages) {
24797            mDirtyUsers.remove(userHandle);
24798            mUserNeedsBadging.delete(userHandle);
24799            mSettings.removeUserLPw(userHandle);
24800            mPendingBroadcasts.remove(userHandle);
24801            mInstantAppRegistry.onUserRemovedLPw(userHandle);
24802            removeUnusedPackagesLPw(userManager, userHandle);
24803        }
24804    }
24805
24806    /**
24807     * We're removing userHandle and would like to remove any downloaded packages
24808     * that are no longer in use by any other user.
24809     * @param userHandle the user being removed
24810     */
24811    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
24812        final boolean DEBUG_CLEAN_APKS = false;
24813        int [] users = userManager.getUserIds();
24814        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
24815        while (psit.hasNext()) {
24816            PackageSetting ps = psit.next();
24817            if (ps.pkg == null) {
24818                continue;
24819            }
24820            final String packageName = ps.pkg.packageName;
24821            // Skip over if system app
24822            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
24823                continue;
24824            }
24825            if (DEBUG_CLEAN_APKS) {
24826                Slog.i(TAG, "Checking package " + packageName);
24827            }
24828            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
24829            if (keep) {
24830                if (DEBUG_CLEAN_APKS) {
24831                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
24832                }
24833            } else {
24834                for (int i = 0; i < users.length; i++) {
24835                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
24836                        keep = true;
24837                        if (DEBUG_CLEAN_APKS) {
24838                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
24839                                    + users[i]);
24840                        }
24841                        break;
24842                    }
24843                }
24844            }
24845            if (!keep) {
24846                if (DEBUG_CLEAN_APKS) {
24847                    Slog.i(TAG, "  Removing package " + packageName);
24848                }
24849                mHandler.post(new Runnable() {
24850                    public void run() {
24851                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24852                                userHandle, 0);
24853                    } //end run
24854                });
24855            }
24856        }
24857    }
24858
24859    /** Called by UserManagerService */
24860    void createNewUser(int userId, String[] disallowedPackages) {
24861        synchronized (mInstallLock) {
24862            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
24863        }
24864        synchronized (mPackages) {
24865            scheduleWritePackageRestrictionsLocked(userId);
24866            scheduleWritePackageListLocked(userId);
24867            applyFactoryDefaultBrowserLPw(userId);
24868            primeDomainVerificationsLPw(userId);
24869        }
24870    }
24871
24872    void onNewUserCreated(final int userId) {
24873        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
24874        // If permission review for legacy apps is required, we represent
24875        // dagerous permissions for such apps as always granted runtime
24876        // permissions to keep per user flag state whether review is needed.
24877        // Hence, if a new user is added we have to propagate dangerous
24878        // permission grants for these legacy apps.
24879        if (mPermissionReviewRequired) {
24880            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
24881                    | UPDATE_PERMISSIONS_REPLACE_ALL);
24882        }
24883    }
24884
24885    @Override
24886    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
24887        mContext.enforceCallingOrSelfPermission(
24888                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
24889                "Only package verification agents can read the verifier device identity");
24890
24891        synchronized (mPackages) {
24892            return mSettings.getVerifierDeviceIdentityLPw();
24893        }
24894    }
24895
24896    @Override
24897    public void setPermissionEnforced(String permission, boolean enforced) {
24898        // TODO: Now that we no longer change GID for storage, this should to away.
24899        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
24900                "setPermissionEnforced");
24901        if (READ_EXTERNAL_STORAGE.equals(permission)) {
24902            synchronized (mPackages) {
24903                if (mSettings.mReadExternalStorageEnforced == null
24904                        || mSettings.mReadExternalStorageEnforced != enforced) {
24905                    mSettings.mReadExternalStorageEnforced = enforced;
24906                    mSettings.writeLPr();
24907                }
24908            }
24909            // kill any non-foreground processes so we restart them and
24910            // grant/revoke the GID.
24911            final IActivityManager am = ActivityManager.getService();
24912            if (am != null) {
24913                final long token = Binder.clearCallingIdentity();
24914                try {
24915                    am.killProcessesBelowForeground("setPermissionEnforcement");
24916                } catch (RemoteException e) {
24917                } finally {
24918                    Binder.restoreCallingIdentity(token);
24919                }
24920            }
24921        } else {
24922            throw new IllegalArgumentException("No selective enforcement for " + permission);
24923        }
24924    }
24925
24926    @Override
24927    @Deprecated
24928    public boolean isPermissionEnforced(String permission) {
24929        // allow instant applications
24930        return true;
24931    }
24932
24933    @Override
24934    public boolean isStorageLow() {
24935        // allow instant applications
24936        final long token = Binder.clearCallingIdentity();
24937        try {
24938            final DeviceStorageMonitorInternal
24939                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
24940            if (dsm != null) {
24941                return dsm.isMemoryLow();
24942            } else {
24943                return false;
24944            }
24945        } finally {
24946            Binder.restoreCallingIdentity(token);
24947        }
24948    }
24949
24950    @Override
24951    public IPackageInstaller getPackageInstaller() {
24952        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24953            return null;
24954        }
24955        return mInstallerService;
24956    }
24957
24958    private boolean userNeedsBadging(int userId) {
24959        int index = mUserNeedsBadging.indexOfKey(userId);
24960        if (index < 0) {
24961            final UserInfo userInfo;
24962            final long token = Binder.clearCallingIdentity();
24963            try {
24964                userInfo = sUserManager.getUserInfo(userId);
24965            } finally {
24966                Binder.restoreCallingIdentity(token);
24967            }
24968            final boolean b;
24969            if (userInfo != null && userInfo.isManagedProfile()) {
24970                b = true;
24971            } else {
24972                b = false;
24973            }
24974            mUserNeedsBadging.put(userId, b);
24975            return b;
24976        }
24977        return mUserNeedsBadging.valueAt(index);
24978    }
24979
24980    @Override
24981    public KeySet getKeySetByAlias(String packageName, String alias) {
24982        if (packageName == null || alias == null) {
24983            return null;
24984        }
24985        synchronized(mPackages) {
24986            final PackageParser.Package pkg = mPackages.get(packageName);
24987            if (pkg == null) {
24988                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24989                throw new IllegalArgumentException("Unknown package: " + packageName);
24990            }
24991            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24992            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24993                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24994                throw new IllegalArgumentException("Unknown package: " + packageName);
24995            }
24996            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24997            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24998        }
24999    }
25000
25001    @Override
25002    public KeySet getSigningKeySet(String packageName) {
25003        if (packageName == null) {
25004            return null;
25005        }
25006        synchronized(mPackages) {
25007            final int callingUid = Binder.getCallingUid();
25008            final int callingUserId = UserHandle.getUserId(callingUid);
25009            final PackageParser.Package pkg = mPackages.get(packageName);
25010            if (pkg == null) {
25011                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
25012                throw new IllegalArgumentException("Unknown package: " + packageName);
25013            }
25014            final PackageSetting ps = (PackageSetting) pkg.mExtras;
25015            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
25016                // filter and pretend the package doesn't exist
25017                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
25018                        + ", uid:" + callingUid);
25019                throw new IllegalArgumentException("Unknown package: " + packageName);
25020            }
25021            if (pkg.applicationInfo.uid != callingUid
25022                    && Process.SYSTEM_UID != callingUid) {
25023                throw new SecurityException("May not access signing KeySet of other apps.");
25024            }
25025            KeySetManagerService ksms = mSettings.mKeySetManagerService;
25026            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
25027        }
25028    }
25029
25030    @Override
25031    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
25032        final int callingUid = Binder.getCallingUid();
25033        if (getInstantAppPackageName(callingUid) != null) {
25034            return false;
25035        }
25036        if (packageName == null || ks == null) {
25037            return false;
25038        }
25039        synchronized(mPackages) {
25040            final PackageParser.Package pkg = mPackages.get(packageName);
25041            if (pkg == null
25042                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
25043                            UserHandle.getUserId(callingUid))) {
25044                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
25045                throw new IllegalArgumentException("Unknown package: " + packageName);
25046            }
25047            IBinder ksh = ks.getToken();
25048            if (ksh instanceof KeySetHandle) {
25049                KeySetManagerService ksms = mSettings.mKeySetManagerService;
25050                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
25051            }
25052            return false;
25053        }
25054    }
25055
25056    @Override
25057    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
25058        final int callingUid = Binder.getCallingUid();
25059        if (getInstantAppPackageName(callingUid) != null) {
25060            return false;
25061        }
25062        if (packageName == null || ks == null) {
25063            return false;
25064        }
25065        synchronized(mPackages) {
25066            final PackageParser.Package pkg = mPackages.get(packageName);
25067            if (pkg == null
25068                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
25069                            UserHandle.getUserId(callingUid))) {
25070                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
25071                throw new IllegalArgumentException("Unknown package: " + packageName);
25072            }
25073            IBinder ksh = ks.getToken();
25074            if (ksh instanceof KeySetHandle) {
25075                KeySetManagerService ksms = mSettings.mKeySetManagerService;
25076                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
25077            }
25078            return false;
25079        }
25080    }
25081
25082    private void deletePackageIfUnusedLPr(final String packageName) {
25083        PackageSetting ps = mSettings.mPackages.get(packageName);
25084        if (ps == null) {
25085            return;
25086        }
25087        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
25088            // TODO Implement atomic delete if package is unused
25089            // It is currently possible that the package will be deleted even if it is installed
25090            // after this method returns.
25091            mHandler.post(new Runnable() {
25092                public void run() {
25093                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
25094                            0, PackageManager.DELETE_ALL_USERS);
25095                }
25096            });
25097        }
25098    }
25099
25100    /**
25101     * Check and throw if the given before/after packages would be considered a
25102     * downgrade.
25103     */
25104    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
25105            throws PackageManagerException {
25106        if (after.versionCode < before.mVersionCode) {
25107            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
25108                    "Update version code " + after.versionCode + " is older than current "
25109                    + before.mVersionCode);
25110        } else if (after.versionCode == before.mVersionCode) {
25111            if (after.baseRevisionCode < before.baseRevisionCode) {
25112                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
25113                        "Update base revision code " + after.baseRevisionCode
25114                        + " is older than current " + before.baseRevisionCode);
25115            }
25116
25117            if (!ArrayUtils.isEmpty(after.splitNames)) {
25118                for (int i = 0; i < after.splitNames.length; i++) {
25119                    final String splitName = after.splitNames[i];
25120                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
25121                    if (j != -1) {
25122                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
25123                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
25124                                    "Update split " + splitName + " revision code "
25125                                    + after.splitRevisionCodes[i] + " is older than current "
25126                                    + before.splitRevisionCodes[j]);
25127                        }
25128                    }
25129                }
25130            }
25131        }
25132    }
25133
25134    private static class MoveCallbacks extends Handler {
25135        private static final int MSG_CREATED = 1;
25136        private static final int MSG_STATUS_CHANGED = 2;
25137
25138        private final RemoteCallbackList<IPackageMoveObserver>
25139                mCallbacks = new RemoteCallbackList<>();
25140
25141        private final SparseIntArray mLastStatus = new SparseIntArray();
25142
25143        public MoveCallbacks(Looper looper) {
25144            super(looper);
25145        }
25146
25147        public void register(IPackageMoveObserver callback) {
25148            mCallbacks.register(callback);
25149        }
25150
25151        public void unregister(IPackageMoveObserver callback) {
25152            mCallbacks.unregister(callback);
25153        }
25154
25155        @Override
25156        public void handleMessage(Message msg) {
25157            final SomeArgs args = (SomeArgs) msg.obj;
25158            final int n = mCallbacks.beginBroadcast();
25159            for (int i = 0; i < n; i++) {
25160                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
25161                try {
25162                    invokeCallback(callback, msg.what, args);
25163                } catch (RemoteException ignored) {
25164                }
25165            }
25166            mCallbacks.finishBroadcast();
25167            args.recycle();
25168        }
25169
25170        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
25171                throws RemoteException {
25172            switch (what) {
25173                case MSG_CREATED: {
25174                    callback.onCreated(args.argi1, (Bundle) args.arg2);
25175                    break;
25176                }
25177                case MSG_STATUS_CHANGED: {
25178                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
25179                    break;
25180                }
25181            }
25182        }
25183
25184        private void notifyCreated(int moveId, Bundle extras) {
25185            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
25186
25187            final SomeArgs args = SomeArgs.obtain();
25188            args.argi1 = moveId;
25189            args.arg2 = extras;
25190            obtainMessage(MSG_CREATED, args).sendToTarget();
25191        }
25192
25193        private void notifyStatusChanged(int moveId, int status) {
25194            notifyStatusChanged(moveId, status, -1);
25195        }
25196
25197        private void notifyStatusChanged(int moveId, int status, long estMillis) {
25198            Slog.v(TAG, "Move " + moveId + " status " + status);
25199
25200            final SomeArgs args = SomeArgs.obtain();
25201            args.argi1 = moveId;
25202            args.argi2 = status;
25203            args.arg3 = estMillis;
25204            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
25205
25206            synchronized (mLastStatus) {
25207                mLastStatus.put(moveId, status);
25208            }
25209        }
25210    }
25211
25212    private final static class OnPermissionChangeListeners extends Handler {
25213        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
25214
25215        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
25216                new RemoteCallbackList<>();
25217
25218        public OnPermissionChangeListeners(Looper looper) {
25219            super(looper);
25220        }
25221
25222        @Override
25223        public void handleMessage(Message msg) {
25224            switch (msg.what) {
25225                case MSG_ON_PERMISSIONS_CHANGED: {
25226                    final int uid = msg.arg1;
25227                    handleOnPermissionsChanged(uid);
25228                } break;
25229            }
25230        }
25231
25232        public void addListenerLocked(IOnPermissionsChangeListener listener) {
25233            mPermissionListeners.register(listener);
25234
25235        }
25236
25237        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
25238            mPermissionListeners.unregister(listener);
25239        }
25240
25241        public void onPermissionsChanged(int uid) {
25242            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
25243                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
25244            }
25245        }
25246
25247        private void handleOnPermissionsChanged(int uid) {
25248            final int count = mPermissionListeners.beginBroadcast();
25249            try {
25250                for (int i = 0; i < count; i++) {
25251                    IOnPermissionsChangeListener callback = mPermissionListeners
25252                            .getBroadcastItem(i);
25253                    try {
25254                        callback.onPermissionsChanged(uid);
25255                    } catch (RemoteException e) {
25256                        Log.e(TAG, "Permission listener is dead", e);
25257                    }
25258                }
25259            } finally {
25260                mPermissionListeners.finishBroadcast();
25261            }
25262        }
25263    }
25264
25265    private class PackageManagerNative extends IPackageManagerNative.Stub {
25266        @Override
25267        public String[] getNamesForUids(int[] uids) throws RemoteException {
25268            final String[] results = PackageManagerService.this.getNamesForUids(uids);
25269            // massage results so they can be parsed by the native binder
25270            for (int i = results.length - 1; i >= 0; --i) {
25271                if (results[i] == null) {
25272                    results[i] = "";
25273                }
25274            }
25275            return results;
25276        }
25277
25278        // NB: this differentiates between preloads and sideloads
25279        @Override
25280        public String getInstallerForPackage(String packageName) throws RemoteException {
25281            final String installerName = getInstallerPackageName(packageName);
25282            if (!TextUtils.isEmpty(installerName)) {
25283                return installerName;
25284            }
25285            // differentiate between preload and sideload
25286            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
25287            ApplicationInfo appInfo = getApplicationInfo(packageName,
25288                                    /*flags*/ 0,
25289                                    /*userId*/ callingUser);
25290            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
25291                return "preload";
25292            }
25293            return "";
25294        }
25295
25296        @Override
25297        public int getVersionCodeForPackage(String packageName) throws RemoteException {
25298            try {
25299                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
25300                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
25301                if (pInfo != null) {
25302                    return pInfo.versionCode;
25303                }
25304            } catch (Exception e) {
25305            }
25306            return 0;
25307        }
25308    }
25309
25310    private class PackageManagerInternalImpl extends PackageManagerInternal {
25311        @Override
25312        public void setLocationPackagesProvider(PackagesProvider provider) {
25313            synchronized (mPackages) {
25314                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
25315            }
25316        }
25317
25318        @Override
25319        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
25320            synchronized (mPackages) {
25321                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
25322            }
25323        }
25324
25325        @Override
25326        public void setSmsAppPackagesProvider(PackagesProvider provider) {
25327            synchronized (mPackages) {
25328                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
25329            }
25330        }
25331
25332        @Override
25333        public void setDialerAppPackagesProvider(PackagesProvider provider) {
25334            synchronized (mPackages) {
25335                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
25336            }
25337        }
25338
25339        @Override
25340        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
25341            synchronized (mPackages) {
25342                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
25343            }
25344        }
25345
25346        @Override
25347        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
25348            synchronized (mPackages) {
25349                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
25350            }
25351        }
25352
25353        @Override
25354        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
25355            synchronized (mPackages) {
25356                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
25357                        packageName, userId);
25358            }
25359        }
25360
25361        @Override
25362        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
25363            synchronized (mPackages) {
25364                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
25365                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
25366                        packageName, userId);
25367            }
25368        }
25369
25370        @Override
25371        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
25372            synchronized (mPackages) {
25373                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
25374                        packageName, userId);
25375            }
25376        }
25377
25378        @Override
25379        public void setKeepUninstalledPackages(final List<String> packageList) {
25380            Preconditions.checkNotNull(packageList);
25381            List<String> removedFromList = null;
25382            synchronized (mPackages) {
25383                if (mKeepUninstalledPackages != null) {
25384                    final int packagesCount = mKeepUninstalledPackages.size();
25385                    for (int i = 0; i < packagesCount; i++) {
25386                        String oldPackage = mKeepUninstalledPackages.get(i);
25387                        if (packageList != null && packageList.contains(oldPackage)) {
25388                            continue;
25389                        }
25390                        if (removedFromList == null) {
25391                            removedFromList = new ArrayList<>();
25392                        }
25393                        removedFromList.add(oldPackage);
25394                    }
25395                }
25396                mKeepUninstalledPackages = new ArrayList<>(packageList);
25397                if (removedFromList != null) {
25398                    final int removedCount = removedFromList.size();
25399                    for (int i = 0; i < removedCount; i++) {
25400                        deletePackageIfUnusedLPr(removedFromList.get(i));
25401                    }
25402                }
25403            }
25404        }
25405
25406        @Override
25407        public boolean isPermissionsReviewRequired(String packageName, int userId) {
25408            synchronized (mPackages) {
25409                // If we do not support permission review, done.
25410                if (!mPermissionReviewRequired) {
25411                    return false;
25412                }
25413
25414                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
25415                if (packageSetting == null) {
25416                    return false;
25417                }
25418
25419                // Permission review applies only to apps not supporting the new permission model.
25420                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
25421                    return false;
25422                }
25423
25424                // Legacy apps have the permission and get user consent on launch.
25425                PermissionsState permissionsState = packageSetting.getPermissionsState();
25426                return permissionsState.isPermissionReviewRequired(userId);
25427            }
25428        }
25429
25430        @Override
25431        public PackageInfo getPackageInfo(
25432                String packageName, int flags, int filterCallingUid, int userId) {
25433            return PackageManagerService.this
25434                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
25435                            flags, filterCallingUid, userId);
25436        }
25437
25438        @Override
25439        public ApplicationInfo getApplicationInfo(
25440                String packageName, int flags, int filterCallingUid, int userId) {
25441            return PackageManagerService.this
25442                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
25443        }
25444
25445        @Override
25446        public ActivityInfo getActivityInfo(
25447                ComponentName component, int flags, int filterCallingUid, int userId) {
25448            return PackageManagerService.this
25449                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
25450        }
25451
25452        @Override
25453        public List<ResolveInfo> queryIntentActivities(
25454                Intent intent, int flags, int filterCallingUid, int userId) {
25455            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
25456            return PackageManagerService.this
25457                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
25458                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
25459        }
25460
25461        @Override
25462        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
25463                int userId) {
25464            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
25465        }
25466
25467        @Override
25468        public void setDeviceAndProfileOwnerPackages(
25469                int deviceOwnerUserId, String deviceOwnerPackage,
25470                SparseArray<String> profileOwnerPackages) {
25471            mProtectedPackages.setDeviceAndProfileOwnerPackages(
25472                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
25473        }
25474
25475        @Override
25476        public boolean isPackageDataProtected(int userId, String packageName) {
25477            return mProtectedPackages.isPackageDataProtected(userId, packageName);
25478        }
25479
25480        @Override
25481        public boolean isPackageEphemeral(int userId, String packageName) {
25482            synchronized (mPackages) {
25483                final PackageSetting ps = mSettings.mPackages.get(packageName);
25484                return ps != null ? ps.getInstantApp(userId) : false;
25485            }
25486        }
25487
25488        @Override
25489        public boolean wasPackageEverLaunched(String packageName, int userId) {
25490            synchronized (mPackages) {
25491                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
25492            }
25493        }
25494
25495        @Override
25496        public void grantRuntimePermission(String packageName, String name, int userId,
25497                boolean overridePolicy) {
25498            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
25499                    overridePolicy);
25500        }
25501
25502        @Override
25503        public void revokeRuntimePermission(String packageName, String name, int userId,
25504                boolean overridePolicy) {
25505            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
25506                    overridePolicy);
25507        }
25508
25509        @Override
25510        public String getNameForUid(int uid) {
25511            return PackageManagerService.this.getNameForUid(uid);
25512        }
25513
25514        @Override
25515        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
25516                Intent origIntent, String resolvedType, String callingPackage,
25517                Bundle verificationBundle, int userId) {
25518            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
25519                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
25520                    userId);
25521        }
25522
25523        @Override
25524        public void grantEphemeralAccess(int userId, Intent intent,
25525                int targetAppId, int ephemeralAppId) {
25526            synchronized (mPackages) {
25527                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
25528                        targetAppId, ephemeralAppId);
25529            }
25530        }
25531
25532        @Override
25533        public boolean isInstantAppInstallerComponent(ComponentName component) {
25534            synchronized (mPackages) {
25535                return mInstantAppInstallerActivity != null
25536                        && mInstantAppInstallerActivity.getComponentName().equals(component);
25537            }
25538        }
25539
25540        @Override
25541        public void pruneInstantApps() {
25542            mInstantAppRegistry.pruneInstantApps();
25543        }
25544
25545        @Override
25546        public String getSetupWizardPackageName() {
25547            return mSetupWizardPackage;
25548        }
25549
25550        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
25551            if (policy != null) {
25552                mExternalSourcesPolicy = policy;
25553            }
25554        }
25555
25556        @Override
25557        public boolean isPackagePersistent(String packageName) {
25558            synchronized (mPackages) {
25559                PackageParser.Package pkg = mPackages.get(packageName);
25560                return pkg != null
25561                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
25562                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
25563                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
25564                        : false;
25565            }
25566        }
25567
25568        @Override
25569        public List<PackageInfo> getOverlayPackages(int userId) {
25570            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
25571            synchronized (mPackages) {
25572                for (PackageParser.Package p : mPackages.values()) {
25573                    if (p.mOverlayTarget != null) {
25574                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
25575                        if (pkg != null) {
25576                            overlayPackages.add(pkg);
25577                        }
25578                    }
25579                }
25580            }
25581            return overlayPackages;
25582        }
25583
25584        @Override
25585        public List<String> getTargetPackageNames(int userId) {
25586            List<String> targetPackages = new ArrayList<>();
25587            synchronized (mPackages) {
25588                for (PackageParser.Package p : mPackages.values()) {
25589                    if (p.mOverlayTarget == null) {
25590                        targetPackages.add(p.packageName);
25591                    }
25592                }
25593            }
25594            return targetPackages;
25595        }
25596
25597        @Override
25598        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
25599                @Nullable List<String> overlayPackageNames) {
25600            synchronized (mPackages) {
25601                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
25602                    Slog.e(TAG, "failed to find package " + targetPackageName);
25603                    return false;
25604                }
25605                ArrayList<String> overlayPaths = null;
25606                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
25607                    final int N = overlayPackageNames.size();
25608                    overlayPaths = new ArrayList<>(N);
25609                    for (int i = 0; i < N; i++) {
25610                        final String packageName = overlayPackageNames.get(i);
25611                        final PackageParser.Package pkg = mPackages.get(packageName);
25612                        if (pkg == null) {
25613                            Slog.e(TAG, "failed to find package " + packageName);
25614                            return false;
25615                        }
25616                        overlayPaths.add(pkg.baseCodePath);
25617                    }
25618                }
25619
25620                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
25621                ps.setOverlayPaths(overlayPaths, userId);
25622                return true;
25623            }
25624        }
25625
25626        @Override
25627        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
25628                int flags, int userId) {
25629            return resolveIntentInternal(
25630                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
25631        }
25632
25633        @Override
25634        public ResolveInfo resolveService(Intent intent, String resolvedType,
25635                int flags, int userId, int callingUid) {
25636            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
25637        }
25638
25639        @Override
25640        public void addIsolatedUid(int isolatedUid, int ownerUid) {
25641            synchronized (mPackages) {
25642                mIsolatedOwners.put(isolatedUid, ownerUid);
25643            }
25644        }
25645
25646        @Override
25647        public void removeIsolatedUid(int isolatedUid) {
25648            synchronized (mPackages) {
25649                mIsolatedOwners.delete(isolatedUid);
25650            }
25651        }
25652
25653        @Override
25654        public int getUidTargetSdkVersion(int uid) {
25655            synchronized (mPackages) {
25656                return getUidTargetSdkVersionLockedLPr(uid);
25657            }
25658        }
25659
25660        @Override
25661        public boolean canAccessInstantApps(int callingUid, int userId) {
25662            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
25663        }
25664
25665        @Override
25666        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
25667            synchronized (mPackages) {
25668                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
25669            }
25670        }
25671
25672        @Override
25673        public void notifyPackageUse(String packageName, int reason) {
25674            synchronized (mPackages) {
25675                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
25676            }
25677        }
25678    }
25679
25680    @Override
25681    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
25682        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
25683        synchronized (mPackages) {
25684            final long identity = Binder.clearCallingIdentity();
25685            try {
25686                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
25687                        packageNames, userId);
25688            } finally {
25689                Binder.restoreCallingIdentity(identity);
25690            }
25691        }
25692    }
25693
25694    @Override
25695    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
25696        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
25697        synchronized (mPackages) {
25698            final long identity = Binder.clearCallingIdentity();
25699            try {
25700                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
25701                        packageNames, userId);
25702            } finally {
25703                Binder.restoreCallingIdentity(identity);
25704            }
25705        }
25706    }
25707
25708    private static void enforceSystemOrPhoneCaller(String tag) {
25709        int callingUid = Binder.getCallingUid();
25710        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
25711            throw new SecurityException(
25712                    "Cannot call " + tag + " from UID " + callingUid);
25713        }
25714    }
25715
25716    boolean isHistoricalPackageUsageAvailable() {
25717        return mPackageUsage.isHistoricalPackageUsageAvailable();
25718    }
25719
25720    /**
25721     * Return a <b>copy</b> of the collection of packages known to the package manager.
25722     * @return A copy of the values of mPackages.
25723     */
25724    Collection<PackageParser.Package> getPackages() {
25725        synchronized (mPackages) {
25726            return new ArrayList<>(mPackages.values());
25727        }
25728    }
25729
25730    /**
25731     * Logs process start information (including base APK hash) to the security log.
25732     * @hide
25733     */
25734    @Override
25735    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
25736            String apkFile, int pid) {
25737        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25738            return;
25739        }
25740        if (!SecurityLog.isLoggingEnabled()) {
25741            return;
25742        }
25743        Bundle data = new Bundle();
25744        data.putLong("startTimestamp", System.currentTimeMillis());
25745        data.putString("processName", processName);
25746        data.putInt("uid", uid);
25747        data.putString("seinfo", seinfo);
25748        data.putString("apkFile", apkFile);
25749        data.putInt("pid", pid);
25750        Message msg = mProcessLoggingHandler.obtainMessage(
25751                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
25752        msg.setData(data);
25753        mProcessLoggingHandler.sendMessage(msg);
25754    }
25755
25756    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
25757        return mCompilerStats.getPackageStats(pkgName);
25758    }
25759
25760    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
25761        return getOrCreateCompilerPackageStats(pkg.packageName);
25762    }
25763
25764    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
25765        return mCompilerStats.getOrCreatePackageStats(pkgName);
25766    }
25767
25768    public void deleteCompilerPackageStats(String pkgName) {
25769        mCompilerStats.deletePackageStats(pkgName);
25770    }
25771
25772    @Override
25773    public int getInstallReason(String packageName, int userId) {
25774        final int callingUid = Binder.getCallingUid();
25775        enforceCrossUserPermission(callingUid, userId,
25776                true /* requireFullPermission */, false /* checkShell */,
25777                "get install reason");
25778        synchronized (mPackages) {
25779            final PackageSetting ps = mSettings.mPackages.get(packageName);
25780            if (filterAppAccessLPr(ps, callingUid, userId)) {
25781                return PackageManager.INSTALL_REASON_UNKNOWN;
25782            }
25783            if (ps != null) {
25784                return ps.getInstallReason(userId);
25785            }
25786        }
25787        return PackageManager.INSTALL_REASON_UNKNOWN;
25788    }
25789
25790    @Override
25791    public boolean canRequestPackageInstalls(String packageName, int userId) {
25792        return canRequestPackageInstallsInternal(packageName, 0, userId,
25793                true /* throwIfPermNotDeclared*/);
25794    }
25795
25796    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
25797            boolean throwIfPermNotDeclared) {
25798        int callingUid = Binder.getCallingUid();
25799        int uid = getPackageUid(packageName, 0, userId);
25800        if (callingUid != uid && callingUid != Process.ROOT_UID
25801                && callingUid != Process.SYSTEM_UID) {
25802            throw new SecurityException(
25803                    "Caller uid " + callingUid + " does not own package " + packageName);
25804        }
25805        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
25806        if (info == null) {
25807            return false;
25808        }
25809        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
25810            return false;
25811        }
25812        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
25813        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
25814        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
25815            if (throwIfPermNotDeclared) {
25816                throw new SecurityException("Need to declare " + appOpPermission
25817                        + " to call this api");
25818            } else {
25819                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
25820                return false;
25821            }
25822        }
25823        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
25824            return false;
25825        }
25826        if (mExternalSourcesPolicy != null) {
25827            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
25828            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
25829                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
25830            }
25831        }
25832        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
25833    }
25834
25835    @Override
25836    public ComponentName getInstantAppResolverSettingsComponent() {
25837        return mInstantAppResolverSettingsComponent;
25838    }
25839
25840    @Override
25841    public ComponentName getInstantAppInstallerComponent() {
25842        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25843            return null;
25844        }
25845        return mInstantAppInstallerActivity == null
25846                ? null : mInstantAppInstallerActivity.getComponentName();
25847    }
25848
25849    @Override
25850    public String getInstantAppAndroidId(String packageName, int userId) {
25851        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
25852                "getInstantAppAndroidId");
25853        enforceCrossUserPermission(Binder.getCallingUid(), userId,
25854                true /* requireFullPermission */, false /* checkShell */,
25855                "getInstantAppAndroidId");
25856        // Make sure the target is an Instant App.
25857        if (!isInstantApp(packageName, userId)) {
25858            return null;
25859        }
25860        synchronized (mPackages) {
25861            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
25862        }
25863    }
25864
25865    boolean canHaveOatDir(String packageName) {
25866        synchronized (mPackages) {
25867            PackageParser.Package p = mPackages.get(packageName);
25868            if (p == null) {
25869                return false;
25870            }
25871            return p.canHaveOatDir();
25872        }
25873    }
25874
25875    private String getOatDir(PackageParser.Package pkg) {
25876        if (!pkg.canHaveOatDir()) {
25877            return null;
25878        }
25879        File codePath = new File(pkg.codePath);
25880        if (codePath.isDirectory()) {
25881            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
25882        }
25883        return null;
25884    }
25885
25886    void deleteOatArtifactsOfPackage(String packageName) {
25887        final String[] instructionSets;
25888        final List<String> codePaths;
25889        final String oatDir;
25890        final PackageParser.Package pkg;
25891        synchronized (mPackages) {
25892            pkg = mPackages.get(packageName);
25893        }
25894        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
25895        codePaths = pkg.getAllCodePaths();
25896        oatDir = getOatDir(pkg);
25897
25898        for (String codePath : codePaths) {
25899            for (String isa : instructionSets) {
25900                try {
25901                    mInstaller.deleteOdex(codePath, isa, oatDir);
25902                } catch (InstallerException e) {
25903                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
25904                }
25905            }
25906        }
25907    }
25908
25909    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
25910        Set<String> unusedPackages = new HashSet<>();
25911        long currentTimeInMillis = System.currentTimeMillis();
25912        synchronized (mPackages) {
25913            for (PackageParser.Package pkg : mPackages.values()) {
25914                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
25915                if (ps == null) {
25916                    continue;
25917                }
25918                PackageDexUsage.PackageUseInfo packageUseInfo =
25919                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
25920                if (PackageManagerServiceUtils
25921                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
25922                                downgradeTimeThresholdMillis, packageUseInfo,
25923                                pkg.getLatestPackageUseTimeInMills(),
25924                                pkg.getLatestForegroundPackageUseTimeInMills())) {
25925                    unusedPackages.add(pkg.packageName);
25926                }
25927            }
25928        }
25929        return unusedPackages;
25930    }
25931}
25932
25933interface PackageSender {
25934    void sendPackageBroadcast(final String action, final String pkg,
25935        final Bundle extras, final int flags, final String targetPkg,
25936        final IIntentReceiver finishedReceiver, final int[] userIds);
25937    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
25938        boolean includeStopped, int appId, int... userIds);
25939}
25940